List of usage examples for org.bouncycastle.crypto.params HKDFParameters HKDFParameters
public HKDFParameters(final byte[] ikm, final byte[] salt, final byte[] info)
From source file:com.amazonaws.encryptionsdk.CryptoAlgorithm.java
License:Open Source License
public SecretKey getEncryptionKeyFromDataKey(final SecretKey dataKey, final CiphertextHeaders headers) throws InvalidKeyException { if (!dataKey.getAlgorithm().equalsIgnoreCase(getDataKeyAlgo())) { throw new InvalidKeyException("DataKey of incorrect algorithm. Expected " + getDataKeyAlgo() + " but was " + dataKey.getAlgorithm()); }// w ww.j a v a 2s. c o m final Digest dgst; switch (this) { case ALG_AES_128_GCM_IV12_TAG16_NO_KDF: case ALG_AES_192_GCM_IV12_TAG16_NO_KDF: case ALG_AES_256_GCM_IV12_TAG16_NO_KDF: return dataKey; case ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256: case ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA256: case ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256: case ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256: dgst = new SHA256Digest(); break; case ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384: case ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384: dgst = new SHA384Digest(); break; default: throw new UnsupportedOperationException("Support for " + this + " not yet built."); } if (!dataKey.getFormat().equalsIgnoreCase("RAW")) { throw new InvalidKeyException( "Currently only RAW format keys are supported for HKDF algorithms. Actual format was " + dataKey.getFormat()); } final byte[] messageId = headers.getMessageId(); final ByteBuffer info = ByteBuffer.allocate(messageId.length + 2); info.order(ByteOrder.BIG_ENDIAN); info.putShort(getValue()); info.put(messageId); final byte[] rawDataKey = dataKey.getEncoded(); if (rawDataKey.length != getDataKeyLength()) { throw new InvalidKeyException("DataKey of incorrect length. Expected " + getDataKeyLength() + " but was " + rawDataKey.length); } final byte[] rawEncKey = new byte[getKeyLength()]; final HKDFBytesGenerator hkdf = new HKDFBytesGenerator(dgst); hkdf.init(new HKDFParameters(rawDataKey, null, info.array())); hkdf.generateBytes(rawEncKey, 0, getKeyLength()); return new SecretKeySpec(rawEncKey, getKeyAlgo()); }
From source file:com.github.horrorho.inflatabledonkey.crypto.RFC5869KDF.java
License:Open Source License
public static final byte[] apply(byte[] ikm, byte[] salt, byte[] info, Supplier<Digest> digestSupplier, int keyLengthBytes) { logger.trace("<< apply() - ikm: 0x{} salt: 0x{} info: 0x{} digestSupplier: {} keyLengthBytes: {}", Hex.toHexString(ikm), Hex.toHexString(salt), Hex.toHexString(info), digestSupplier, keyLengthBytes); Digest hash = digestSupplier.get();// ww w .j ava2s . c o m byte[] okm = new byte[keyLengthBytes]; HKDFParameters params = new HKDFParameters(ikm, salt, info); HKDFBytesGenerator hkdf = new HKDFBytesGenerator(hash); hkdf.init(params); hkdf.generateBytes(okm, 0, keyLengthBytes); logger.trace(">> apply() - output keying material: 0x{}", Hex.toHexString(okm)); return okm; }
From source file:eu.betaas.taas.securitymanager.common.mqv.ECMQVUtils.java
License:Apache License
/** * A method to derive a new key using HKDF (Hash based Key Derivation Function) * @param keyIn: an "original" key to be derived * @param keyOutLenByte: the length of the new derived (output) key in byte * @return //from w w w .j a v a 2 s. com */ public static byte[] deriveKeyHKDF(byte[] keyIn, int keyOutLenByte) { DerivationParameters kdfParam = new HKDFParameters(keyIn, null, intToByteArray(keyOutLenByte * 8)); HKDFBytesGenerator hkdfGen = new HKDFBytesGenerator(new SHA1Digest()); hkdfGen.init(kdfParam); // initialize the new key with size of L bits (or L/8 bytes) byte[] newKey = new byte[keyOutLenByte]; hkdfGen.generateBytes(newKey, 0, keyOutLenByte); return newKey; }
From source file:me.grapebaba.hyperledger.fabric.Crypto.java
License:Apache License
public ByteString eciesDecrypt(PrivateKey recipientPrivateKey, ByteString cipherText) { BCECPrivateKey bcecPrivateKey = (BCECPrivateKey) recipientPrivateKey; ECNamedCurveSpec ecNamedCurveSpec = (ECNamedCurveSpec) bcecPrivateKey.getParams(); int level = SecurityLevel.from(ecNamedCurveSpec.getName()).size(); //cipherText = ephemeralPubKeyBytes + encryptedTokBytes + macBytes //ephemeralPubKeyBytes = first ((384+7)/8)*2 + 1 bytes = first 97 bytes //hmac is sha3_384 = 48 bytes or sha3_256 = 32 bytes int ephemeralPubKeyLength = ((level + 7) / 8) * 2 + 1; int hmacLength = level >> 3; int cipherTextLength = cipherText.size(); if (cipherTextLength <= ephemeralPubKeyLength + hmacLength) throw new RuntimeException(String.format("Illegal cipherText length: %d must be > %d", cipherTextLength, ephemeralPubKeyLength + hmacLength)); ByteString ephemeralPubKey = cipherText.substring(0, ephemeralPubKeyLength); ByteString encryptedContent = cipherText.substring(ephemeralPubKeyLength, cipherTextLength - hmacLength); ByteString hmac = cipherText.substring(cipherTextLength - hmacLength); ECPrivateKeyParameters ecdhPrivateKeyParameters; try {// www. j a v a 2s .c o m ecdhPrivateKeyParameters = (ECPrivateKeyParameters) (PrivateKeyFactory .createKey(bcecPrivateKey.getEncoded())); } catch (IOException e) { logger.error("ECIES decrypt load private key exception", e); throw new RuntimeException(e); } ECDomainParameters ecDomainParameters = ecdhPrivateKeyParameters.getParameters(); ECCurve ecCurve = ecDomainParameters.getCurve(); ECPublicKeyParameters ecPublicKeyParameters = new ECPublicKeyParameters( ecCurve.decodePoint(ephemeralPubKey.toByteArray()), ecDomainParameters); BasicAgreement agree = new ECDHBasicAgreement(); agree.init(ecdhPrivateKeyParameters); byte[] keyAgreement = agree.calculateAgreement(ecPublicKeyParameters).toByteArray(); HKDFParameters hkdfParameters = new HKDFParameters(keyAgreement, null, null); HKDFBytesGenerator hkdfBytesGenerator = new HKDFBytesGenerator(digest); hkdfBytesGenerator.init(hkdfParameters); byte[] hkdfOutputBytes = new byte[AESKEY_LENGTH + HMACKEY_LENGTH]; hkdfBytesGenerator.generateBytes(hkdfOutputBytes, 0, AESKEY_LENGTH + HMACKEY_LENGTH); ByteString hkdfOutput = ByteString.copyFrom(hkdfOutputBytes); ByteString aesKey = hkdfOutput.substring(0, AESKEY_LENGTH); ByteString hmacKey = hkdfOutput.substring(AESKEY_LENGTH, AESKEY_LENGTH + HMACKEY_LENGTH); HMac hMac = new HMac(digest); hMac.init(new KeyParameter(hmacKey.toByteArray())); hMac.update(encryptedContent.toByteArray(), 0, encryptedContent.size()); byte[] recoveredHmac = new byte[hMac.getMacSize()]; hMac.doFinal(recoveredHmac, 0); if (!MessageDigest.isEqual(hmac.toByteArray(), recoveredHmac)) { throw new RuntimeException("HMAC verify failed"); } CFBBlockCipher aesCipher = new CFBBlockCipher(new AESEngine(), BLOCK_BIT_SIZE); ByteString iv = encryptedContent.substring(0, IV_LENGTH); CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(aesKey.toByteArray()), iv.toByteArray()); aesCipher.init(false, ivAndKey); byte[] decryptedBytes = new byte[500]; aesCipher.decryptBlock(encryptedContent.substring(IV_LENGTH).toByteArray(), 0, decryptedBytes, 0); return ByteString.copyFrom(decryptedBytes); }
From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java
License:Open Source License
public byte[] eciesDecrypt(KeyPair keyPair, byte[] data) throws CryptoException { try {//w w w.j a v a2 s . co m int ek_len = (int) (Math.floor((this.securityLevel + 7) / 8) * 2 + 1); int mk_len = this.securityLevel >> 3; int em_len = data.length - ek_len - mk_len; byte[] ephemeralPublicKeyBytes = Arrays.copyOfRange(data, 0, ek_len); byte[] encryptedMessage = Arrays.copyOfRange(data, ek_len, ek_len + em_len); byte[] tag = Arrays.copyOfRange(data, ek_len + em_len, data.length); // Parsing public key. ECParameterSpec asymmetricKeyParams = generateECParameterSpec(); KeyFactory asymmetricKeyFactory = KeyFactory.getInstance(ASYMMETRIC_KEY_TYPE, SECURITY_PROVIDER); PublicKey ephemeralPublicKey = asymmetricKeyFactory.generatePublic(new ECPublicKeySpec( asymmetricKeyParams.getCurve().decodePoint(ephemeralPublicKeyBytes), asymmetricKeyParams)); // Deriving shared secret. KeyAgreement keyAgreement = KeyAgreement.getInstance(KEY_AGREEMENT_ALGORITHM, SECURITY_PROVIDER); keyAgreement.init(keyPair.getPrivate()); keyAgreement.doPhase(ephemeralPublicKey, true); byte[] sharedSecret = keyAgreement.generateSecret(); // Deriving encryption and mac keys. HKDFBytesGenerator hkdfBytesGenerator = new HKDFBytesGenerator(getHashDigest()); hkdfBytesGenerator.init(new HKDFParameters(sharedSecret, null, null)); byte[] encryptionKey = new byte[SYMMETRIC_KEY_BYTE_COUNT]; hkdfBytesGenerator.generateBytes(encryptionKey, 0, SYMMETRIC_KEY_BYTE_COUNT); byte[] macKey = new byte[MAC_KEY_BYTE_COUNT]; hkdfBytesGenerator.generateBytes(macKey, 0, MAC_KEY_BYTE_COUNT); // Verifying Message Authentication Code (aka mac/tag) byte[] expectedTag = calculateMac(macKey, encryptedMessage); if (!Arrays.areEqual(tag, expectedTag)) { throw new RuntimeException("Bad Message Authentication Code!"); } // Decrypting the message. byte[] iv = Arrays.copyOfRange(encryptedMessage, 0, 16); byte[] encrypted = Arrays.copyOfRange(encryptedMessage, 16, encryptedMessage.length); byte[] output = aesDecrypt(encryptionKey, iv, encrypted); return output; } catch (Exception e) { throw new CryptoException("Could not decrypt the message", e); } }
From source file:org.syncany.crypto.CipherUtil.java
License:Open Source License
/** * Creates a derived key from the given input key material (raw byte array) and an input salt * and wraps the key in a {@link SecretKeySpec} using the given output key algorithm and output * key size.//from w w w.j a v a 2 s . c om * * <p>The algorithm used to derive the new key from the input key material (IKM) is the * <b>HMAC-based Extract-and-Expand Key Derivation Function (HKDF)</b> (see * <a href="http://tools.ietf.org/html/rfc5869">RFC 5869</a>) * * @param inputKeyMaterial The input key material as raw data bytes, e.g. determined from {@link SecretKey#getEncoded()} * @param inputSalt Input salt used to generate the new key (a non-secret random value!) * @param outputKeyAlgorithm Defines the algorithm of the new output key (for {@link SecretKeySpec#getAlgorithm()}) * @param outputKeySize Defines the key size of the new output key * @return Returns a new pseudorandom key derived from the input key material using HKDF * @see <a href="http://tools.ietf.org/html/rfc5869">RFC 5869</a> */ public static SaltedSecretKey createDerivedKey(byte[] inputKeyMaterial, byte[] inputSalt, String outputKeyAlgorithm, int outputKeySize) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException { HKDFBytesGenerator hkdf = new HKDFBytesGenerator(KEY_DERIVATION_DIGEST); hkdf.init(new HKDFParameters(inputKeyMaterial, inputSalt, KEY_DERIVATION_INFO)); byte[] derivedKey = new byte[outputKeySize / 8]; hkdf.generateBytes(derivedKey, 0, derivedKey.length); return toSaltedSecretKey(derivedKey, inputSalt, outputKeyAlgorithm); }