use of com.github.zhenwei.core.asn1.pkcs.PBKDF2Params 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 com.github.zhenwei.core.asn1.pkcs.PBKDF2Params 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 com.github.zhenwei.core.asn1.pkcs.PBKDF2Params in project robovm by robovm.
the class PKCS12KeyStoreSpi method unwrapKey.
protected PrivateKey unwrapKey(AlgorithmIdentifier algId, byte[] data, char[] password, boolean wrongPKCS12Zero) throws IOException {
ASN1ObjectIdentifier algorithm = algId.getAlgorithm();
try {
if (algorithm.on(PKCSObjectIdentifiers.pkcs_12PbeIds)) {
PKCS12PBEParams pbeParams = PKCS12PBEParams.getInstance(algId.getParameters());
PBEKeySpec pbeSpec = new PBEKeySpec(password);
PrivateKey out;
SecretKeyFactory keyFact = SecretKeyFactory.getInstance(algorithm.getId(), bcProvider);
PBEParameterSpec defParams = new PBEParameterSpec(pbeParams.getIV(), pbeParams.getIterations().intValue());
SecretKey k = keyFact.generateSecret(pbeSpec);
((BCPBEKey) k).setTryWrongPKCS12Zero(wrongPKCS12Zero);
Cipher cipher = Cipher.getInstance(algorithm.getId(), bcProvider);
cipher.init(Cipher.UNWRAP_MODE, k, defParams);
// we pass "" as the key algorithm type as it is unknown at this point
return (PrivateKey) cipher.unwrap(data, "", Cipher.PRIVATE_KEY);
} else if (algorithm.equals(PKCSObjectIdentifiers.id_PBES2)) {
PBES2Parameters alg = PBES2Parameters.getInstance(algId.getParameters());
PBKDF2Params func = PBKDF2Params.getInstance(alg.getKeyDerivationFunc().getParameters());
SecretKeyFactory keyFact = SecretKeyFactory.getInstance(alg.getKeyDerivationFunc().getAlgorithm().getId(), bcProvider);
SecretKey k = keyFact.generateSecret(new PBEKeySpec(password, func.getSalt(), func.getIterationCount().intValue(), SecretKeyUtil.getKeySize(alg.getEncryptionScheme().getAlgorithm())));
Cipher cipher = Cipher.getInstance(alg.getEncryptionScheme().getAlgorithm().getId(), bcProvider);
cipher.init(Cipher.UNWRAP_MODE, k, new IvParameterSpec(ASN1OctetString.getInstance(alg.getEncryptionScheme().getParameters()).getOctets()));
// we pass "" as the key algorithm type as it is unknown at this point
return (PrivateKey) cipher.unwrap(data, "", Cipher.PRIVATE_KEY);
}
} catch (Exception e) {
throw new IOException("exception unwrapping private key - " + e.toString());
}
throw new IOException("exception unwrapping private key - cannot recognise: " + algorithm);
}
use of com.github.zhenwei.core.asn1.pkcs.PBKDF2Params in project jruby-openssl by jruby.
the class PEMInputOutput method extractPBES2CipherParams.
private static CipherParameters extractPBES2CipherParams(char[] password, PBES2Parameters pbeParams) {
PBKDF2Params pbkdfParams = PBKDF2Params.getInstance(pbeParams.getKeyDerivationFunc().getParameters());
int keySize = 192;
if (pbkdfParams.getKeyLength() != null) {
keySize = pbkdfParams.getKeyLength().intValue() * 8;
}
int iterationCount = pbkdfParams.getIterationCount().intValue();
byte[] salt = pbkdfParams.getSalt();
PBEParametersGenerator generator = new PKCS5S2ParametersGenerator();
generator.init(PBEParametersGenerator.PKCS5PasswordToBytes(password), salt, iterationCount);
return generator.generateDerivedParameters(keySize);
}
use of com.github.zhenwei.core.asn1.pkcs.PBKDF2Params in project xipki by xipki.
the class CmpAgentUtil method decrypt.
private static byte[] decrypt(EncryptedValue ev, char[] password) throws XiSecurityException {
AlgorithmIdentifier symmAlg = ev.getSymmAlg();
if (!PKCSObjectIdentifiers.id_PBES2.equals(symmAlg.getAlgorithm())) {
throw new XiSecurityException("unsupported symmAlg " + symmAlg.getAlgorithm().getId());
}
PBES2Parameters alg = PBES2Parameters.getInstance(symmAlg.getParameters());
PBKDF2Params func = PBKDF2Params.getInstance(alg.getKeyDerivationFunc().getParameters());
AlgorithmIdentifier encScheme = AlgorithmIdentifier.getInstance(alg.getEncryptionScheme());
try {
SecretKeyFactory keyFact = SecretKeyFactory.getInstance(alg.getKeyDerivationFunc().getAlgorithm().getId());
SecretKey key;
int iterations = func.getIterationCount().intValue();
key = keyFact.generateSecret(new PBKDF2KeySpec(password, func.getSalt(), iterations, KEYSIZE_PROVIDER.getKeySize(encScheme), func.getPrf()));
key = new SecretKeySpec(key.getEncoded(), "AES");
String cipherAlgOid = alg.getEncryptionScheme().getAlgorithm().getId();
Cipher cipher = Cipher.getInstance(cipherAlgOid);
ASN1Encodable encParams = alg.getEncryptionScheme().getParameters();
GCMParameters gcmParameters = GCMParameters.getInstance(encParams);
GCMParameterSpec gcmParamSpec = new GCMParameterSpec(gcmParameters.getIcvLen() * 8, gcmParameters.getNonce());
cipher.init(Cipher.DECRYPT_MODE, key, gcmParamSpec);
return cipher.doFinal(ev.getEncValue().getOctets());
} catch (IllegalBlockSizeException | BadPaddingException | NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException ex) {
throw new XiSecurityException("Error while decrypting the EncryptedValue", ex);
}
}
Aggregations