use of org.kse.utilities.pem.PemAttribute in project keystore-explorer by kaikramer.
the class OpenSslPvkUtil method getEncrypted.
/**
* OpenSSL encode and encrypt a private key. Encrypted OpenSSL private keys
* must always by PEM'd.
*
* @return The encrypted, PEM'd encoding
* @param privateKey
* The private key
* @param pbeType
* PBE algorithm to use for encryption
* @param password
* Encryption password
* @throws CryptoException
* Problem encountered while getting the encoded private key
*/
public static String getEncrypted(PrivateKey privateKey, OpenSslPbeType pbeType, Password password) throws CryptoException {
byte[] openSsl = get(privateKey);
String pemType = null;
if (privateKey instanceof RSAPrivateCrtKey) {
pemType = OPENSSL_RSA_PVK_PEM_TYPE;
} else if (privateKey instanceof ECPrivateKey) {
pemType = OPENSSL_EC_PVK_PEM_TYPE;
} else {
pemType = OPENSSL_DSA_PVK_PEM_TYPE;
}
byte[] salt = generateSalt(pbeType.saltSize() / 8);
String saltHex = bytesToHex(salt);
byte[] encOpenSsl = null;
try {
byte[] encryptKey = deriveKeyFromPassword(password, salt, pbeType.keySize());
// Create cipher - use all of the salt as the IV
Cipher cipher = createCipher(pbeType.jceCipher(), encryptKey, salt, ENCRYPT_MODE);
encOpenSsl = cipher.doFinal(openSsl);
} catch (GeneralSecurityException ex) {
throw new CryptoException(MessageFormat.format("OpenSslEncryptionFailed.exception.message", pbeType.friendly()), ex);
}
PemAttributes attributes = new PemAttributes();
attributes.add(new PemAttribute(PROC_TYPE_ATTR_NAME, PROC_TYPE_ATTR_VALUE));
String dekInfoAttrValue = MessageFormat.format(DEK_INFO_ATTR_VALUE_TEMPLATE, pbeType.dekInfo(), saltHex);
attributes.add(new PemAttribute(DEK_INFO_ATTR_NAME, dekInfoAttrValue));
PemInfo pemInfo = new PemInfo(pemType, attributes, encOpenSsl);
return PemUtil.encode(pemInfo);
}
Aggregations