@Override public U2fSignRequest getSignRequest(String accountName, String appId) throws U2FException { Log.info(">> getSignRequest " + accountName); List<SecurityKeyData> securityKeyDataList = dataStore.getSecurityKeyData(accountName); byte[] challenge = challengeGenerator.generateChallenge(accountName); String challengeBase64 = Base64.encodeBase64URLSafeString(challenge); ImmutableList.Builder<RegisteredKey> registeredKeys = ImmutableList.builder(); Log.info(" challenge: " + Hex.encodeHexString(challenge)); for (SecurityKeyData securityKeyData : securityKeyDataList) { SignSessionData sessionData = new SignSessionData(accountName, appId, challenge, securityKeyData.getPublicKey()); String sessionId = dataStore.storeSessionData(sessionData); byte[] keyHandle = securityKeyData.getKeyHandle(); List<Transports> transports = securityKeyData.getTransports(); Log.info("-- Output --"); Log.info(" sessionId: " + sessionId); Log.info(" keyHandle: " + Hex.encodeHexString(keyHandle)); String keyHandleBase64 = Base64.encodeBase64URLSafeString(keyHandle); Log.info("<< getRegisteredKey " + accountName); registeredKeys.add( new RegisteredKey(U2FConsts.U2F_V2, keyHandleBase64, transports, appId, sessionId)); } return new U2fSignRequest(challengeBase64, registeredKeys.build()); }
/** * Checks if the {@code TimeStampToken} matches the signed data. * * @param data the array of {@code byte} representing the timestamped data * @return true if the data is verified by the TimeStampToken */ public boolean matchData(final byte[] data) { try { messageImprintData = data != null; final TimeStampTokenInfo timeStampInfo = timeStamp.getTimeStampInfo(); final ASN1ObjectIdentifier hashAlgorithm = timeStampInfo.getHashAlgorithm().getAlgorithm(); final DigestAlgorithm digestAlgorithm = DigestAlgorithm.forOID(hashAlgorithm.getId()); final byte[] computedDigest = DSSUtils.digest(digestAlgorithm, data); final byte[] timestampDigest = timeStampInfo.getMessageImprintDigest(); messageImprintIntact = Arrays.equals(computedDigest, timestampDigest); if (!messageImprintIntact) { logger.error( "Computed digest ({}) on the extracted data from the document : {}", digestAlgorithm, Hex.encodeHexString(computedDigest)); logger.error("Digest present in TimestampToken: {}", Hex.encodeHexString(timestampDigest)); logger.error( "Digest in TimestampToken matches digest of extracted data from document: {}", messageImprintIntact); } } catch (DSSException e) { messageImprintIntact = false; signedDataMessage = "Timestamp digest problem: " + e.getMessage(); } return messageImprintIntact; }
@Test public void testSplitQuery() throws Exception { // Insert 20 rows per shard for (String shardName : testEnv.shardKidMap.keySet()) { Util.insertRowsInShard(testEnv, shardName, 20); } Util.waitForTablet("rdonly", 40, 3, testEnv); VtGate vtgate = VtGate.connect("localhost:" + testEnv.port, 0); Map<Query, Long> queries = vtgate.splitQuery("test_keyspace", "select id,keyspace_id from vtgate_test", 1); vtgate.close(); // Verify 2 splits, one per shard Assert.assertEquals(2, queries.size()); Set<String> shardsInSplits = new HashSet<>(); for (Query q : queries.keySet()) { Assert.assertEquals("select id,keyspace_id from vtgate_test", q.getSql()); Assert.assertEquals("test_keyspace", q.getKeyspace()); Assert.assertEquals("rdonly", q.getTabletType()); Assert.assertEquals(0, q.getBindVars().size()); Assert.assertEquals(null, q.getKeyspaceIds()); String start = Hex.encodeHexString(q.getKeyRanges().get(0).get("Start")); String end = Hex.encodeHexString(q.getKeyRanges().get(0).get("End")); shardsInSplits.add(start + "-" + end); } // Verify the keyrange queries in splits cover the entire keyspace Assert.assertTrue(shardsInSplits.containsAll(testEnv.shardKidMap.keySet())); }
/** * Convert a public key to the SSH format. * * <p>Note that only RSA keys are supported at the moment. * * @param key the public key to convert * @return an array of bytes that can with the representation of the public key */ public static byte[] getKeyBytes(final PublicKey key) { // We only support RSA at the moment: if (!(key instanceof RSAPublicKey)) { log.error( "The key algorithm \"" + key.getAlgorithm() + "\" is not supported, will return null."); return null; } // Extract the bytes of the exponent and the modulus // of the key: final RSAPublicKey rsaKey = (RSAPublicKey) key; final byte[] exponentBytes = rsaKey.getPublicExponent().toByteArray(); final byte[] modulusBytes = rsaKey.getModulus().toByteArray(); if (log.isDebugEnabled()) { log.debug( "Exponent is " + rsaKey.getPublicExponent() + " (" + Hex.encodeHexString(exponentBytes) + ")."); log.debug( "Modulus is " + rsaKey.getModulus() + " (" + Hex.encodeHexString(exponentBytes) + ")."); } try { // Prepare the stream to write the binary SSH key: final ByteArrayOutputStream binaryOut = new ByteArrayOutputStream(); final DataOutputStream dataOut = new DataOutputStream(binaryOut); // Write the SSH header (4 bytes for the length of the algorithm // name and then the algorithm name): dataOut.writeInt(SSH_RSA.length()); dataOut.writeBytes(SSH_RSA); // Write the exponent and modulus bytes (note that it is not // necessary to check if the most significative bit is one, as // that will never happen with byte arrays created from big // integers, unless they are negative, which is not the case // for RSA modulus or exponents): dataOut.writeInt(exponentBytes.length); dataOut.write(exponentBytes); dataOut.writeInt(modulusBytes.length); dataOut.write(modulusBytes); // Done, extract the bytes: binaryOut.close(); final byte[] keyBytes = binaryOut.toByteArray(); if (log.isDebugEnabled()) { log.debug("Key bytes are " + Hex.encodeHexString(keyBytes) + "."); } return keyBytes; } catch (IOException exception) { log.error("Error while serializing public key, will return null.", exception); return null; } }
@Override public boolean importData(TransferSupport support) throws ConverterException { try { if (support.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { List<File> files = (List<File>) support.getTransferable().getTransferData(DataFlavor.javaFileListFlavor); for (File file : files) { FileInputStream fis = null; OutputStream out = null; try { out = getOutputStream(file, ".hex"); fis = new FileInputStream(file); byte[] buffer = new byte[bufferSize]; int count = 0; while (-1 != (count = fis.read(buffer))) { if (count == bufferSize) { out.write(Hex.encodeHexString(buffer).getBytes("UTF-8")); } else { byte[] tmp = Arrays.copyOf(Hex.encodeHexString(buffer).getBytes("UTF-8"), count); out.write(tmp); } } } catch (Exception e) { throw new ConverterException(e); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(fis); } } return true; } else if (support.isDataFlavorSupported(DataFlavor.stringFlavor)) { String data = (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor); OutputStream out = null; try { byte[] encode = Hex.encodeHexString(data.getBytes()).getBytes(); out = getOutputStream(null, ".hex"); out.write(encode); } catch (Exception e) { throw new ConverterException(e); } finally { IOUtils.closeQuietly(out); } } } catch (Exception e) { throw new ConverterException(e); } return false; }
private static void bcDES() throws Exception { Security.addProvider(new BouncyCastleProvider()); // Key convert DESKeySpec desKeySpec = new DESKeySpec(bytesKey); SecretKeyFactory factory = SecretKeyFactory.getInstance("DES", "BC"); SecretKey desKey = factory.generateSecret(desKeySpec); Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, desKey); System.out.println("BC" + cipher.getProvider()); byte[] result = cipher.doFinal("ABC".getBytes()); String hexResult = Hex.encodeHexString(result); System.out.println(hexResult); cipher.init(Cipher.DECRYPT_MODE, desKey); result = cipher.doFinal( Hex.decodeHex(hexResult.toCharArray()) // result ); System.out.println(new String(result)); }
private String query(String method, HashMap<String, String> args) { Mac mac = null; SecretKeySpec key = null; args.put("method", method); long time = System.currentTimeMillis() / 1000L; args.put("nonce", "" + (int) (time)); String postData = ""; for (Iterator argumentIterator = args.entrySet().iterator(); argumentIterator.hasNext(); ) { Map.Entry argument = (Map.Entry) argumentIterator.next(); if (postData.length() > 0) { postData += "&"; } postData += argument.getKey() + "=" + argument.getValue(); } try { key = new SecretKeySpec(apisecret.getBytes("UTF-8"), "HmacSHA512"); mac = Mac.getInstance("HmacSHA512"); mac.init(key); URL queryUrl = new URL("https://btc-e.com/tapi/"); HttpURLConnection connection = (HttpURLConnection) queryUrl.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; Java Test client)"); connection.setRequestProperty("Key", apikey); connection.setRequestProperty( "Sign", Hex.encodeHexString(mac.doFinal(postData.getBytes("UTF-8")))); connection.getOutputStream().write(postData.getBytes()); StringWriter writer = new StringWriter(); IOUtils.copy(connection.getInputStream(), writer, "UTF-8"); return writer.toString(); } catch (Exception ex) { utils.logger.log(true, ex.getMessage()); } return new String(); }
/** * Get the content body. * * @return the content */ public String getContent() { if (StringUtils.hasText(content)) { return content; } else if (StringUtils.hasText(contentResourcePath) && contentType.startsWith("text")) { try { return FileUtils.readToString( new PathMatchingResourcePatternResolver() .getResource(contentResourcePath) .getInputStream(), Charset.forName(charsetName)); } catch (IOException e) { throw new CitrusRuntimeException("Failed to read SOAP attachment file resource", e); } } else { try { byte[] binaryData = FileUtils.readToString(getDataHandler().getInputStream(), Charset.forName(charsetName)) .getBytes(Charset.forName(charsetName)); if (encodingType.equals(SoapAttachment.ENCODING_BASE64_BINARY)) { return Base64.encodeBase64String(binaryData); } else if (encodingType.equals(SoapAttachment.ENCODING_HEX_BINARY)) { return Hex.encodeHexString(binaryData).toUpperCase(); } else { throw new CitrusRuntimeException( String.format( "Unsupported encoding type '%s' for SOAP attachment - choose one of %s or %s", encodingType, SoapAttachment.ENCODING_BASE64_BINARY, SoapAttachment.ENCODING_HEX_BINARY)); } } catch (IOException e) { throw new CitrusRuntimeException("Failed to read SOAP attachment data input stream", e); } } }
public Day4(String input) { super(input); try { MessageDigest md = MessageDigest.getInstance("MD5"); boolean foundFiveZeroesNumber = false; boolean foundSixZeroesNumber = false; for (int i = 0; ; i++) { byte[] bytesOfMessage = (input + i).getBytes("UTF-8"); String digest = Hex.encodeHexString(md.digest(bytesOfMessage)); if (!foundFiveZeroesNumber && digest.substring(0, 5).equals("00000")) { fiveZeroesNumber = i; foundFiveZeroesNumber = true; } if (!foundSixZeroesNumber && digest.substring(0, 6).equals("000000")) { sixZeroesNumber = i; foundSixZeroesNumber = true; } if (foundFiveZeroesNumber && foundSixZeroesNumber) { break; } } } catch (Exception e) { // Gotta catch em all! System.out.println("something happened :("); } }
@Test public void test() throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, InvalidKeyException, NoSuchProviderException, SignatureException, DecoderException { byte[] assinatura = SignerSample.signTestFile(); assertTrue(assinatura != null); String saida = Hex.encodeHexString(assinatura); logger.debug("Assinatura: " + saida); // Verifica a assinatura: InputStream filepath = SignerSample.class.getClassLoader().getResourceAsStream("arquivo.txt"); byte[] bTexto = IOUtils.toByteArray(filepath); String texto = new String(bTexto, "UTF-8"); logger.debug("Texto: " + texto); boolean resultado = VerifySignature.verify(saida, texto, "*", "meucertificado", "teste001"); assertTrue(resultado); /* // Verifica com keystore externa (troque o path antes de rodar esse teste) resultado = VerifySignature.verify(saida, texto, "/home/cleuton/wsDropwizard01/certstore/verifykeystore.jks", "meucertificado", "teste001"); assertTrue(resultado); */ // Altera o texto e verifica novamente: bTexto[5] = 61; String texto2 = new String(bTexto, "UTF-8"); resultado = VerifySignature.verify(saida, texto2, "*", "meucertificado", "teste001"); assertFalse(resultado); }
public static void jdkHMacMD5() { KeyGenerator keyGenerator; try { // 生成密钥 // keyGenerator = KeyGenerator.getInstance("HmacMD5"); // SecretKey secretKey = keyGenerator.generateKey(); // byte[] key = secretKey.getEncoded(); byte[] key = Hex.decodeHex(new char[] {'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'}); // 还原密钥 SecretKey restoreSecretKey = new SecretKeySpec(key, "HmacMD5"); // 实例和初始化Mac Mac mac = Mac.getInstance(restoreSecretKey.getAlgorithm()); mac.init(restoreSecretKey); // 执行摘要 byte[] hmacMD5Bytes = mac.doFinal(src.getBytes()); System.out.println("jdk hmacMD5:" + Hex.encodeHexString(hmacMD5Bytes)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (DecoderException e) { e.printStackTrace(); } }
public String getString() { if (this.isPublic()) { return "_" + Hex.encodeHexString(this.publicLabel.getData()); } else { return Long.toHexString(this.privateLabel.getClassId().getId()) + Integer.toHexString(this.privateLabel.getIndex()); } }
private String hmac(String secret, String message) throws GeneralSecurityException { SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), HMAC_SHA256); Mac mac = Mac.getInstance(HMAC_SHA256); mac.init(signingKey); byte[] rawHmac = mac.doFinal(message.getBytes(Charsets.UTF_8)); String result = new String(Hex.encodeHexString(rawHmac)); return result; }
@Override protected SoapMessage createMessage(TestContext context, String messageType) { Message message = super.createMessage(context, getMessageType()); SoapMessage soapMessage = new SoapMessage(message).mtomEnabled(mtomEnabled); try { for (SoapAttachment attachment : attachments) { attachment.resolveDynamicContent(context); if (mtomEnabled) { String messagePayload = soapMessage.getPayload(String.class); String cid = CID_MARKER + attachment.getContentId(); if (attachment.isMtomInline() && messagePayload.contains(cid)) { byte[] attachmentBinaryData = FileUtils.readToString( attachment.getInputStream(), Charset.forName(attachment.getCharsetName())) .getBytes(Charset.forName(attachment.getCharsetName())); if (attachment.getEncodingType().equals(SoapAttachment.ENCODING_BASE64_BINARY)) { log.info("Adding inline base64Binary data for attachment: %s", cid); messagePayload = messagePayload.replaceAll(cid, Base64.encodeBase64String(attachmentBinaryData)); } else if (attachment.getEncodingType().equals(SoapAttachment.ENCODING_HEX_BINARY)) { log.info("Adding inline hexBinary data for attachment: %s", cid); messagePayload = messagePayload.replaceAll( cid, Hex.encodeHexString(attachmentBinaryData).toUpperCase()); } else { throw new CitrusRuntimeException( String.format( "Unsupported encoding type '%s' for SOAP attachment: %s - choose one of %s or %s", attachment.getEncodingType(), cid, SoapAttachment.ENCODING_BASE64_BINARY, SoapAttachment.ENCODING_HEX_BINARY)); } } else { messagePayload = messagePayload.replaceAll( cid, String.format( "<xop:Include xmlns:xop=\"http://www.w3.org/2004/08/xop/include\" href=\"%s\"/>", cid)); soapMessage.addAttachment(attachment); } soapMessage.setPayload(messagePayload); } else { soapMessage.addAttachment(attachment); } } } catch (IOException e) { throw new CitrusRuntimeException(e); } return soapMessage; }
@Override public String toSQL(Object value) { byte[] b = (byte[]) value; if (charset.equals("utf8") || charset.equals("utf8mb4")) { return quoteString(new String(b)); } else { return "x'" + Hex.encodeHexString(b) + "'"; } }
public static String jdkMD2() { try { MessageDigest md = MessageDigest.getInstance("MD2"); byte[] md2Bytes = md.digest(src.getBytes()); md2 = Hex.encodeHexString(md2Bytes); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return md2; }
/** * Encrypts the specified text in MD5. * * @param original the text to encrypt * @return the digest of the text in a 32-bits hexadecimal. * @throws UtilException */ public static String encrypt(String original) throws UtilException { byte[] uniqueKey = original.getBytes(Charsets.UTF_8); try { byte[] hash = MessageDigest.getInstance("MD5").digest(uniqueKey); return Hex.encodeHexString(hash); } catch (NoSuchAlgorithmException e) { // TODO utiliser le CryptoException // throw new CryptoException throw new UtilException( "CryptMD5.encrypt()", SilverpeasException.ERROR, "root.EX_NO_MESSAGE", e); } }
public void setPassword(String plaintextPassword) throws SugarApiException { try { this.password = Hex.encodeHexString( MessageDigest.getInstance("MD5").digest(plaintextPassword.getBytes())); } catch (NoSuchAlgorithmException ex) { SugarApiException sae = new SugarApiException( "Unable to generate Sugar password value because this JRE does not support MD5", ex); throw sae; } }
/** Convert bytes to SHA-1 */ public Text evaluate(BytesWritable b) { if (b == null) { return null; } digest.reset(); digest.update(b.getBytes(), 0, b.getLength()); byte[] shaBytes = digest.digest(); String shaHex = Hex.encodeHexString(shaBytes); result.set(shaHex); return result; }
@Override public void delete(byte[] blobKey) throws BlobException { Delete delete = new Delete(blobKey); try { table.delete(delete); } catch (IOException e) { throw new BlobException( "Failed to delete blob with key '" + Hex.encodeHexString(blobKey) + "' from the DFS blobstore", e); } }
@Test public void cast_hexBinary_to_base64() throws XPathException { final String testData = "testdata"; final String expectedResult = Base64.encodeBase64String(testData.getBytes()).trim(); BinaryValue binaryValue = new BinaryValueFromBinaryString( new HexBinaryValueType(), Hex.encodeHexString(testData.getBytes())); final AtomicValue result = binaryValue.convertTo(new Base64BinaryValueType()); assertEquals(expectedResult, result.getStringValue()); }
/** * Converts {@link ObjectName} to a key that helps verifying whether different MBeans can produce * same RBAC info * * @param allJmxAclPids * @param n * @return */ public static String pidListKey(List<String> allJmxAclPids, ObjectName n) throws NoSuchAlgorithmException, UnsupportedEncodingException { List<String> pidCandidates = iterateDownPids(nameSegments(n)); MessageDigest md = MessageDigest.getInstance("MD5"); for (String pc : pidCandidates) { String generalPid = getGeneralPid(allJmxAclPids, pc); if (generalPid.length() > 0) { md.update(generalPid.getBytes("UTF-8")); } } return Hex.encodeHexString(md.digest()); }
protected byte[] getHash(RSAPublicKey publicKey) throws EbicsException { String modulus; String exponent; String hash; byte[] digest; exponent = Hex.encodeHexString(publicKey.getPublicExponent().toByteArray()); modulus = Hex.encodeHexString(removeFirstByte(publicKey.getModulus().toByteArray())); hash = exponent + " " + modulus; if (hash.charAt(0) == '0') { hash = hash.substring(1); } try { digest = MessageDigest.getInstance("SHA-256", "BC").digest(hash.getBytes("US-ASCII")); } catch (GeneralSecurityException | UnsupportedEncodingException e) { throw new EbicsException(e.getMessage()); } return format(new String(Hex.encodeHex(digest, false))).getBytes(); }
@Test public void testSplitQueryMultipleSplitsPerShard() throws Exception { int rowCount = 30; Util.insertRows(testEnv, 1, 30); List<String> expectedSqls = Lists.newArrayList( "select id, keyspace_id from vtgate_test where id < 10", "select id, keyspace_id from vtgate_test where id < 11", "select id, keyspace_id from vtgate_test where id >= 10 and id < 19", "select id, keyspace_id from vtgate_test where id >= 11 and id < 19", "select id, keyspace_id from vtgate_test where id >= 19", "select id, keyspace_id from vtgate_test where id >= 19"); Util.waitForTablet("rdonly", rowCount, 3, testEnv); VtGate vtgate = VtGate.connect("localhost:" + testEnv.port, 0); int splitCount = 6; Map<Query, Long> queries = vtgate.splitQuery("test_keyspace", "select id,keyspace_id from vtgate_test", splitCount); vtgate.close(); // Verify 6 splits, 3 per shard Assert.assertEquals(splitCount, queries.size()); Set<String> shardsInSplits = new HashSet<>(); for (Query q : queries.keySet()) { String sql = q.getSql(); Assert.assertTrue(expectedSqls.contains(sql)); expectedSqls.remove(sql); Assert.assertEquals("test_keyspace", q.getKeyspace()); Assert.assertEquals("rdonly", q.getTabletType()); Assert.assertEquals(0, q.getBindVars().size()); Assert.assertEquals(null, q.getKeyspaceIds()); String start = Hex.encodeHexString(q.getKeyRanges().get(0).get("Start")); String end = Hex.encodeHexString(q.getKeyRanges().get(0).get("End")); shardsInSplits.add(start + "-" + end); } // Verify the keyrange queries in splits cover the entire keyspace Assert.assertTrue(shardsInSplits.containsAll(testEnv.shardKidMap.keySet())); Assert.assertTrue(expectedSqls.size() == 0); }
private byte[] signDocumentAndReturnDigest( final PAdESSignatureParameters parameters, final byte[] signatureBytes, final File signedFile, final FileOutputStream fileOutputStream, final PDDocument pdDocument, final PDSignature pdSignature, final DigestAlgorithm digestAlgorithm) throws DSSException { SignatureOptions options = new SignatureOptions(); try { final MessageDigest digest = DSSUtils.getMessageDigest(digestAlgorithm); // register signature dictionary and sign interface SignatureInterface signatureInterface = new SignatureInterface() { @Override public byte[] sign(InputStream content) throws SignatureException, IOException { byte[] b = new byte[4096]; int count; while ((count = content.read(b)) > 0) { digest.update(b, 0, count); } return signatureBytes; } }; options.setPreferedSignatureSize(parameters.getSignatureSize()); if (parameters.getImageParameters() != null) { fillImageParameters(pdDocument, parameters.getImageParameters(), options); } pdDocument.addSignature(pdSignature, signatureInterface, options); saveDocumentIncrementally(parameters, signedFile, fileOutputStream, pdDocument); final byte[] digestValue = digest.digest(); if (logger.isDebugEnabled()) { logger.debug("Digest to be signed: " + Hex.encodeHexString(digestValue)); } fileOutputStream.close(); return digestValue; } catch (IOException e) { throw new DSSException(e); } catch (SignatureException e) { throw new DSSException(e); } finally { IOUtils.closeQuietly(options.getVisualSignature()); } }
@Override public InputStream getInputStream(byte[] blobKey) throws BlobException { Get get = new Get(blobKey); get.addColumn(BLOBS_COLUMN_FAMILY_BYTES, BLOB_COLUMN); Result result; try { result = table.get(get); } catch (IOException e) { throw new BlobException( "Failed to open an inputstream for blobkey '" + Hex.encodeHexString(blobKey) + "' on the HBASE blobstore", e); } byte[] value = result.getValue(BLOBS_COLUMN_FAMILY_BYTES, BLOB_COLUMN); if (value == null) { throw new BlobException( "Failed to open an inputstream for blobkey '" + Hex.encodeHexString(blobKey) + "' since no blob was found on the HBASE blobstore"); } return new ByteArrayInputStream(value); }
/** * The code in this method is based on this blog post: * https://www.sammyk.me/the-single-most-important-way-to-make-your-facebook-app-more-secure and * this answer: * https://stackoverflow.com/questions/7124735/hmac-sha256-algorithm-for-signature-calculation * * @param url the URL to which we're adding the proof * @param token the application token we pass back and forth * @return URL with the appsecret_proof parameter added */ protected String computeAppSecretProof(String url, Token token) { try { Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); SecretKeySpec secret_key = new SecretKeySpec(this.secret.getBytes("UTF-8"), "HmacSHA256"); sha256_HMAC.init(secret_key); String proof = org.apache.commons.codec.binary.Hex.encodeHexString( sha256_HMAC.doFinal(token.getToken().getBytes("UTF-8"))); url = CommonHelper.addParameter(url, APPSECRET_PARAMETER, proof); return url; } catch (Exception e) { throw new TechnicalException("Unable to compute appsecret_proof", e); } }
@Test public void getImageHashTest() throws Exception { File test = new File(testConfig.getImageToHash()); String hashResult = Util.getImageHash(test, "MD5"); BufferedImage bufferedImage = ImageIO.read(test); byte[] pixels = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer()).getData(); MessageDigest digester = MessageDigest.getInstance("MD5"); digester.update(pixels); byte[] messageDigest = digester.digest(); String hash2 = Hex.encodeHexString(messageDigest); Assert.assertEquals("Hash result does not match", hashResult, testConfig.getImageHash()); }
public static UUID getIndexId( EntityRef connectingEntity, String connectionType, String connectedEntityType, ConnectedEntityRef... pairedConnections) { UUID uuid = null; try { if (connectionsNull(pairedConnections) && ((connectionType == null) && (connectedEntityType == null))) { return connectingEntity.getUuid(); } ByteArrayOutputStream byteStream = new ByteArrayOutputStream(16 + (32 * pairedConnections.length)); byteStream.write(uuidToBytesNullOk(connectingEntity.getUuid())); for (ConnectedEntityRef connection : pairedConnections) { String type = connection.getConnectionType(); UUID id = connection.getUuid(); byteStream.write(ascii(StringUtils.lowerCase(type))); byteStream.write(uuidToBytesNullOk(id)); } if (connectionType == null) { connectionType = NULL_ENTITY_TYPE; } if (connectedEntityType == null) { connectedEntityType = NULL_ENTITY_TYPE; } byteStream.write(ascii(StringUtils.lowerCase(connectionType))); byteStream.write(ascii(StringUtils.lowerCase(connectedEntityType))); byte[] raw_id = byteStream.toByteArray(); logger.info("raw connection index id: " + Hex.encodeHexString(raw_id)); uuid = UUID.nameUUIDFromBytes(raw_id); logger.info("connection index uuid: " + uuid); } catch (IOException e) { logger.error("Unable to create connection index UUID", e); } return uuid; }
private String getPassword() { if (hashPassword) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(password.getBytes("ISO-8859-1")); byte[] bytes = md.digest(); return Hex.encodeHexString(bytes); } catch (Exception e) { throw new RuntimeException(e); } } else { return password; } }