org.bouncycastle.crypto.digests.SHA256Digest Java Examples

The following examples show how to use org.bouncycastle.crypto.digests.SHA256Digest. 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: ECIESDemo.java    From ontology-java-sdk with GNU Lesser General Public License v3.0 9 votes vote down vote up
public static void main(String[] args) {

        try {
            OntSdk ontSdk = getOntSdk();

            com.github.ontio.account.Account account = new com.github.ontio.account.Account(Helper.hexToBytes("9a31d585431ce0aa0aab1f0a432142e98a92afccb7bcbcaff53f758df82acdb3"), ontSdk.defaultSignScheme);
            System.out.println("PrivateKey:"+Helper.toHexString(account.serializePrivateKey()));
            System.out.println("PublicKey:"+Helper.toHexString(account.serializePublicKey()));
//            System.out.println(Helper.toHexString(account.serializePrivateKey()));

            //setDigest
            ECIES.setDigest(new SHA256Digest());
            byte[] msg = new String("1234567890").getBytes();
            String[] ret = ECIES.Encrypt(Helper.toHexString(account.serializePublicKey()),msg);
            byte[] msg2 = ECIES.Decrypt(Helper.toHexString(account.serializePrivateKey()),ret);
//            byte[] msg3 = ECIES.Decrypt(account,ret);
            System.out.println("Msg:"+Helper.toHexString(msg));
            System.out.println("Encrypted:"+JSON.toJSONString(ret));
            System.out.println("Decrypt:"+Helper.toHexString(msg2));
//            System.out.println(Helper.toHexString(msg3));

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
 
Example #2
Source File: CryptoPrimitives.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
private Digest getHashDigest() {
    if ("SHA3".equals(hashAlgorithm)) {
        return new SHA3Digest();
    } else {
        // Default to SHA2
        return new SHA256Digest();
    }
}
 
Example #3
Source File: HttpEce.java    From webpush-java with MIT License 6 votes vote down vote up
/**
 * Convenience method for computing the HMAC Key Derivation Function. The real work is offloaded to BouncyCastle.
 */
protected static byte[] hkdfExpand(byte[] ikm, byte[] salt, byte[] info, int length) {
    log("salt", salt);
    log("ikm", ikm);
    log("info", info);

    HKDFBytesGenerator hkdf = new HKDFBytesGenerator(new SHA256Digest());
    hkdf.init(new HKDFParameters(ikm, salt, info));

    byte[] okm = new byte[length];
    hkdf.generateBytes(okm, 0, length);

    log("expand", okm);

    return okm;
}
 
Example #4
Source File: Signature.java    From evt4j with MIT License 6 votes vote down vote up
public static Signature signHash(byte[] hash, @NotNull PrivateKey key) {
    checkHashLength(hash);

    // init deterministic k calculator
    Signer signer = new Signer(new HMacDSAKCalculator(new SHA256Digest()));
    ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(key.getD(), ECKey.CURVE);

    signer.init(true, privateKeyParameters);
    BigInteger[] components = signer.generateSignature(hash);

    Signature sig = new Signature(components[0], components[1]).toCanonicalised();

    // find the recId and store in signature for public key recover later
    PublicKey publicKey = key.toPublicKey();
    int recId = getRecId(sig, hash, publicKey);

    if (recId == -1) {
        throw new RecoverIDNotFoundException();
    }

    sig.setRecId(recId);

    return sig;
}
 
Example #5
Source File: BouncyCastleCrypto.java    From fabric-api with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] sign(byte[] hash, byte[] privateKey) {
    ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
    signer.init(true, new ECPrivateKeyParameters(new BigInteger(privateKey), domain));
    BigInteger[] signature = signer.generateSignature(hash);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        DERSequenceGenerator seq = new DERSequenceGenerator(baos);
        seq.addObject(new ASN1Integer(signature[0]));
        seq.addObject(new ASN1Integer(toCanonicalS(signature[1])));
        seq.close();
        return baos.toByteArray();
    } catch (IOException e) {
        return new byte[0];
    }
}
 
Example #6
Source File: EscrowOperationsRecover.java    From InflatableDonkey with MIT License 6 votes vote down vote up
static NSDictionary decrypt(BlobA6 blob, byte[] key) {
    logger.debug("-- decrypt() - response blob: {}", blob);

    byte[] pcsData = AESCBC.decryptAESCBC(key, blob.iv(), blob.data());
    logger.debug("-- decrypt() - pcs data: 0x{}", Hex.toHexString(pcsData));

    BlobA0 pcsBlob = new BlobA0(ByteBuffer.wrap(pcsData));
    logger.debug("-- decrypt() - pcs blob: {}", pcsBlob);

    byte[] derivedKey
            = PBKDF2.generate(new SHA256Digest(), pcsBlob.dsid(), pcsBlob.salt(), pcsBlob.iterations(), 16 * 8);
    logger.debug("-- decrypt() - derived key: 0x{}", Hex.toHexString(derivedKey));

    byte[] saltIV = Arrays.copyOf(pcsBlob.salt(), 0x10);
    logger.debug("-- decrypt() - salt/ iv: 0x{}", Hex.toHexString(saltIV));

    byte[] dictionaryData = AESCBC.decryptAESCBC(derivedKey, saltIV, pcsBlob.data());
    logger.debug("-- decrypt() - dictionary data: 0x{}", Hex.toHexString(dictionaryData));

    NSDictionary dictionary = PListsLegacy.parseDictionary(dictionaryData);
    logger.debug("-- decrypt() - dictionary: {}", dictionary.toXMLPropertyList());
    return dictionary;
}
 
Example #7
Source File: HMacTest.java    From nuls-v2 with MIT License 6 votes vote down vote up
@Test
public void test() {
    String iv = "00000000000000000000000000000000";
    String pubKeyA = "0410baeeb267e1d680adf4e2ad0eb61b6a3173657971c0209425406883f09ac639c7dad2baf8ab2d66e6b64c3cbd4dd488de91cc47b5ead45db299a929c4ebd468";
    String ciphertext = "b4d6ecbd61b3630abf609e102fcbd125";
    String dataToMac = iv + pubKeyA + ciphertext;
    String macKey = "785ac461b5c8607c39ec4f63e1004f19a77c371e6f91293f66d4c19c02524265";
    HMac mac = new HMac(new SHA256Digest());
    mac.init(new KeyParameter(HexUtil.decode(macKey)));

    byte[] byteArray = HexUtil.decode(dataToMac);
    mac.update(byteArray, 0, byteArray.length);
    byte[] macOutput = new byte[mac.getMacSize()];
    mac.doFinal(macOutput, 0);
    System.out.println(HexUtil.encode(macOutput));
    // hmac hex string: bcf0e6f47bf5622e3596104f4d1bcd0bc4f643a196f0520be834bb0b4d1043fa
}
 
Example #8
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 #9
Source File: KeyBlobCurve25519Unwrap.java    From InflatableDonkey with MIT License 6 votes vote down vote up
public static Optional<byte[]> curve25519Unwrap(
        byte[] myPublicKey,
        byte[] myPrivateKey,
        byte[] otherPublicKey,
        byte[] wrappedKey) {

    SHA256Digest sha256 = new SHA256Digest();

    byte[] shared = Curve25519.agreement(otherPublicKey, myPrivateKey);
    logger.debug("-- curve25519Unwrap() - shared agreement: 0x{}", Hex.toHexString(shared));

    // Stripped down NIST SP 800-56A KDF.
    byte[] counter = new byte[]{0x00, 0x00, 0x00, 0x01};
    byte[] hash = new byte[sha256.getDigestSize()];

    sha256.reset();
    sha256.update(counter, 0, counter.length);
    sha256.update(shared, 0, shared.length);
    sha256.update(otherPublicKey, 0, otherPublicKey.length);
    sha256.update(myPublicKey, 0, myPublicKey.length);
    sha256.doFinal(hash, 0);

    logger.debug("-- curve25519Unwrap() - kek: {}", Hex.toHexString(hash));
    return RFC3394Wrap.unwrapAES(hash, wrappedKey);
}
 
Example #10
Source File: BouncyCastleCrypto.java    From fabric-api-archive with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] sign(byte[] hash, byte[] privateKey) {
    ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
    signer.init(true, new ECPrivateKeyParameters(new BigInteger(privateKey), domain));
    BigInteger[] signature = signer.generateSignature(hash);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        DERSequenceGenerator seq = new DERSequenceGenerator(baos);
        seq.addObject(new ASN1Integer(signature[0]));
        seq.addObject(new ASN1Integer(toCanonicalS(signature[1])));
        seq.close();
        return baos.toByteArray();
    } catch (IOException e) {
        return new byte[0];
    }
}
 
Example #11
Source File: Endpoint.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #12
Source File: ECKeyPair.java    From bop-bitcoin-client with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] sign (byte[] hash) throws ValidationException
{
	if ( priv == null )
	{
		throw new ValidationException ("Need private key to sign");
	}
	ECDSASigner signer = new ECDSASigner (new HMacDSAKCalculator (new SHA256Digest ()));
	signer.init (true, new ECPrivateKeyParameters (priv, domain));
	BigInteger[] signature = signer.generateSignature (hash);
	ByteArrayOutputStream s = new ByteArrayOutputStream ();
	try
	{
		DERSequenceGenerator seq = new DERSequenceGenerator (s);
		seq.addObject (new ASN1Integer (signature[0]));
		seq.addObject (new ASN1Integer (signature[1]));
		seq.close ();
		return s.toByteArray ();
	}
	catch ( IOException e )
	{
	}
	return null;
}
 
Example #13
Source File: ECKeyPair.java    From WalletCordova with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public byte[] sign (byte[] hash) throws ValidationException
{
	if ( priv == null )
	{
		throw new ValidationException ("Need private key to sign");
	}
	ECDSASigner signer = new ECDSASigner (new HMacDSAKCalculator (new SHA256Digest ()));
	signer.init (true, new ECPrivateKeyParameters (priv, domain));
	BigInteger[] signature = signer.generateSignature (hash);
	ByteArrayOutputStream s = new ByteArrayOutputStream ();
	try
	{
		DERSequenceGenerator seq = new DERSequenceGenerator (s);
		seq.addObject (new ASN1Integer (signature[0]));
		seq.addObject (new ASN1Integer (signature[1]));
		seq.close ();
		return s.toByteArray ();
	}
	catch ( IOException e )
	{
	}
	return null;
}
 
Example #14
Source File: BouncyCastleSHA256.java    From pluotsorbet with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String args[]) {
    byte[] digest = new byte[4096];
    for (int i = 0; i < digest.length; i++) {
        digest[i] = (byte)i;
    }

    long start = JVM.monotonicTimeMillis();
    for (int i = 0; i < 20; i++) {
        SHA256Digest digester = new SHA256Digest();
        byte[] retValue = new byte[digester.getDigestSize()];
        for (int j = 0; j < UPDATES; j++) {
            digester.update(digest, 0, digest.length);
        }
        digester.doFinal(retValue, 0);
    }
    long time = JVM.monotonicTimeMillis() - start;
    System.out.println("BouncyCastleSHA256: " + time);
}
 
Example #15
Source File: TestBouncyCastleSHA256.java    From pluotsorbet with GNU General Public License v2.0 6 votes vote down vote up
public void test(TestHarness th) {
    SHA256Digest md = new SHA256Digest();
    byte[] retValue = new byte[md.getDigestSize()];

    for (int i = 0; i < messages.length; i++) {
        byte[] bytes = messages[i].getBytes();
        md.update(bytes, 0, bytes.length);
        md.doFinal(retValue, 0);
        th.check(Util.hexEncode(retValue).toLowerCase(), digests[i]);
    }

    for (int i = 0; i < 1000000; i++) {
        md.update((byte)'a');
    }
    md.doFinal(retValue, 0);
    th.check(Util.hexEncode(retValue).toLowerCase(), MILLION_A_DIGEST);
}
 
Example #16
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 #17
Source File: ECKeyPair.java    From web3j with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #18
Source File: FileKeyFactory.java    From LiquidDonkey with MIT License 5 votes vote down vote up
ByteString unwrapCurve25519(KeyBag keyBag, int protectionClass, ByteString key, AESWrap aesWrap, SHA256Digest sha256) {
    if (key.size() != 0x48) {
        logger.warn("-- unwrapCurve25519() > bad key length: {}", Bytes.hex(key));
        return null;
    }

    byte[] myPrivateKey = keyBag.classKey(protectionClass, "KEY").toByteArray();
    if (myPrivateKey == null) {
        logger.warn("-- unwrapCurve25519() > no KEY key for protection class: {}", protectionClass);
        return null;
    }

    byte[] myPublicKey = keyBag.classKey(protectionClass, "PBKY").toByteArray();
    if (myPublicKey == null) {
        logger.warn("-- unwrapCurve25519() > no PBKY key for protection class: {}", protectionClass);
        return null;
    }

    byte[] otherPublicKey = key.substring(0, 32).toByteArray();
    byte[] shared = Curve25519.create().agreement(otherPublicKey, myPrivateKey);
    byte[] pad = new byte[]{0x00, 0x00, 0x00, 0x01};
    byte[] hash = new byte[sha256.getDigestSize()];

    sha256.reset();
    sha256.update(pad, 0, pad.length);
    sha256.update(shared, 0, shared.length);
    sha256.update(otherPublicKey, 0, otherPublicKey.length);
    sha256.update(myPublicKey, 0, myPublicKey.length);
    sha256.doFinal(hash, 0);

    try {
        return ByteString.copyFrom(aesWrap.unwrap(hash, key.substring(0x20, key.size()).toByteArray()));
    } catch (IllegalStateException | InvalidCipherTextException ex) {
        logger.warn("-- unwrapCurve25519() > failed to unwrap key: {} protection class: {} exception: {}",
                Bytes.hex(key), protectionClass, ex);
        return null;
    }
}
 
Example #19
Source File: ECKey.java    From bushido-java-core with GNU General Public License v3.0 5 votes vote down vote up
public byte[] sign(byte[] message) throws Exception
{
    if (priv == null) {
        throw new Exception("Unable to sign");
    }
    ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
    signer.init(true, new ECPrivateKeyParameters(priv, params));
    BigInteger[] signature = signer.generateSignature(message);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    DERSequenceGenerator seqGen = new DERSequenceGenerator(outputStream);
    seqGen.addObject(new ASN1Integer(signature[0]));
    seqGen.addObject(new ASN1Integer(signature[1]));
    seqGen.close();
    return outputStream.toByteArray();
}
 
Example #20
Source File: ValidationChecksum.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
private byte[] calculateChecksum() {
    final SHA256Digest digest = new SHA256Digest();
    final byte[] result = new byte[digest.getDigestSize()];
    for (final Artifact artifact : this.artifacts) {
        final byte[] id = artifact.getId().getBytes(UTF_8);
        digest.update(id, 0, id.length);
        digest.update((byte) '\0');
    }
    digest.doFinal(result, 0);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Checksum of resolved artifacts: {}", ByteUtils.toHexString(result, "0x", ""));
    }
    return result;
}
 
Example #21
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 #22
Source File: KeyID.java    From InflatableDonkey with MIT License 5 votes vote down vote up
static byte[] id(byte[] data) {
    // SHA256 truncated to 20 bytes. 
    Digest digest = new SHA256Digest();
    byte[] out = new byte[digest.getDigestSize()];

    digest.update(data, 0, data.length);
    digest.doFinal(out, 0);

    return Arrays.copyOf(out, 20);
}
 
Example #23
Source File: RFC6637Factory.java    From InflatableDonkey with MIT License 5 votes vote down vote up
public static synchronized RFC6637 secp256r1() {
    if (SECP256R1 == null) {
        SECP256R1 = create(
                "secp256r1",
                SHA256Digest::new,
                () -> new RFC3394WrapEngine(new AESFastEngine()),
                RFC6637Constants.ECDH,
                RFC6637Constants.AES_128,
                0x10,
                RFC6637Constants.SHA256);
    }

    return SECP256R1;
}
 
Example #24
Source File: PZAssistantLight.java    From InflatableDonkey with MIT License 5 votes vote down vote up
public Optional<byte[]> unwrap(ECPublicKey otherPublicKey, ECPrivateKey myPrivateKey, Digest digest, byte[] wrappedKey) {
    byte[] S = myPrivateKey.agreement(otherPublicKey);
    logger.debug("-- unwrap() - shared secret: 0x{}", Hex.toHexString(S));

    byte[] salt = myPrivateKey.publicKey().point().xEncoded();
    logger.debug("-- unwrap() - salt: 0x{}", Hex.toHexString(salt));

    byte[] dk = RFC5869KDF.apply(S, salt, info, SHA256Digest::new, keyLength);
    logger.debug("-- unwrap() - dk: 0x{}", Hex.toHexString(salt));

    Optional<byte[]> unwrapped = RFC3394Wrap.unwrapAES(dk, wrappedKey);
    logger.debug("-- unwrap() - unwrapped key: 0x{}", unwrapped.map(Hex::toHexString));

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

		HMac hmac = new HMac(new SHA256Digest());
		byte[] result = new byte[hmac.getMacSize()];
		hmac.init(new KeyParameter(key));
		hmac.reset();
		hmac.update(msg, 0, msg.length);
		hmac.doFinal(result, 0);
		return result;
	}
 
Example #26
Source File: CryptoPrimitives.java    From Clusion with GNU General Public License v3.0 5 votes vote down vote up
public static byte[] generateHmac(byte[] key, String msg) throws UnsupportedEncodingException {

		HMac hmac = new HMac(new SHA256Digest());
		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 #27
Source File: PcfAuthentication.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
private static String doSign(byte[] message, String instanceKeyPem) throws CryptoException {

		RSAPrivateKeySpec privateKey = PemObject.fromKey(instanceKeyPem).getRSAKeySpec();
		PSSSigner signer = new PSSSigner(new RSAEngine(), new SHA256Digest(), SALT_LENGTH);

		signer.init(true, new RSAKeyParameters(true, privateKey.getModulus(), privateKey.getPrivateExponent()));
		signer.update(message, 0, message.length);

		byte[] signature = signer.generateSignature();
		return Base64Utils.encodeToUrlSafeString(signature);
	}
 
Example #28
Source File: Smb3KeyDerivation.java    From jcifs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @param sessionKey
 * @param label
 * @param context
 */
private static byte[] derive ( byte[] sessionKey, byte[] label, byte[] context ) {
    KDFCounterBytesGenerator gen = new KDFCounterBytesGenerator(new HMac(new SHA256Digest()));

    int r = 32;
    byte[] suffix = new byte[label.length + context.length + 5];
    // per bouncycastle
    // <li>1: K(i) := PRF( KI, [i]_2 || Label || 0x00 || Context || [L]_2 ) with the counter at the very beginning
    // of the fixedInputData (The default implementation has this format)</li>
    // with the parameters
    // <li>1. KDFCounterParameters(ki, null, "Label || 0x00 || Context || [L]_2]", 8);

    // all fixed inputs go into the suffix:
    // + label
    System.arraycopy(label, 0, suffix, 0, label.length);
    // + 1 byte 0x00
    // + context
    System.arraycopy(context, 0, suffix, label.length + 1, context.length);
    // + 4 byte (== r bits) big endian encoding of L
    suffix[ suffix.length - 1 ] = (byte) 128;

    DerivationParameters param = new KDFCounterParameters(sessionKey, null /* prefix */, suffix /* suffix */, r /* r */);
    gen.init(param);

    byte[] derived = new byte[16];
    gen.generateBytes(derived, 0, 16);
    return derived;
}
 
Example #29
Source File: Wallet.java    From web3j with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #30
Source File: Crypto.java    From webauthndemo with Apache License 2.0 5 votes vote down vote up
public static byte[] hkdfSha256(byte[] ikm, byte[] salt, byte[] info, int outputLength) {
  byte[] output = new byte[outputLength];
  HKDFParameters params = new HKDFParameters(ikm, salt, info);
  HKDFBytesGenerator hkdf = new HKDFBytesGenerator(new SHA256Digest());
  hkdf.init(params);
  hkdf.generateBytes(output, 0, outputLength);
  return output;
}