use of org.kse.crypto.CryptoException in project keystore-explorer by kaikramer.
the class MsPvkUtil method blobToRsaPrivateKey.
private static RSAPrivateCrtKey blobToRsaPrivateKey(byte[] rsaPrivateKeyBlob) throws CryptoException {
try {
ByteBuffer bb = ByteBuffer.wrap(rsaPrivateKeyBlob);
bb.order(ByteOrder.LITTLE_ENDIAN);
// Get each blob field
// rsapubkey.magic
long magic = UnsignedUtil.getInt(bb);
// Check magic field is valid
if (magic != RSA_PRIV_MAGIC) {
throw new CryptoException(MessageFormat.format(res.getString("InvalidRsaMagicField.exception.message"), Long.toHexString(magic), Long.toHexString(RSA_PRIV_MAGIC)));
}
// rsapubkey.bitlen
long bitLength = UnsignedUtil.getInt(bb);
// Byte lengths divisions may have remainders to take account for if not factors of 16 and/or 8
int add8 = 0;
if ((bitLength % 8) != 0) {
add8++;
}
int add16 = 0;
if ((bitLength % 16) != 0) {
add16++;
}
// rsapubkey.pubexp
BigInteger publicExponent = new BigInteger(Long.toString(UnsignedUtil.getInt(bb)));
// modulus
BigInteger modulus = readBigInteger(bb, (int) (bitLength / 8) + add8);
// prime 1
BigInteger prime1 = readBigInteger(bb, (int) (bitLength / 16) + add16);
// prime 2
BigInteger prime2 = readBigInteger(bb, (int) (bitLength / 16) + add16);
// exponent1
BigInteger exponent1 = readBigInteger(bb, (int) (bitLength / 16) + add16);
// exponent2
BigInteger exponent2 = readBigInteger(bb, (int) (bitLength / 16) + add16);
// coefficient
BigInteger coefficient = readBigInteger(bb, (int) (bitLength / 16) + add16);
// privateExponent
BigInteger privateExponent = readBigInteger(bb, (int) (bitLength / 8) + add8);
RSAPrivateCrtKeySpec rsaPrivateCrtKeySpec = new RSAPrivateCrtKeySpec(modulus, publicExponent, privateExponent, prime1, prime2, exponent1, exponent2, coefficient);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return (RSAPrivateCrtKey) keyFactory.generatePrivate(rsaPrivateCrtKeySpec);
} catch (IOException ex) {
throw new CryptoException(res.getString("NoConvertBlobToRsaKey.exception.message"), ex);
} catch (GeneralSecurityException ex) {
throw new CryptoException(res.getString("NoConvertBlobToRsaKey.exception.message"), ex);
}
}
use of org.kse.crypto.CryptoException in project keystore-explorer by kaikramer.
the class MsPvkUtil method load.
/**
* Load an unencrypted PVK private key from the stream.
*
* @param is
* Stream to load the unencrypted private key from
* @return The private key
* @throws PrivateKeyEncryptedException
* If private key is encrypted
* @throws CryptoException
* Problem encountered while loading the private key
* @throws IOException
* An I/O error occurred
*/
public static PrivateKey load(InputStream is) throws IOException, CryptoException {
byte[] pvk = ReadUtil.readFully(is);
// Wrap in a byte buffer set up to read little endian
ByteBuffer bb = ByteBuffer.wrap(pvk);
bb.order(ByteOrder.LITTLE_ENDIAN);
// Read and validate the reserved, magic number and key type fields - only returns the latter
long keyType = readReservedMagicKeyType(bb);
// Read and validate encrypted field
long encrypted = UnsignedUtil.getInt(bb);
if (encrypted != PVK_UNENCRYPTED) {
throw new PrivateKeyEncryptedException(MessageFormat.format(res.getString("MsPvkIsEncrypted.exception.message"), Long.toHexString(encrypted), Long.toHexString(PVK_UNENCRYPTED)));
}
// Read and validate salt length field
long saltLength = UnsignedUtil.getInt(bb);
if (// Specific length (0) for unencrypted PVK
saltLength != UNENCRYPTED_SALT_LENGTH) {
throw new CryptoException(MessageFormat.format(res.getString("InvalidMsPvkSaltLengthField.exception.message"), Long.toHexString(saltLength), Long.toHexString(UNENCRYPTED_SALT_LENGTH)));
}
// Read key length
long keyLength = UnsignedUtil.getInt(bb);
// Read private key blob header
readPrivateKeyBlobHeader(bb, keyType);
// Read all remaining bytes as the private key blob
byte[] privateKeyBlob = new byte[bb.remaining()];
bb.get(privateKeyBlob);
// Validate key length - should be length of key blob plus blob header
if (keyLength != (privateKeyBlob.length + BLOB_HEADER_LENGTH)) {
throw new CryptoException(MessageFormat.format(res.getString("InvalidMsPvkKeyLengthField.exception.message"), Long.toHexString(keyLength), Long.toHexString(privateKeyBlob.length + BLOB_HEADER_LENGTH)));
}
return blobToPrivateKey(privateKeyBlob);
}
use of org.kse.crypto.CryptoException 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);
}
use of org.kse.crypto.CryptoException in project keystore-explorer by kaikramer.
the class OpenSslPvkUtil method createCipher.
private static Cipher createCipher(String transformation, byte[] key, byte[] iv, int operation) throws CryptoException {
SecretKey secretKey = new SecretKeySpec(key, transformation);
IvParameterSpec ivParams = new IvParameterSpec(iv);
try {
Cipher cipher = Cipher.getInstance(transformation, "BC");
cipher.init(operation, secretKey, ivParams);
return cipher;
} catch (GeneralSecurityException ex) {
throw new CryptoException(MessageFormat.format("OpenSslCreateCipherFailed.exception.message", transformation), ex);
}
}
use of org.kse.crypto.CryptoException in project keystore-explorer by kaikramer.
the class OpenSslPvkUtil method load.
/**
* Load an unencrypted OpenSSL private key from the stream. The encoding of
* the private key may be PEM or DER.
*
* @param is
* Stream to load the unencrypted private key from
* @return The private key
* @throws PrivateKeyEncryptedException
* If private key is encrypted
* @throws CryptoException
* Problem encountered while loading the private key
* @throws IOException
* An I/O error occurred
*/
public static PrivateKey load(InputStream is) throws CryptoException, IOException {
byte[] streamContents = ReadUtil.readFully(is);
EncryptionType encType = getEncryptionType(new ByteArrayInputStream(streamContents));
if (encType == null) {
throw new CryptoException(res.getString("NotValidOpenSsl.exception.message"));
}
if (encType == ENCRYPTED) {
throw new PrivateKeyEncryptedException(res.getString("OpenSslIsEncrypted.exception.message"));
}
// Check if stream is PEM encoded
PemInfo pemInfo = PemUtil.decode(new ByteArrayInputStream(streamContents));
if (pemInfo != null) {
// It is - get DER from PEM
streamContents = pemInfo.getContent();
}
try {
// Read OpenSSL DER structure
ASN1InputStream asn1InputStream = new ASN1InputStream(streamContents);
ASN1Primitive openSsl = asn1InputStream.readObject();
asn1InputStream.close();
if (openSsl instanceof ASN1Sequence) {
ASN1Sequence seq = (ASN1Sequence) openSsl;
if (seq.size() == 9) {
// RSA private key
BigInteger version = ((ASN1Integer) seq.getObjectAt(0)).getValue();
BigInteger modulus = ((ASN1Integer) seq.getObjectAt(1)).getValue();
BigInteger publicExponent = ((ASN1Integer) seq.getObjectAt(2)).getValue();
BigInteger privateExponent = ((ASN1Integer) seq.getObjectAt(3)).getValue();
BigInteger primeP = ((ASN1Integer) seq.getObjectAt(4)).getValue();
BigInteger primeQ = ((ASN1Integer) seq.getObjectAt(5)).getValue();
BigInteger primeExponentP = ((ASN1Integer) seq.getObjectAt(6)).getValue();
BigInteger primeExponenetQ = ((ASN1Integer) seq.getObjectAt(7)).getValue();
BigInteger crtCoefficient = ((ASN1Integer) seq.getObjectAt(8)).getValue();
if (!version.equals(VERSION)) {
throw new CryptoException(MessageFormat.format(res.getString("OpenSslVersionIncorrect.exception.message"), "" + VERSION.intValue(), "" + version.intValue()));
}
RSAPrivateCrtKeySpec rsaPrivateCrtKeySpec = new RSAPrivateCrtKeySpec(modulus, publicExponent, privateExponent, primeP, primeQ, primeExponentP, primeExponenetQ, crtCoefficient);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePrivate(rsaPrivateCrtKeySpec);
} else if (seq.size() == 6) {
// DSA private key
BigInteger version = ((ASN1Integer) seq.getObjectAt(0)).getValue();
BigInteger primeModulusP = ((ASN1Integer) seq.getObjectAt(1)).getValue();
BigInteger primeQ = ((ASN1Integer) seq.getObjectAt(2)).getValue();
BigInteger generatorG = ((ASN1Integer) seq.getObjectAt(3)).getValue();
// publicExponentY not req for pvk: sequence.getObjectAt(4);
BigInteger secretExponentX = ((ASN1Integer) seq.getObjectAt(5)).getValue();
if (!version.equals(VERSION)) {
throw new CryptoException(MessageFormat.format(res.getString("OpenSslVersionIncorrect.exception.message"), "" + VERSION.intValue(), "" + version.intValue()));
}
DSAPrivateKeySpec dsaPrivateKeySpec = new DSAPrivateKeySpec(secretExponentX, primeModulusP, primeQ, generatorG);
KeyFactory keyFactory = KeyFactory.getInstance("DSA");
return keyFactory.generatePrivate(dsaPrivateKeySpec);
} else if (seq.size() >= 2) {
// EC private key (RFC 5915)
org.bouncycastle.asn1.sec.ECPrivateKey pKey = org.bouncycastle.asn1.sec.ECPrivateKey.getInstance(seq);
AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, pKey.getParameters());
PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey);
return new JcaPEMKeyConverter().getPrivateKey(privInfo);
} else {
throw new CryptoException(MessageFormat.format(res.getString("OpenSslSequenceIncorrectSize.exception.message"), "" + seq.size()));
}
} else {
throw new CryptoException(res.getString("OpenSslSequenceNotFound.exception.message"));
}
} catch (Exception ex) {
throw new CryptoException(res.getString("NoLoadOpenSslPrivateKey.exception.message"), ex);
}
}
Aggregations