org.bouncycastle.crypto.digests.SHA512Digest Java Examples

The following examples show how to use org.bouncycastle.crypto.digests.SHA512Digest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Mnemonic.java    From hedera-sdk-java with Apache License 2.0 6 votes vote down vote up
@Internal
public byte[] toSeed(String passphrase) {
    final String salt = "mnemonic" + passphrase;

    // BIP-39 seed generation
    final PKCS5S2ParametersGenerator pbkdf2 = new PKCS5S2ParametersGenerator(new SHA512Digest());
    pbkdf2.init(
        toString().getBytes(StandardCharsets.UTF_8),
        salt.getBytes(StandardCharsets.UTF_8),
        2048);

    final KeyParameter key = (KeyParameter) pbkdf2.generateDerivedParameters(512);
    return key.getKey();
}
 
Example #2
Source File: Ed25519PrivateKey.java    From hedera-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Recover a private key from a generated mnemonic phrase and a passphrase.
 * <p>
 * This is not compatible with the phrases generated by the Android and iOS wallets;
 * use the no-passphrase version instead.
 *
 * @param mnemonic   the mnemonic phrase which should be a 24 byte list of words.
 * @param passphrase the passphrase used to protect the mnemonic (not used in the
 *                   mobile wallets, use {@link #fromMnemonic(Mnemonic)} instead.)
 * @return the recovered key; use {@link #derive(int)} to get a key for an account index (0
 * for default account)
 */
public static Ed25519PrivateKey fromMnemonic(Mnemonic mnemonic, String passphrase) {
    final byte[] seed = mnemonic.toSeed(passphrase);

    final HMac hmacSha512 = new HMac(new SHA512Digest());
    hmacSha512.init(new KeyParameter("ed25519 seed".getBytes(StandardCharsets.UTF_8)));
    hmacSha512.update(seed, 0, seed.length);

    final byte[] derivedState = new byte[hmacSha512.getMacSize()];
    hmacSha512.doFinal(derivedState, 0);

    Ed25519PrivateKey derivedKey = derivableKey(derivedState);

    // BIP-44 path with the Hedera Hbar coin-type (omitting key index)
    // we pre-derive most of the path as the mobile wallets don't expose more than the index
    // https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
    // https://github.com/satoshilabs/slips/blob/master/slip-0044.md
    for (int index : new int[]{44, 3030, 0, 0}) {
        derivedKey = derivedKey.derive(index);
    }

    return derivedKey;
}
 
Example #3
Source File: PBKDF2CipherProvider.java    From nifi with Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example #4
Source File: PBKDF2CipherProvider.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example #5
Source File: FinalPairHandler.java    From HAP-Java with MIT License 6 votes vote down vote up
private HttpResponse createUser(byte[] username, byte[] ltpk, byte[] proof) throws Exception {
  HKDFBytesGenerator hkdf = new HKDFBytesGenerator(new SHA512Digest());
  hkdf.init(
      new HKDFParameters(
          k,
          "Pair-Setup-Controller-Sign-Salt".getBytes(StandardCharsets.UTF_8),
          "Pair-Setup-Controller-Sign-Info".getBytes(StandardCharsets.UTF_8)));
  byte[] okm = new byte[32];
  hkdf.generateBytes(okm, 0, 32);

  byte[] completeData = ByteUtils.joinBytes(okm, username, ltpk);

  if (!new EdsaVerifier(ltpk).verify(completeData, proof)) {
    throw new Exception("Invalid signature");
  }
  authInfo.createUser(authInfo.getMac() + new String(username, StandardCharsets.UTF_8), ltpk);
  return createResponse();
}
 
Example #6
Source File: TOTPMIDletTest.java    From totp-me with Apache License 2.0 5 votes vote down vote up
public void testTOTP() {
	HMac sha1Hmac = new HMac(new SHA1Digest());
	sha1Hmac.init(new KeyParameter(seed20));
	HMac sha256Hmac = new HMac(new SHA256Digest());
	sha256Hmac.init(new KeyParameter(seed32));
	HMac sha512Hmac = new HMac(new SHA512Digest());
	sha512Hmac.init(new KeyParameter(seed64));
	for (int i = 0; i < TEST_TIME.length; i++) {
		long counter = TOTPMIDlet.getCounter(TEST_TIME[i], TIMESTEP);
		assertEquals(SHA1_VALUES[i], TOTPMIDlet.genToken(counter, sha1Hmac, DIGITS));
		assertEquals(SHA256_VALUES[i], TOTPMIDlet.genToken(counter, sha256Hmac, DIGITS));
		assertEquals(SHA512_VALUES[i], TOTPMIDlet.genToken(counter, sha512Hmac, DIGITS));
	}
}
 
Example #7
Source File: DSAParameterCache.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static DSAParameterSpec getNewDSAParameterSpec(int plength, int qlength,
    SecureRandom random) {
  final int certainty = 80;
  SecureRandom tmpRandom = (random == null) ? new SecureRandom() : random;
  DSAParametersGenerator paramGen = new DSAParametersGenerator(new SHA512Digest());
  DSAParameterGenerationParameters genParams =
      new DSAParameterGenerationParameters(plength, qlength, certainty, tmpRandom);
  paramGen.init(genParams);
  DSAParameters dsaParams = paramGen.generateParameters();
  return new DSAParameterSpec(dsaParams.getP(), dsaParams.getQ(), dsaParams.getG());
}
 
Example #8
Source File: PairVerificationManager.java    From HAP-Java with MIT License 5 votes vote down vote up
private byte[] createKey(String info) {
  HKDFBytesGenerator hkdf = new HKDFBytesGenerator(new SHA512Digest());
  hkdf.init(
      new HKDFParameters(
          sharedSecret,
          "Control-Salt".getBytes(StandardCharsets.UTF_8),
          info.getBytes(StandardCharsets.UTF_8)));
  byte[] key = new byte[32];
  hkdf.generateBytes(key, 0, 32);
  return key;
}
 
Example #9
Source File: PairVerificationManager.java    From HAP-Java with MIT License 5 votes vote down vote up
private HttpResponse stage1(Stage1Request request) throws Exception {
  logger.trace("Starting pair verification for " + registry.getLabel());
  clientPublicKey = request.getClientPublicKey();
  publicKey = new byte[32];
  byte[] privateKey = new byte[32];
  getSecureRandom().nextBytes(privateKey);
  Curve25519.keygen(publicKey, null, privateKey);

  sharedSecret = new byte[32];
  Curve25519.curve(sharedSecret, privateKey, clientPublicKey);

  byte[] material =
      ByteUtils.joinBytes(
          publicKey, authInfo.getMac().getBytes(StandardCharsets.UTF_8), clientPublicKey);

  byte[] proof = new EdsaSigner(authInfo.getPrivateKey()).sign(material);

  HKDFBytesGenerator hkdf = new HKDFBytesGenerator(new SHA512Digest());
  hkdf.init(
      new HKDFParameters(
          sharedSecret,
          "Pair-Verify-Encrypt-Salt".getBytes(StandardCharsets.UTF_8),
          "Pair-Verify-Encrypt-Info".getBytes(StandardCharsets.UTF_8)));
  hkdfKey = new byte[32];
  hkdf.generateBytes(hkdfKey, 0, 32);

  Encoder encoder = TypeLengthValueUtils.getEncoder();
  encoder.add(MessageType.USERNAME, authInfo.getMac().getBytes(StandardCharsets.UTF_8));
  encoder.add(MessageType.SIGNATURE, proof);
  byte[] plaintext = encoder.toByteArray();

  ChachaEncoder chacha = new ChachaEncoder(hkdfKey, "PV-Msg02".getBytes(StandardCharsets.UTF_8));
  byte[] ciphertext = chacha.encodeCiphertext(plaintext);

  encoder = TypeLengthValueUtils.getEncoder();
  encoder.add(MessageType.STATE, (short) 2);
  encoder.add(MessageType.ENCRYPTED_DATA, ciphertext);
  encoder.add(MessageType.PUBLIC_KEY, publicKey);
  return new PairingResponse(encoder.toByteArray());
}
 
Example #10
Source File: FinalPairHandler.java    From HAP-Java with MIT License 5 votes vote down vote up
private HttpResponse createResponse() throws Exception {
  HKDFBytesGenerator hkdf = new HKDFBytesGenerator(new SHA512Digest());
  hkdf.init(
      new HKDFParameters(
          k,
          "Pair-Setup-Accessory-Sign-Salt".getBytes(StandardCharsets.UTF_8),
          "Pair-Setup-Accessory-Sign-Info".getBytes(StandardCharsets.UTF_8)));
  byte[] okm = new byte[32];
  hkdf.generateBytes(okm, 0, 32);

  EdsaSigner signer = new EdsaSigner(authInfo.getPrivateKey());

  byte[] material =
      ByteUtils.joinBytes(
          okm, authInfo.getMac().getBytes(StandardCharsets.UTF_8), signer.getPublicKey());

  byte[] proof = signer.sign(material);

  Encoder encoder = TypeLengthValueUtils.getEncoder();
  encoder.add(MessageType.USERNAME, authInfo.getMac().getBytes(StandardCharsets.UTF_8));
  encoder.add(MessageType.PUBLIC_KEY, signer.getPublicKey());
  encoder.add(MessageType.SIGNATURE, proof);
  byte[] plaintext = encoder.toByteArray();

  ChachaEncoder chacha =
      new ChachaEncoder(hkdf_enc_key, "PS-Msg06".getBytes(StandardCharsets.UTF_8));
  byte[] ciphertext = chacha.encodeCiphertext(plaintext);

  encoder = TypeLengthValueUtils.getEncoder();
  encoder.add(MessageType.STATE, (short) 6);
  encoder.add(MessageType.ENCRYPTED_DATA, ciphertext);

  return new PairingResponse(encoder.toByteArray());
}
 
Example #11
Source File: FinalPairHandler.java    From HAP-Java with MIT License 5 votes vote down vote up
public HttpResponse handle(PairSetupRequest req) throws Exception {
  HKDFBytesGenerator hkdf = new HKDFBytesGenerator(new SHA512Digest());
  hkdf.init(
      new HKDFParameters(
          k,
          "Pair-Setup-Encrypt-Salt".getBytes(StandardCharsets.UTF_8),
          "Pair-Setup-Encrypt-Info".getBytes(StandardCharsets.UTF_8)));
  byte[] okm = hkdf_enc_key = new byte[32];
  hkdf.generateBytes(okm, 0, 32);

  return decrypt((Stage3Request) req, okm);
}
 
Example #12
Source File: SignatureAssistant.java    From InflatableDonkey with MIT License 5 votes vote down vote up
static Optional<Digest> digest(Signature signature) {
    switch (signature.type()) {
        case 0x01:
            return Optional.ofNullable(new SHA256Digest());
        case 0x02:
            return Optional.ofNullable(new SHA512Digest());
        default:
            logger.warn("-- digest() - unsupported signature type: {}", signature);
            return Optional.empty();
    }
}
 
Example #13
Source File: RFC6637Factory.java    From InflatableDonkey with MIT License 5 votes vote down vote up
public static synchronized RFC6637 secp521r1() {
    if (SECP521R1 == null) {
        SECP521R1 = create(
                "secp521r1",
                SHA512Digest::new,
                () -> new RFC3394WrapEngine(new AESFastEngine()),
                RFC6637Constants.ECDH,
                RFC6637Constants.AES_256,
                0x20,
                RFC6637Constants.SHA512);
    }

    return SECP521R1;
}
 
Example #14
Source File: CryptoPrimitives.java    From Clusion with GNU General Public License v3.0 5 votes vote down vote up
public static byte[] generateHmac512(byte[] key, String msg) throws UnsupportedEncodingException {

		HMac hmac = new HMac(new SHA512Digest());
		byte[] result = new byte[hmac.getMacSize()];
		byte[] msgAry = msg.getBytes("UTF-8");
		hmac.init(new KeyParameter(key));
		hmac.reset();
		hmac.update(msgAry, 0, msgAry.length);
		hmac.doFinal(result, 0);
		return result;
	}
 
Example #15
Source File: MnemonicUtils.java    From web3j with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #16
Source File: Hash.java    From web3j with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #17
Source File: Hash.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #18
Source File: MnemonicUtils.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #19
Source File: Sha512Hash.java    From nuls-v2 with MIT License 5 votes vote down vote up
public static byte[] sha512(byte[] bytes) {
    Digest digest = new SHA512Digest();
    digest.update(bytes, 0, bytes.length);
    byte[] rsData = new byte[digest.getDigestSize()];
    digest.doFinal(rsData, 0);
    return rsData;
}
 
Example #20
Source File: Sha512Test.java    From nuls-v2 with MIT License 5 votes vote down vote up
@Test
public void test() {
    byte[] bytes = HexUtil.decode("92d1552a53f2b526895542131bc768eae406ece0b8f5437631d5b0cc750b89e6");
    Digest digest = new SHA512Digest();
    digest.update(bytes, 0, bytes.length);
    byte[] rsData = new byte[digest.getDigestSize()];
    digest.doFinal(rsData, 0);
    int[] result = uint8Array(rsData);
    System.out.println(HexUtil.encode(rsData));
    System.out.println(Arrays.toString(result));
    // sha512 hex string: fc72ef919a913dd93d4d83215c0db7a9895c82aee1987c2cefdf1911caee2a154039be04f02552cf6870f3aa0ada43af8c02b3d20e5db90c5ae2ea146f6824ab
}
 
Example #21
Source File: Digest.java    From ontology-java-sdk with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static byte[] hmacSha512(byte[] keyBytes, byte[] text) {
	HMac hmac = new HMac(new SHA512Digest());
	byte[] resBuf = new byte[hmac.getMacSize()];
	CipherParameters pm = new KeyParameter(keyBytes);
	hmac.init(pm);
	hmac.update(text, 0, text.length);
	hmac.doFinal(resBuf, 0);
	return resBuf;
}
 
Example #22
Source File: BouncyCastleSha512Provider.java    From curve25519-java with GNU General Public License v3.0 4 votes vote down vote up
public void calculateDigest(byte[] out, byte[] in, long length) {
  SHA512Digest digest = new SHA512Digest();
  digest.update(in, 0, (int)length);
  digest.doFinal(out, 0);
}
 
Example #23
Source File: BouncyCastleHasher.java    From hash-bench with MIT License 4 votes vote down vote up
public static final void register(final Map<String, Hasher> hashers) {
  hashers.put(BouncyCastleHasher.GOST,
          new BouncyCastleHasher(new GOST3411Digest()));
  hashers.put(BouncyCastleHasher.MD2,
          new BouncyCastleHasher(new MD2Digest()));
  hashers.put(BouncyCastleHasher.MD4,
          new BouncyCastleHasher(new MD4Digest()));
  hashers.put(BouncyCastleHasher.MD5,
          new BouncyCastleHasher(new MD5Digest()));
  hashers.put(BouncyCastleHasher.RIPEMD128,
          new BouncyCastleHasher(new RIPEMD128Digest()));
  hashers.put(BouncyCastleHasher.RIPEMD160,
          new BouncyCastleHasher(new RIPEMD160Digest()));
  hashers.put(BouncyCastleHasher.RIPEMD256,
          new BouncyCastleHasher(new RIPEMD256Digest()));
  hashers.put(BouncyCastleHasher.RIPEMD320,
          new BouncyCastleHasher(new RIPEMD320Digest()));
  hashers.put(BouncyCastleHasher.SHA1,
          new BouncyCastleHasher(new SHA1Digest()));
  hashers.put(BouncyCastleHasher.SHA224,
          new BouncyCastleHasher(new SHA224Digest()));
  hashers.put(BouncyCastleHasher.SHA256,
          new BouncyCastleHasher(new SHA256Digest()));
  hashers.put(BouncyCastleHasher.SHA3,
          new BouncyCastleHasher(new SHA3Digest()));
  hashers.put(BouncyCastleHasher.SHA384,
          new BouncyCastleHasher(new SHA384Digest()));
  hashers.put(BouncyCastleHasher.SHA512,
          new BouncyCastleHasher(new SHA512Digest()));
  hashers.put(BouncyCastleHasher.SHA512_T,
          new BouncyCastleHasher(new SHA512tDigest(7 * 8)));
  hashers.put(BouncyCastleHasher.SKEIN1024, new BouncyCastleHasher(
          new SkeinDigest(SkeinDigest.SKEIN_1024, Long.BYTES * 8)));
  hashers.put(BouncyCastleHasher.SKEIN256, new BouncyCastleHasher(
          new SkeinDigest(SkeinDigest.SKEIN_256, Long.BYTES * 8)));
  hashers.put(BouncyCastleHasher.SKEIN512, new BouncyCastleHasher(
          new SkeinDigest(SkeinDigest.SKEIN_512, Long.BYTES * 8)));
  hashers.put(BouncyCastleHasher.SM3,
          new BouncyCastleHasher(new SM3Digest()));
  hashers.put(BouncyCastleHasher.TIGER,
          new BouncyCastleHasher(new TigerDigest()));
  hashers.put(BouncyCastleHasher.WHIRLPOOL2,
          new BouncyCastleHasher(new WhirlpoolDigest()));
}
 
Example #24
Source File: MnemonicUtils.java    From blockchain with Apache License 2.0 3 votes vote down vote up
/**
 * 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) {
    validateMnemonic(mnemonic);
    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();
}
 
Example #25
Source File: MnemonicUtils.java    From etherscan-explorer with GNU General Public License v3.0 3 votes vote down vote up
/**
 * 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) {
    validateMnemonic(mnemonic);
    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();
}
 
Example #26
Source File: MnemonicUtils.java    From client-sdk-java with Apache License 2.0 3 votes vote down vote up
/**
 * 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();
}