use of com.github.zhenwei.core.asn1.pkcs.EncryptedPrivateKeyInfo 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.EncryptedPrivateKeyInfo in project certmgr by hdecarne.
the class DERCertReaderWriter method tryDecodeKey.
@Nullable
private static KeyPair tryDecodeKey(ASN1Primitive asn1Object, String resource, PasswordCallback password) throws IOException {
PKCS8EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = null;
try {
encryptedPrivateKeyInfo = new PKCS8EncryptedPrivateKeyInfo(EncryptedPrivateKeyInfo.getInstance(asn1Object));
} catch (Exception e) {
Exceptions.ignore(e);
}
PrivateKeyInfo privateKeyInfo = null;
if (encryptedPrivateKeyInfo != null) {
Throwable passwordException = null;
while (privateKeyInfo == null) {
char[] passwordChars = password.queryPassword(resource);
if (passwordChars == null) {
throw new PasswordRequiredException(resource, passwordException);
}
InputDecryptorProvider inputDecryptorProvider = INPUT_DECRYPTOR_BUILDER.build(passwordChars);
try {
privateKeyInfo = encryptedPrivateKeyInfo.decryptPrivateKeyInfo(inputDecryptorProvider);
} catch (PKCSException e) {
passwordException = e;
}
}
}
try {
privateKeyInfo = PrivateKeyInfo.getInstance(asn1Object);
} catch (Exception e) {
Exceptions.ignore(e);
}
KeyPair key = null;
if (privateKeyInfo != null) {
PrivateKey privateKey;
try {
String algorithmId = privateKeyInfo.getPrivateKeyAlgorithm().getAlgorithm().getId();
KeyFactory keyFactory = JCA_JCE_HELPER.createKeyFactory(algorithmId);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyInfo.getEncoded());
privateKey = keyFactory.generatePrivate(keySpec);
} catch (GeneralSecurityException e) {
throw new CertProviderException(e);
}
key = KeyHelper.rebuildKeyPair(privateKey);
}
return key;
}
use of com.github.zhenwei.core.asn1.pkcs.EncryptedPrivateKeyInfo in project jruby-openssl by jruby.
the class PEMInputOutput method derivePrivateKeyPBES1.
private static PrivateKey derivePrivateKeyPBES1(EncryptedPrivateKeyInfo eIn, AlgorithmIdentifier algId, char[] password) throws GeneralSecurityException, IOException {
// From BC's PEMReader
PKCS12PBEParams pkcs12Params = PKCS12PBEParams.getInstance(algId.getParameters());
PBEKeySpec pbeSpec = new PBEKeySpec(password);
PBEParameterSpec pbeParams = new PBEParameterSpec(pkcs12Params.getIV(), pkcs12Params.getIterations().intValue());
String algorithm = ASN1Registry.o2a(algId.getAlgorithm());
algorithm = (algorithm.split("-"))[0];
SecretKeyFactory secKeyFactory = SecurityHelper.getSecretKeyFactory(algorithm);
Cipher cipher = SecurityHelper.getCipher(algorithm);
cipher.init(Cipher.DECRYPT_MODE, secKeyFactory.generateSecret(pbeSpec), pbeParams);
PrivateKeyInfo pInfo = PrivateKeyInfo.getInstance(ASN1Primitive.fromByteArray(cipher.doFinal(eIn.getEncryptedData())));
KeyFactory keyFactory = getKeyFactory(pInfo.getPrivateKeyAlgorithm());
return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(pInfo.getEncoded()));
}
use of com.github.zhenwei.core.asn1.pkcs.EncryptedPrivateKeyInfo in project LinLong-Java by zhenwei1108.
the class EncryptedPrivateKeyData method toASN1Primitive.
public ASN1Primitive toASN1Primitive() {
ASN1EncodableVector v = new ASN1EncodableVector(2);
v.add(encryptedPrivateKeyInfo);
v.add(new DERSequence(certificateChain));
return new DERSequence(v);
}
use of com.github.zhenwei.core.asn1.pkcs.EncryptedPrivateKeyInfo 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;
}
Aggregations