use of com.github.zhenwei.core.asn1.pkcs.EncryptionScheme in project xwiki-commons by xwiki.
the class AbstractBcPBES2Cipher method getPBEParameters.
@Override
public AlgorithmIdentifier getPBEParameters() throws IOException {
KeyDerivationFunc kdfParams;
if (getKeyDerivationFunction() instanceof AbstractBcKDF) {
kdfParams = ((AbstractBcKDF) getKeyDerivationFunction()).getKeyDerivationFunction();
} else {
kdfParams = KeyDerivationFunc.getInstance(getKeyDerivationFunction().getEncoded());
}
EncryptionScheme scheme = getScheme(getParameters());
return new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBES2, new PBES2Parameters(kdfParams, scheme));
}
use of com.github.zhenwei.core.asn1.pkcs.EncryptionScheme 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.EncryptionScheme 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.EncryptionScheme in project jruby-openssl by jruby.
the class PEMInputOutput method derivePrivateKeyPBES2.
private static PrivateKey derivePrivateKeyPBES2(EncryptedPrivateKeyInfo eIn, AlgorithmIdentifier algId, char[] password) throws GeneralSecurityException, InvalidCipherTextException {
PBES2Parameters pbeParams = PBES2Parameters.getInstance((ASN1Sequence) algId.getParameters());
CipherParameters cipherParams = extractPBES2CipherParams(password, pbeParams);
EncryptionScheme scheme = pbeParams.getEncryptionScheme();
BufferedBlockCipher cipher;
if (scheme.getAlgorithm().equals(PKCSObjectIdentifiers.RC2_CBC)) {
RC2CBCParameter rc2Params = RC2CBCParameter.getInstance(scheme);
byte[] iv = rc2Params.getIV();
CipherParameters param = new ParametersWithIV(cipherParams, iv);
cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new RC2Engine()));
cipher.init(false, param);
} else {
byte[] iv = ASN1OctetString.getInstance(scheme.getParameters()).getOctets();
CipherParameters param = new ParametersWithIV(cipherParams, iv);
cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new DESedeEngine()));
cipher.init(false, param);
}
byte[] data = eIn.getEncryptedData();
byte[] out = new byte[cipher.getOutputSize(data.length)];
int len = cipher.processBytes(data, 0, data.length, out, 0);
len += cipher.doFinal(out, len);
byte[] pkcs8 = new byte[len];
System.arraycopy(out, 0, pkcs8, 0, len);
// It seems to work for both RSA and DSA.
KeyFactory fact = SecurityHelper.getKeyFactory("RSA");
return fact.generatePrivate(new PKCS8EncodedKeySpec(pkcs8));
}
use of com.github.zhenwei.core.asn1.pkcs.EncryptionScheme 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