public static byte[] streamEncrypt(String message, SecretKey key, MessageDigest digest) throws Exception { byte[] data; Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); encCipher.init(Cipher.ENCRYPT_MODE, key); try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); DigestOutputStream dos = new DigestOutputStream(bos, digest); CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) { try (ObjectOutputStream oos = new ObjectOutputStream(cos)) { oos.writeObject(message); } data = bos.toByteArray(); } if (debug) { System.out.println(DatatypeConverter.printHexBinary(data)); } return data; }
public static boolean Verify(String jwt, String type) throws Exception { try{ Claims claims = Jwts.parser() .setSigningKey(DatatypeConverter.parseBase64Binary(Parameters.TOKENKEY)) .parseClaimsJws(jwt).getBody(); //verifica se o issuer é igual ao type return claims.getIssuer().equals(type); } catch (ExpiredJwtException | MalformedJwtException | SignatureException | UnsupportedJwtException | IllegalArgumentException e) { System.out.println(e.getMessage()); return false; } }
/** * Encodes the given image InputStream to a base64 coded string. * * @param is image InputStream to encode * @param type type of the image: jpeg, bmp, png, gif etc. * @return encoded string */ public static String encodeImg2String(InputStream is, String type) { String imageString = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { BufferedImage image = ImageIO.read(is); ImageIO.write(image, type, bos); byte[] imageBytes = bos.toByteArray(); imageString = DatatypeConverter.printBase64Binary(imageBytes); bos.close(); } catch (IOException ex) { LOGGER.error(ex.getMessage(), ex); } return imageString; }
@RequestMapping(value = "/get-data-to-sign", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public GetDataToSignResponse getDataToSign(Model model, @RequestBody @Valid DataToSignParams params, @ModelAttribute("signatureMultipleDocumentsForm") @Valid SignatureMultipleDocumentsForm signatureMultipleDocumentsForm, BindingResult result) { signatureMultipleDocumentsForm.setBase64Certificate(params.getSigningCertificate()); signatureMultipleDocumentsForm.setBase64CertificateChain(params.getCertificateChain()); signatureMultipleDocumentsForm.setEncryptionAlgorithm(params.getEncryptionAlgorithm()); signatureMultipleDocumentsForm.setSigningDate(new Date()); model.addAttribute("signatureMultipleDocumentsForm", signatureMultipleDocumentsForm); ToBeSigned dataToSign = signingService.getDataToSign(signatureMultipleDocumentsForm); if (dataToSign == null) { return null; } GetDataToSignResponse responseJson = new GetDataToSignResponse(); responseJson.setDataToSign(DatatypeConverter.printBase64Binary(dataToSign.getBytes())); return responseJson; }
@SuppressWarnings({ "rawtypes", "unchecked" }) public DSSDocument signDocument(SignatureDocumentForm form) { logger.info("Start signDocument with one document"); DocumentSignatureService service = getSignatureService(form.getContainerType(), form.getSignatureForm()); AbstractSignatureParameters parameters = fillParameters(form); DSSDocument signedDocument = null; try { DSSDocument toSignDocument = WebAppUtils.toDSSDocument(form.getDocumentToSign()); SignatureAlgorithm sigAlgorithm = SignatureAlgorithm.getAlgorithm(form.getEncryptionAlgorithm(), form.getDigestAlgorithm()); SignatureValue signatureValue = new SignatureValue(sigAlgorithm, DatatypeConverter.parseBase64Binary(form.getBase64SignatureValue())); signedDocument = service.signDocument(toSignDocument, parameters, signatureValue); } catch (Exception e) { logger.error("Unable to execute signDocument : " + e.getMessage(), e); } logger.info("End signDocument with one document"); return signedDocument; }
@SuppressWarnings({ "rawtypes", "unchecked" }) public DSSDocument signDocument(SignatureMultipleDocumentsForm form) { logger.info("Start signDocument with multiple documents"); MultipleDocumentsSignatureService service = getASiCSignatureService(form.getSignatureForm()); AbstractSignatureParameters parameters = fillParameters(form); DSSDocument signedDocument = null; try { List<DSSDocument> toSignDocuments = WebAppUtils.toDSSDocuments(form.getDocumentsToSign()); SignatureAlgorithm sigAlgorithm = SignatureAlgorithm.getAlgorithm(form.getEncryptionAlgorithm(), form.getDigestAlgorithm()); SignatureValue signatureValue = new SignatureValue(sigAlgorithm, DatatypeConverter.parseBase64Binary(form.getBase64SignatureValue())); signedDocument = service.signDocument(toSignDocuments, parameters, signatureValue); } catch (Exception e) { logger.error("Unable to execute signDocument : " + e.getMessage(), e); } logger.info("End signDocument with multiple documents"); return signedDocument; }
public ServerFinalMessage(byte[] messageBytes) throws SaslException { String message = toMessage(messageBytes); Matcher matcher = PATTERN.matcher(message); if (!matcher.matches()) throw new SaslException("Invalid SCRAM server final message format: " + message); String error = null; try { error = matcher.group("error"); } catch (IllegalArgumentException e) { // ignore } if (error == null) { this.serverSignature = DatatypeConverter.parseBase64Binary(matcher.group("signature")); this.error = null; } else { this.serverSignature = null; this.error = error; } }
@SuppressWarnings("unchecked") @Override public T deserialize(String topic, byte[] data) { try { T result = null; if (data != null) { LOGGER.debug("data='{}'", DatatypeConverter.printHexBinary(data)); DatumReader<GenericRecord> datumReader = new SpecificDatumReader<>( targetType.newInstance().getSchema()); Decoder decoder = DecoderFactory.get().binaryDecoder(data, null); result = (T) datumReader.read(null, decoder); LOGGER.debug("deserialized data='{}'", result); } return result; } catch (Exception ex) { throw new SerializationException( "Can't deserialize data '" + Arrays.toString(data) + "' from topic '" + topic + "'", ex); } }
private static boolean checkSHA256(File provingKey, Component parent) throws IOException { MessageDigest sha256; try { sha256 = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException impossible) { throw new RuntimeException(impossible); } try (InputStream is = new BufferedInputStream(new FileInputStream(provingKey))) { ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(parent,"Verifying proving key",is); pmis.getProgressMonitor().setMaximum(PROVING_KEY_SIZE); pmis.getProgressMonitor().setMillisToPopup(10); DigestInputStream dis = new DigestInputStream(pmis, sha256); byte [] temp = new byte[0x1 << 13]; while(dis.read(temp) >= 0); byte [] digest = sha256.digest(); return SHA256.equalsIgnoreCase(DatatypeConverter.printHexBinary(digest)); } }
public static String[] decode(String auth) { //Replacing "Basic THE_BASE_64" to "THE_BASE_64" directly auth = auth.replaceFirst("[B|b]asic ", ""); //Decode the Base64 into byte[] byte[] decodedBytes = DatatypeConverter.parseBase64Binary(auth); //If the decode fails in any case if(decodedBytes == null || decodedBytes.length == 0){ return null; } //Now split the byte[] into an array : // - the first one is login, // - the second one password return new String(decodedBytes).split(":", 2); }
/** * Testing method for decompression of ewf file hex bytes * @param ewfHexStr any zlib compressed hex * @return decompressed string */ protected static String decompress(String ewfHexStr) { Inflater inflater = new Inflater(); byte[] input = DatatypeConverter.parseHexBinary(ewfHexStr); inflater.setInput(input, 0, input.length); String outputString = "empty"; byte[] result = new byte[input.length]; int resultLength; try { resultLength = inflater.inflate(result); outputString = new String(result, 0, resultLength, "UTF-8"); } catch (DataFormatException | UnsupportedEncodingException e) { e.printStackTrace(); } inflater.end(); return outputString; }
/** * Verify that the NotOnOrAfter attribute in any bearer * <SubjectConfirmationData> has not passed, subject to allowable clock skew * between the providers * * @throws AssertionValidationException */ void verifyAssertionExpirationDate(Node nodeAssertion, Node nodeConfirmationData) throws AssertionValidationException { Calendar expirationDate = DatatypeConverter.parseDateTime(XMLConverter .getStringAttValue(nodeConfirmationData, SamlXmlTags.ATTRIBUTE_NOT_ON_OR_AFTER)); if (now.equals(expirationDate) || now.after(expirationDate)) { String assertionId = XMLConverter.getStringAttValue(nodeAssertion, SamlXmlTags.ATTRIBUTE_ID); AssertionValidationException exception = new AssertionValidationException( String.format("Assertion (id=%s) expired", assertionId), AssertionValidationException.ReasonEnum.ASSERTION_EXPIRED, new String[] { assertionId }); throw exception; } }
public static String EncryptAES(String input, SecretKey key) throws CryptoException { // encode input input = DatatypeConverter.printBase64Binary(input.getBytes()); byte[] ciphertext = null; try { ciphertext = AES.encrypt(input.getBytes(), key); } catch (Exception e) { throw new CryptoException(e); } // encode encrypted input //return DatatypeConverter.printBase64Binary(ciphertext.getBytes()); return DatatypeConverter.printHexBinary(ciphertext); }
/** * Using a filter chain step, make some JSON out of it and then hash it to create an idempotent identifier. * @param triggerEvent Trigger event that contains metadata about the request * @param step The FilterChainStep that we are going to generate the request from * @return A sideline request identifier for the filter chain step * @throws NoSuchAlgorithmException Your java install is whack yo, it's missing MD5, for realz??? */ private SidelineRequestIdentifier generateSidelineRequestIdentifier( final TriggerEvent triggerEvent, final FilterChainStep step ) throws NoSuchAlgorithmException, UnsupportedEncodingException { final String json = gson.toJson(step); final StringBuilder identifier = new StringBuilder( DatatypeConverter.printHexBinary(MessageDigest.getInstance("MD5").digest(json.getBytes("UTF-8"))) ); // If we were provided a date time in the event, append the time stamp of that event to the identifier if (triggerEvent.getCreatedAt() != null) { identifier.append("-"); identifier.append( triggerEvent.getCreatedAt().atZone(ZoneOffset.UTC).toInstant().toEpochMilli() ); } return new SidelineRequestIdentifier(identifier.toString()); }
@Test public void testExec_withValidKeyStoreProperties_ProperlyEncodesBackup() throws Exception { // Arrange. TestBackupFileServiceRequest testRequest = new TestBackupFileServiceRequest(); SecretKey secretKey = generateTestSecretKey(); KeyStoreProvider.getInstance().putSecretKey(BACKUP_KEY_ALIAS, secretKey, BACKUP_KEY_PASSWORD); String ivHex = generateTestIVHex(); KeyStoreProvider.getInstance().putPassword(BACKUP_IV_ALIAS, ivHex, BACKUP_IV_PASSWORD); // Act. TestBackupFileServiceResponse response = this.target.exec(testRequest, this.em); // Assert. assertEquals(secretKey, response.key); assertEquals(ivHex, DatatypeConverter.printHexBinary(response.iv)); }
@Override public void read(javolution.xml.XMLFormat.InputElement xml, DiameterIdentityImpl diameterIdentity) throws XMLStreamException { String s = xml.getAttribute(DATA, DEFAULT_VALUE); if (s != null) { diameterIdentity.data = DatatypeConverter.parseHexBinary(s); } }
@Override public void write(DiameterIdentityImpl diameterIdentity, javolution.xml.XMLFormat.OutputElement xml) throws XMLStreamException { if (diameterIdentity.data != null) { xml.setAttribute(DATA, DatatypeConverter.printHexBinary(diameterIdentity.data)); } }
private void addBasicAuth(Packet context, Map<String, List<String>> reqHeaders) { String user = (String) context.invocationProperties.get(BindingProvider.USERNAME_PROPERTY); if (user != null) { String pw = (String) context.invocationProperties.get(BindingProvider.PASSWORD_PROPERTY); if (pw != null) { StringBuilder buf = new StringBuilder(user); buf.append(":"); buf.append(pw); String creds = DatatypeConverter.printBase64Binary(buf.toString().getBytes()); reqHeaders.put("Authorization", Collections.singletonList("Basic "+creds)); } } }
@Override public void read(javolution.xml.XMLFormat.InputElement xml, TAIdImpl taId) throws XMLStreamException { String s = xml.getAttribute(DATA, DEFAULT_VALUE); if (s != null) { taId.data = DatatypeConverter.parseHexBinary(s); } }
private String getGeneratedAnnotation(String comment) { StringBuilder buffer = new StringBuilder(); buffer.append("@Generated("); //$NON-NLS-1$ if (suppressAllComments) { buffer.append('\"'); } else { buffer.append("value=\""); //$NON-NLS-1$ } buffer.append(MyBatisGenerator.class.getName()); buffer.append('\"'); if (!suppressDate && !suppressAllComments) { buffer.append(", date=\""); //$NON-NLS-1$ buffer.append(DatatypeConverter.printDateTime(Calendar.getInstance())); buffer.append('\"'); } if (!suppressAllComments) { buffer.append(", comments=\""); //$NON-NLS-1$ buffer.append(comment); buffer.append('\"'); } buffer.append(')'); return buffer.toString(); }
/** * Converts a number to four bytes. * * @param numberToConvert number to convert * @return numInBytes given number as bytes */ public static byte[] convertToFourBytes(int numberToConvert) { byte[] numInBytes = new byte[4]; String s1 = Integer.toHexString(numberToConvert); if (s1.length() % 2 != 0) { s1 = "0" + s1; } byte[] hexas = DatatypeConverter.parseHexBinary(s1); if (hexas.length == 1) { numInBytes[0] = 0; numInBytes[1] = 0; numInBytes[2] = 0; numInBytes[3] = hexas[0]; } else if (hexas.length == 2) { numInBytes[0] = 0; numInBytes[1] = 0; numInBytes[2] = hexas[0]; numInBytes[3] = hexas[1]; } else if (hexas.length == 3) { numInBytes[0] = 0; numInBytes[1] = hexas[0]; numInBytes[2] = hexas[1]; numInBytes[3] = hexas[2]; } else { numInBytes[0] = hexas[0]; numInBytes[1] = hexas[1]; numInBytes[2] = hexas[2]; numInBytes[3] = hexas[3]; } return numInBytes; }
public static String sign(byte[] plainText, PrivateKey privateKey) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException { Signature privateSignature = Signature.getInstance(signVerifyAlgorithm); privateSignature.initSign(privateKey); privateSignature.update(plainText); return DatatypeConverter.printBase64Binary(privateSignature.sign()); }
@Override public void read(javolution.xml.XMLFormat.InputElement xml, CUGInterlockImpl cugInterlock) throws XMLStreamException { String s = xml.getAttribute(DATA, DEFAULT_VALUE); if (s != null) { cugInterlock.data = DatatypeConverter.parseHexBinary(s); } }
/** * Converts a number to four bytes. * * @param numberToConvert number to convert * @return given number as bytes */ public static byte[] convertToFourBytes(int numberToConvert) { byte[] numInBytes = new byte[4]; String s1 = Integer.toHexString(numberToConvert); if (s1.length() % 2 != 0) { s1 = "0" + s1; } byte[] hexas = DatatypeConverter.parseHexBinary(s1); if (hexas.length == 1) { numInBytes[0] = 0; numInBytes[1] = 0; numInBytes[2] = 0; numInBytes[3] = hexas[0]; } else if (hexas.length == 2) { numInBytes[0] = 0; numInBytes[1] = 0; numInBytes[2] = hexas[0]; numInBytes[3] = hexas[1]; } else if (hexas.length == 3) { numInBytes[0] = 0; numInBytes[1] = hexas[0]; numInBytes[2] = hexas[1]; numInBytes[3] = hexas[2]; } else { numInBytes[0] = hexas[0]; numInBytes[1] = hexas[1]; numInBytes[2] = hexas[2]; numInBytes[3] = hexas[3]; } return numInBytes; }
public static byte[] hexStringToBytes(String text) { text = text.replace(" ", ""); if (text.length() % 2 == 1) { text = text.substring(0, text.length() - 1) + "0" + text.charAt(text.length() - 1); } return DatatypeConverter.parseHexBinary(text); }
public static JwtBuilder builder(KeyEncrypt keyEncrypt) throws KeyOperationException { SecretKey secretKey = MacProvider.generateKey(SignatureAlgorithm.HS256); byte[] encryptedKey = keyEncrypt.encrypt(secretKey.getEncoded()); return Jwts.builder() .setHeaderParam("kid", DatatypeConverter.printBase64Binary(encryptedKey)) .signWith(SignatureAlgorithm.HS256, secretKey); }
@Override public void visit(HexValue value) { String stringValue = value.getValue().substring(2); byte[] byteValue = DatatypeConverter.parseHexBinary(stringValue); setValue(byteValue); }
@SuppressWarnings("deprecation") private void verifyTableContentsAfterUpdate() throws SQLException { verifyTableContents("SELECT UUID FROM TEST WHERE ID=1", DatatypeConverter.parseHexBinary("aabbcc")); verifyTableContents("SELECT ACTIVE FROM TEST WHERE ID=1", Boolean.FALSE); verifyTableContents("SELECT AMOUNT FROM TEST WHERE ID=1", Double.valueOf(129.95d)); verifyTableContents("SELECT AMOUNT FROM TEST WHERE ID=2", Double.valueOf(-129.95d)); verifyTableContents("SELECT CREATED_DATE FROM TEST WHERE ID=2", new Date(2017 - 1900, 1, 17)); verifyTableContents("SELECT LAST_UPDATED FROM TEST WHERE ID=2", new Timestamp(2017 - 1900, 1, 17, 8, 0, 0, 0)); }
public static void setStroke(String name, Stroke stroke) { ByteArrayOutputStream os = new ByteArrayOutputStream(); try { DataSaver.saveStroke(os, stroke, new DataLoader.MemoryData()); setString(name, DatatypeConverter.printHexBinary(os.toByteArray())); } catch (IOException e) { } }
/** * convert String id into ByteBuffer * @param type * @param id String * @return byte[] */ public static byte[] getIdBytes(Type type, String id) { if (type == Type.INT) { return ByteBuffer.allocate(Type.INT.size).putInt(Integer.parseInt(id)).array(); } else if (type == Type.LONG) { return ByteBuffer.allocate(Type.LONG.size).putLong(Long.parseLong(id)).array(); } else if (type == Type.UUID) { return DatatypeConverter.parseHexBinary(id); } else { return new byte[0]; } }
private String deflateAndBase64(final String data) { try { final Deflater deflater = new Deflater(); deflater.setInput(data.getBytes(HttpConstants.UTF8_ENCODING)); deflater.finish(); final byte[] buffer = new byte[data.length()]; final int resultSize = deflater.deflate(buffer); final byte[] output = new byte[resultSize]; System.arraycopy(buffer, 0, output, 0, resultSize); return DatatypeConverter.printBase64Binary(output); } catch (final UnsupportedEncodingException e) { throw new RuntimeException("Cannot find encoding:" + HttpConstants.UTF8_ENCODING, e); } }
@Override public byte[] getByteArray(String key, byte[] def) { String value = get(key, null); if (value != null) { byte [] decoded = DatatypeConverter.parseBase64Binary(value); if (decoded != null) { return decoded; } } return def; }
public static String Gerate(String issuer, int idSubject, int hours) { //The JWT signature algorithm we will be using to sign the token SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; //Hours to milliseconds long ttlMillis = hours * 3600000; String subject = String.valueOf(idSubject); long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); //We will sign our JWT with our ApiKey secret byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(Parameters.TOKENKEY); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); //Let's set the JWT Claims JwtBuilder builder = Jwts.builder().setIssuedAt(now) .setSubject(subject) .setIssuer(issuer) .signWith(signatureAlgorithm, signingKey); //if it has been specified, let's add the expiration if (ttlMillis >= 0) { long expMillis = nowMillis + ttlMillis; Date exp = new Date(expMillis); builder.setExpiration(exp); } //Builds the JWT and serializes it to a compact, URL-safe string return builder.compact(); }
private final LicenseStatus verifyProduct(Product product) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException { if(product.isExtension() && product.getProductId().startsWith("rapidminer-")) { return LicenseStatus.WRONG_PRODUCT_ID; } else { Signature rsaSignature = Signature.getInstance("SHA1withRSA"); rsaSignature.initVerify(this.publicKey); rsaSignature.update(product.createBase64Representation().getBytes(StandardCharsets.UTF_8)); return rsaSignature.verify(DatatypeConverter.parseBase64Binary(product.getSignature()))?LicenseStatus.VALID:LicenseStatus.SIGNATURE_INVALID; } }
@Test public void testconvertImageToBase64() { System.out.println("\n testconvertImageToBase64()"); String encodedImage = null; Network TempNetwork = new Network (); encodedImage = TempNetwork.convertImageToBase64(""); DatatypeConverter.parseBase64Binary(encodedImage); }
/** * Encodes the given image to a base64 coded string. * * @param image image to encode * @param type type of the image: jpeg, bmp, png, gif etc. * @return encoded string */ public static String encodeImg2String(BufferedImage image, String type) { String imageString = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ImageIO.write(image, type, bos); byte[] imageBytes = bos.toByteArray(); imageString = DatatypeConverter.printBase64Binary(imageBytes); bos.close(); } catch (IOException ex) { LOGGER.error(ex.getMessage(), ex); } return imageString; }
public JsonElement toJson(String uuid, String username, String skinUrl, String capeUrl) { // Lets add all the information in case the game really needs them JsonObject tex = new JsonObject(); if(skinUrl != null && !skinUrl.isEmpty()) { JsonObject skin = new JsonObject(); skin.addProperty("url", skinUrl); tex.add("SKIN", skin); } if(capeUrl != null && !capeUrl.isEmpty()) { JsonObject cape = new JsonObject(); cape.addProperty("url", capeUrl); tex.add("CAPE", cape); } JsonObject textures = new JsonObject(); textures.addProperty("timestamp", (int)(System.currentTimeMillis() / 1000L)); textures.addProperty("profileId", uuid); textures.addProperty("profileName", username); textures.add("textures", tex); JsonObject property = new JsonObject(); property.addProperty("name", "textures"); property.addProperty("value", DatatypeConverter.printBase64Binary(textures.toString().getBytes())); JsonArray properties = new JsonArray(); properties.add(property); JsonObject obj = new JsonObject(); obj.addProperty("id", uuid); obj.addProperty("name", username); obj.add("properties", properties); return obj; }
public ArrayList getByteArrayList(){ String hexStr = this.byteArray.getText().replace(" ", ""); byte[] bytes = DatatypeConverter.parseHexBinary(hexStr); ArrayList doubleArrayList = new ArrayList(); for (byte byteVal : bytes){ doubleArrayList.add((double) byteVal); } return doubleArrayList; }
public static String digestHex(String str) { try { MessageDigest md = MessageDigest.getInstance("SHA-512"); byte[] data = md.digest(str.getBytes()); return DatatypeConverter.printHexBinary(data); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }