use of org.bouncycastle.asn1.pkcs.KeyDerivationFunc in project hedera-sdk-java by hashgraph.
the class Pem method decryptPrivateKey.
private static PrivateKeyInfo decryptPrivateKey(byte[] encodedStruct, String passphrase) throws IOException {
var encryptedPrivateKeyInfo = EncryptedPrivateKeyInfo.getInstance(ASN1Primitive.fromByteArray(encodedStruct));
AlgorithmIdentifier encryptAlg = encryptedPrivateKeyInfo.getEncryptionAlgorithm();
if (!encryptAlg.getAlgorithm().equals(PKCSObjectIdentifiers.id_PBES2)) {
throw new BadKeyException("unsupported PEM key encryption: " + encryptAlg);
}
PBES2Parameters params = PBES2Parameters.getInstance(encryptAlg.getParameters());
KeyDerivationFunc kdf = params.getKeyDerivationFunc();
EncryptionScheme encScheme = params.getEncryptionScheme();
if (!kdf.getAlgorithm().equals(PKCSObjectIdentifiers.id_PBKDF2)) {
throw new BadKeyException("unsupported KDF: " + kdf.getAlgorithm());
}
if (!encScheme.getAlgorithm().equals(NISTObjectIdentifiers.id_aes128_CBC)) {
throw new BadKeyException("unsupported encryption: " + encScheme.getAlgorithm());
}
PBKDF2Params kdfParams = PBKDF2Params.getInstance(kdf.getParameters());
if (!kdfParams.getPrf().getAlgorithm().equals(PKCSObjectIdentifiers.id_hmacWithSHA256)) {
throw new BadKeyException("unsupported PRF: " + kdfParams.getPrf());
}
int keyLength = kdfParams.getKeyLength() != null ? kdfParams.getKeyLength().intValue() : Crypto.CBC_DK_LEN;
KeyParameter derivedKey = Crypto.deriveKeySha256(passphrase, kdfParams.getSalt(), kdfParams.getIterationCount().intValue(), keyLength);
AlgorithmParameters aesParams;
try {
aesParams = AlgorithmParameters.getInstance("AES");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
aesParams.init(encScheme.getParameters().toASN1Primitive().getEncoded());
Cipher cipher = Crypto.initAesCbc128Decrypt(derivedKey, aesParams);
byte[] decrypted = Crypto.runCipher(cipher, encryptedPrivateKeyInfo.getEncryptedData());
// we need to parse our input data as the cipher may add padding
ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(decrypted));
return PrivateKeyInfo.getInstance(inputStream.readObject());
}
use of org.bouncycastle.asn1.pkcs.KeyDerivationFunc in project hedera-sdk-java by hashgraph.
the class Pem method writeEncryptedPrivateKey.
/*
* For some reason, this generates PEM encodings that we ourselves can import, but OpenSSL
* doesn't like. We decided to punt on generating encrypted PEMs for now but saving
* the code for when we get back to it and/or any demand arises.
*/
@SuppressWarnings("unused")
static void writeEncryptedPrivateKey(PrivateKeyInfo pkInfo, Writer out, String passphrase) throws IOException {
byte[] salt = Crypto.randomBytes(Crypto.SALT_LEN);
KeyParameter derivedKey = Crypto.deriveKeySha256(passphrase, salt, Crypto.ITERATIONS, Crypto.CBC_DK_LEN);
byte[] iv = Crypto.randomBytes(Crypto.IV_LEN);
Cipher cipher = Crypto.initAesCbc128Encrypt(derivedKey, iv);
byte[] encryptedKey = Crypto.runCipher(cipher, pkInfo.getEncoded());
// I wanted to just do this with BC's PKCS8Generator and KcePKCSPBEOutputEncryptorBuilder
// but it tries to init AES instance of `Cipher` with a `PBKDF2Key` and the former complains
// So this is basically a reimplementation of that minus the excess OO
PBES2Parameters parameters = new PBES2Parameters(new KeyDerivationFunc(PKCSObjectIdentifiers.id_PBKDF2, new PBKDF2Params(salt, Crypto.ITERATIONS, Crypto.CBC_DK_LEN, new AlgorithmIdentifier(PKCSObjectIdentifiers.id_hmacWithSHA256))), new EncryptionScheme(NISTObjectIdentifiers.id_aes128_CBC, ASN1Primitive.fromByteArray(cipher.getParameters().getEncoded())));
EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBES2, parameters), encryptedKey);
PemWriter writer = new PemWriter(out);
writer.writeObject(new PemObject(TYPE_ENCRYPTED_PRIVATE_KEY, encryptedPrivateKeyInfo.getEncoded()));
writer.flush();
}
use of org.bouncycastle.asn1.pkcs.KeyDerivationFunc in project LinLong-Java by zhenwei1108.
the class BcFKSKeyStoreSpi method engineSetKeyEntry.
public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) throws KeyStoreException {
Date creationDate = new Date();
Date lastEditDate = creationDate;
ObjectData entry = (ObjectData) entries.get(alias);
if (entry != null) {
creationDate = extractCreationDate(entry, creationDate);
}
privateKeyCache.remove(alias);
if (key instanceof PrivateKey) {
if (chain == null) {
throw new KeyStoreException("BCFKS KeyStore requires a certificate chain for private key storage.");
}
try {
// check that the key pair and the certificate public are consistent
// TODO: new ConsistentKeyPair(chain[0].getPublicKey(), (PrivateKey)key);
byte[] encodedKey = key.getEncoded();
KeyDerivationFunc pbkdAlgId = generatePkbdAlgorithmIdentifier(PKCSObjectIdentifiers.id_PBKDF2, 256 / 8);
byte[] keyBytes = generateKey(pbkdAlgId, "PRIVATE_KEY_ENCRYPTION", ((password != null) ? password : new char[0]), 32);
EncryptedPrivateKeyInfo keyInfo;
if (storeEncryptionAlgorithm.equals(NISTObjectIdentifiers.id_aes256_CCM)) {
Cipher c = createCipher("AES/CCM/NoPadding", keyBytes);
byte[] encryptedKey = c.doFinal(encodedKey);
AlgorithmParameters algParams = c.getParameters();
PBES2Parameters pbeParams = new PBES2Parameters(pbkdAlgId, new EncryptionScheme(NISTObjectIdentifiers.id_aes256_CCM, CCMParameters.getInstance(algParams.getEncoded())));
keyInfo = new EncryptedPrivateKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBES2, pbeParams), encryptedKey);
} else {
Cipher c = createCipher("AESKWP", keyBytes);
byte[] encryptedKey = c.doFinal(encodedKey);
PBES2Parameters pbeParams = new PBES2Parameters(pbkdAlgId, new EncryptionScheme(NISTObjectIdentifiers.id_aes256_wrap_pad));
keyInfo = new EncryptedPrivateKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBES2, pbeParams), encryptedKey);
}
EncryptedPrivateKeyData keySeq = createPrivateKeySequence(keyInfo, chain);
entries.put(alias, new ObjectData(PRIVATE_KEY, alias, creationDate, lastEditDate, keySeq.getEncoded(), null));
} catch (Exception e) {
throw new ExtKeyStoreException("BCFKS KeyStore exception storing private key: " + e.toString(), e);
}
} else if (key instanceof SecretKey) {
if (chain != null) {
throw new KeyStoreException("BCFKS KeyStore cannot store certificate chain with secret key.");
}
try {
byte[] encodedKey = key.getEncoded();
KeyDerivationFunc pbkdAlgId = generatePkbdAlgorithmIdentifier(PKCSObjectIdentifiers.id_PBKDF2, 256 / 8);
byte[] keyBytes = generateKey(pbkdAlgId, "SECRET_KEY_ENCRYPTION", ((password != null) ? password : new char[0]), 32);
String keyAlg = Strings.toUpperCase(key.getAlgorithm());
SecretKeyData secKeyData;
if (keyAlg.indexOf("AES") > -1) {
secKeyData = new SecretKeyData(NISTObjectIdentifiers.aes, encodedKey);
} else {
ASN1ObjectIdentifier algOid = (ASN1ObjectIdentifier) oidMap.get(keyAlg);
if (algOid != null) {
secKeyData = new SecretKeyData(algOid, encodedKey);
} else {
algOid = (ASN1ObjectIdentifier) oidMap.get(keyAlg + "." + (encodedKey.length * 8));
if (algOid != null) {
secKeyData = new SecretKeyData(algOid, encodedKey);
} else {
throw new KeyStoreException("BCFKS KeyStore cannot recognize secret key (" + keyAlg + ") for storage.");
}
}
}
EncryptedSecretKeyData keyData;
if (storeEncryptionAlgorithm.equals(NISTObjectIdentifiers.id_aes256_CCM)) {
Cipher c = createCipher("AES/CCM/NoPadding", keyBytes);
byte[] encryptedKey = c.doFinal(secKeyData.getEncoded());
AlgorithmParameters algParams = c.getParameters();
PBES2Parameters pbeParams = new PBES2Parameters(pbkdAlgId, new EncryptionScheme(NISTObjectIdentifiers.id_aes256_CCM, CCMParameters.getInstance(algParams.getEncoded())));
keyData = new EncryptedSecretKeyData(new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBES2, pbeParams), encryptedKey);
} else {
Cipher c = createCipher("AESKWP", keyBytes);
byte[] encryptedKey = c.doFinal(secKeyData.getEncoded());
PBES2Parameters pbeParams = new PBES2Parameters(pbkdAlgId, new EncryptionScheme(NISTObjectIdentifiers.id_aes256_wrap_pad));
keyData = new EncryptedSecretKeyData(new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBES2, pbeParams), encryptedKey);
}
entries.put(alias, new ObjectData(SECRET_KEY, alias, creationDate, lastEditDate, keyData.getEncoded(), null));
} catch (Exception e) {
throw new ExtKeyStoreException("BCFKS KeyStore exception storing private key: " + e.toString(), e);
}
} else {
throw new KeyStoreException("BCFKS KeyStore unable to recognize key.");
}
lastModifiedDate = lastEditDate;
}
use of org.bouncycastle.asn1.pkcs.KeyDerivationFunc in project LinLong-Java by zhenwei1108.
the class BcFKSKeyStoreSpi method generatePkbdAlgorithmIdentifier.
private KeyDerivationFunc generatePkbdAlgorithmIdentifier(PBKDFConfig pbkdfConfig, int keySizeInBytes) {
if (MiscObjectIdentifiers.id_scrypt.equals(pbkdfConfig.getAlgorithm())) {
ScryptConfig scryptConfig = (ScryptConfig) pbkdfConfig;
byte[] pbkdSalt = new byte[scryptConfig.getSaltLength()];
getDefaultSecureRandom().nextBytes(pbkdSalt);
ScryptParams params = new ScryptParams(pbkdSalt, scryptConfig.getCostParameter(), scryptConfig.getBlockSize(), scryptConfig.getParallelizationParameter(), keySizeInBytes);
return new KeyDerivationFunc(MiscObjectIdentifiers.id_scrypt, params);
} else {
PBKDF2Config pbkdf2Config = (PBKDF2Config) pbkdfConfig;
byte[] pbkdSalt = new byte[pbkdf2Config.getSaltLength()];
getDefaultSecureRandom().nextBytes(pbkdSalt);
return new KeyDerivationFunc(PKCSObjectIdentifiers.id_PBKDF2, new PBKDF2Params(pbkdSalt, pbkdf2Config.getIterationCount(), keySizeInBytes, pbkdf2Config.getPRF()));
}
}
use of org.bouncycastle.asn1.pkcs.KeyDerivationFunc in project LinLong-Java by zhenwei1108.
the class BcFKSKeyStoreSpi method generatePkbdAlgorithmIdentifier.
private KeyDerivationFunc generatePkbdAlgorithmIdentifier(KeyDerivationFunc baseAlg, int keySizeInBytes) {
if (MiscObjectIdentifiers.id_scrypt.equals(baseAlg.getAlgorithm())) {
ScryptParams oldParams = ScryptParams.getInstance(baseAlg.getParameters());
byte[] pbkdSalt = new byte[oldParams.getSalt().length];
getDefaultSecureRandom().nextBytes(pbkdSalt);
ScryptParams params = new ScryptParams(pbkdSalt, oldParams.getCostParameter(), oldParams.getBlockSize(), oldParams.getParallelizationParameter(), BigInteger.valueOf(keySizeInBytes));
return new KeyDerivationFunc(MiscObjectIdentifiers.id_scrypt, params);
} else {
PBKDF2Params oldParams = PBKDF2Params.getInstance(baseAlg.getParameters());
byte[] pbkdSalt = new byte[oldParams.getSalt().length];
getDefaultSecureRandom().nextBytes(pbkdSalt);
PBKDF2Params params = new PBKDF2Params(pbkdSalt, oldParams.getIterationCount().intValue(), keySizeInBytes, oldParams.getPrf());
return new KeyDerivationFunc(PKCSObjectIdentifiers.id_PBKDF2, params);
}
}
Aggregations