/** * SM3计算. * * @param datas * 待计算的数据 * @return 计算结果 */ private static byte[] sm3(byte[] data) { SM3Digest sm3 = new SM3Digest(); sm3.update(data, 0, data.length); byte[] result = new byte[sm3.getDigestSize()]; sm3.doFinal(result, 0); return result; }
public static byte[] sha256hash160(byte[] input) { byte[] sha256 = sha256(input); RIPEMD160Digest digest = new RIPEMD160Digest(); digest.update(sha256, 0, sha256.length); byte[] out = new byte[20]; digest.doFinal(out, 0); return out; } }
private static byte[] blake2Hash(HashAlgorithm algorithm, byte[] value) { int digestLengthBytes = algorithm.getDigestBytesLength(); Blake2bDigest blake2bDigest = new Blake2bDigest(digestLengthBytes * 8); byte[] rawHash = new byte[blake2bDigest.getDigestSize()]; blake2bDigest.update(value, 0, value.length); blake2bDigest.doFinal(rawHash, 0); return rawHash; }
private Digest resolvePRF(final String prf) { if (StringUtils.isEmpty(prf)) { throw new IllegalArgumentException("Cannot resolve empty PRF"); } String formattedPRF = prf.toLowerCase().replaceAll("[\\W]+", ""); logger.debug("Resolved PRF {} to {}", prf, formattedPRF); switch (formattedPRF) { case "md5": return new MD5Digest(); case "sha1": return new SHA1Digest(); case "sha384": return new SHA384Digest(); case "sha256": return new SHA256Digest(); case "sha512": return new SHA512Digest(); default: logger.warn("Could not resolve PRF {}. Using default PRF {} instead", prf, DEFAULT_PRF); return new SHA512Digest(); } } }
PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest()); gen.init("password".getBytes("UTF-8"), "salt".getBytes(), 4096); byte[] dk = ((KeyParameter) gen.generateDerivedParameters(256)).getKey();
private Digest getHashDigest() { if ("SHA3".equals(hashAlgorithm)) { return new SHA3Digest(); } else { // Default to SHA2 return new SHA256Digest(); } }
public static byte[] hmacSha512(byte[] key, byte[] input) { HMac hMac = new HMac(new SHA512Digest()); hMac.init(new KeyParameter(key)); hMac.update(input, 0, input.length); byte[] out = new byte[64]; hMac.doFinal(out, 0); return out; }
/** * Generate parameter hash for the given chaincode path,func and args * * @param path Chaincode path * @param func Chaincode function name * @param args List of arguments * @return hash of path, func and args */ public static String generateParameterHash(String path, String func, List<String> args) { logger.debug(format("GenerateParameterHash : path=%s, func=%s, args=%s", path, func, args)); // Append the arguments StringBuilder param = new StringBuilder(path); param.append(func); args.forEach(param::append); // Compute the hash return Hex.toHexString(hash(param.toString().getBytes(UTF_8), new SHA3Digest())); }
private byte[] generateKey(byte[] salt) throws UnsupportedEncodingException { PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest()); gen.init(this.passphrase.getBytes("UTF-8"), salt, PBKDF2_ITERATIONS); return ((KeyParameter) gen.generateDerivedParameters(AES_KEY_LENGTH_BITS)).getKey(); } }
/** * To create a binary seed from the mnemonic, we use the PBKDF2 function with a * mnemonic sentence (in UTF-8 NFKD) used as the password and the string "mnemonic" * + passphrase (again in UTF-8 NFKD) used as the salt. The iteration count is set * to 2048 and HMAC-SHA512 is used as the pseudo-random function. The length of the * derived key is 512 bits (= 64 bytes). * * @param mnemonic The input mnemonic which should be 128-160 bits in length containing * only valid words * @param passphrase The passphrase which will be used as part of salt for PBKDF2 * function * @return Byte array representation of the generated seed */ public static byte[] generateSeed(String mnemonic, String passphrase) { if (isMnemonicEmpty(mnemonic)) { throw new IllegalArgumentException("Mnemonic is required to generate a seed"); } passphrase = passphrase == null ? "" : passphrase; String salt = String.format("mnemonic%s", passphrase); PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA512Digest()); gen.init(mnemonic.getBytes(UTF_8), salt.getBytes(UTF_8), SEED_ITERATIONS); return ((KeyParameter) gen.generateDerivedParameters(SEED_KEY_SIZE)).getKey(); }
private static byte[] blake2HashStreaming(HashAlgorithm algorithm, InputStream value) throws IOException { int digestLengthBytes = algorithm.getDigestBytesLength(); Blake2bDigest blake2bDigest = new Blake2bDigest(digestLengthBytes * 8); byte[] rawHash = new byte[blake2bDigest.getDigestSize()]; final byte[] buffer = new byte[BUFFER_SIZE]; int read = value.read(buffer, 0, BUFFER_SIZE); while (read > -1) { blake2bDigest.update(buffer, 0, read); read = value.read(buffer, 0, BUFFER_SIZE); } blake2bDigest.doFinal(rawHash, 0); return rawHash; } }
byte[] toHash = Arrays.concatenate(buf, hashBuilder.toString().getBytes(UTF_8)); hashBuilder.setLength(0); hashBuilder.append(Hex.toHexString(hash(toHash, new SHA3Digest()))); } catch (IOException ex) { throw new RuntimeException(format("Error while reading file %s", file.getAbsolutePath()), ex);
private static byte[] generateAes128CtrDerivedKey( byte[] password, byte[] salt, int c, String prf) throws CipherException { if (!prf.equals("hmac-sha256")) { throw new CipherException("Unsupported prf:" + prf); } // Java 8 supports this, but you have to convert the password to a character array, see // http://stackoverflow.com/a/27928435/3211687 PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest()); gen.init(password, salt, c); return ((KeyParameter) gen.generateDerivedParameters(256)).getKey(); }
/** * Sign a hash with the private key of this key pair. * @param transactionHash the hash to sign * @return An {@link ECDSASignature} of the hash */ public ECDSASignature sign(byte[] transactionHash) { ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest())); ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKey, Sign.CURVE); signer.init(true, privKey); BigInteger[] components = signer.generateSignature(transactionHash); return new ECDSASignature(components[0], components[1]).toCanonicalised(); }
PKCS5S2ParametersGenerator generator = new PKCS5S2ParametersGenerator(new SHA256Digest()); generator.init(PBEParametersGenerator.PKCS5PasswordToUTF8Bytes(password), salt, iterations); KeyParameter key = (KeyParameter)generator.generateDerivedMacParameters(keySizeInBits);
byte[] getClientTLSCertificateDigest() { //The digest must be SHA256 over the DER encoded certificate. The PEM has the exact DER sequence in hex encoding around the begin and end markers if (tlsClientCertificatePEMBytes != null && clientTLSCertificateDigest == null) { String pemCert = new String(tlsClientCertificatePEMBytes, UTF_8); byte[] derBytes = Base64.getDecoder().decode( pemCert.replaceAll("-+[ \t]*(BEGIN|END)[ \t]+CERTIFICATE[ \t]*-+", "").replaceAll("\\s", "").trim() ); Digest digest = new SHA256Digest(); clientTLSCertificateDigest = new byte[digest.getDigestSize()]; digest.update(derBytes, 0, derBytes.length); digest.doFinal(clientTLSCertificateDigest, 0); } return clientTLSCertificateDigest; }
Digest md = new SHA256Digest() md.reset(); md.update(data, 0, data.length); byte[] hash = new byte[md.getDigestSize()]; md.doFinal(hash, 0);
private byte[] decryptWithLWCrypto(byte[] cipher, String password, byte[] salt, final int iterationCount) throws Exception { PKCS12ParametersGenerator pGen = new PKCS12ParametersGenerator(new SHA256Digest()); char[] passwordChars = password.toCharArray(); final byte[] pkcs12PasswordBytes = PBEParametersGenerator .PKCS12PasswordToBytes(passwordChars); pGen.init(pkcs12PasswordBytes, salt, iterationCount); CBCBlockCipher aesCBC = new CBCBlockCipher(new AESEngine()); ParametersWithIV aesCBCParams = (ParametersWithIV) pGen.generateDerivedParameters(256, 128); aesCBC.init(false, aesCBCParams); PaddedBufferedBlockCipher aesCipher = new PaddedBufferedBlockCipher(aesCBC, new PKCS7Padding()); byte[] plainTemp = new byte[aesCipher.getOutputSize(cipher.length)]; int offset = aesCipher.processBytes(cipher, 0, cipher.length, plainTemp, 0); int last = aesCipher.doFinal(plainTemp, offset); final byte[] plain = new byte[offset + last]; System.arraycopy(plainTemp, 0, plain, 0, plain.length); return plain; }