use of org.kse.crypto.CryptoException in project keystore-explorer by kaikramer.
the class OpenSslPvkUtil method get.
/**
* OpenSSL encode a private key.
*
* @return The encoding
* @param privateKey
* The private key
* @throws CryptoException
* Problem encountered while getting the encoded private key
*/
public static byte[] get(PrivateKey privateKey) throws CryptoException {
// DER encoding for each key type is a sequence
ASN1EncodableVector vec = new ASN1EncodableVector();
if (privateKey instanceof ECPrivateKey) {
try {
ECPrivateKey ecPrivKey = (ECPrivateKey) privateKey;
org.bouncycastle.asn1.sec.ECPrivateKey keyStructure = EccUtil.convertToECPrivateKeyStructure(ecPrivKey);
return keyStructure.toASN1Primitive().getEncoded();
} catch (IOException e) {
throw new CryptoException(res.getString("NoDerEncodeOpenSslPrivateKey.exception.message"), e);
}
} else if (privateKey instanceof RSAPrivateCrtKey) {
RSAPrivateCrtKey rsaPrivateKey = (RSAPrivateCrtKey) privateKey;
vec.add(new ASN1Integer(VERSION));
vec.add(new ASN1Integer(rsaPrivateKey.getModulus()));
vec.add(new ASN1Integer(rsaPrivateKey.getPublicExponent()));
vec.add(new ASN1Integer(rsaPrivateKey.getPrivateExponent()));
vec.add(new ASN1Integer(rsaPrivateKey.getPrimeP()));
vec.add(new ASN1Integer(rsaPrivateKey.getPrimeQ()));
vec.add(new ASN1Integer(rsaPrivateKey.getPrimeExponentP()));
vec.add(new ASN1Integer(rsaPrivateKey.getPrimeExponentQ()));
vec.add(new ASN1Integer(rsaPrivateKey.getCrtCoefficient()));
} else {
DSAPrivateKey dsaPrivateKey = (DSAPrivateKey) privateKey;
DSAParams dsaParams = dsaPrivateKey.getParams();
BigInteger primeModulusP = dsaParams.getP();
BigInteger primeQ = dsaParams.getQ();
BigInteger generatorG = dsaParams.getG();
BigInteger secretExponentX = dsaPrivateKey.getX();
// Derive public key from private key parts, ie Y = G^X mod P
BigInteger publicExponentY = generatorG.modPow(secretExponentX, primeModulusP);
vec.add(new ASN1Integer(VERSION));
vec.add(new ASN1Integer(primeModulusP));
vec.add(new ASN1Integer(primeQ));
vec.add(new ASN1Integer(generatorG));
vec.add(new ASN1Integer(publicExponentY));
vec.add(new ASN1Integer(secretExponentX));
}
DERSequence derSequence = new DERSequence(vec);
try {
return derSequence.getEncoded();
} catch (IOException ex) {
throw new CryptoException(res.getString("NoDerEncodeOpenSslPrivateKey.exception.message"), ex);
}
}
use of org.kse.crypto.CryptoException in project keystore-explorer by kaikramer.
the class Pkcs8Util method loadEncrypted.
/**
* Load an encrypted PKCS #8 private key from the specified stream. The
* encoding of the private key may be PEM or DER.
*
* @param is
* Stream load the encrypted private key from
* @param password
* Password to decrypt
* @return The private key
* @throws PrivateKeyUnencryptedException
* If private key is unencrypted
* @throws PrivateKeyPbeNotSupportedException
* If private key PBE algorithm is not supported
* @throws CryptoException
* Problem encountered while loading the private key
* @throws IOException
* If an I/O error occurred
*/
public static PrivateKey loadEncrypted(InputStream is, Password password) throws CryptoException, IOException {
byte[] streamContents = ReadUtil.readFully(is);
// Check PKCS#8 is encrypted
EncryptionType encType = getEncryptionType(new ByteArrayInputStream(streamContents));
if (encType == null) {
// Not a valid PKCS #8 private key
throw new CryptoException(res.getString("NotValidPkcs8.exception.message"));
}
if (encType == UNENCRYPTED) {
throw new PrivateKeyUnencryptedException(res.getString("Pkcs8IsEncrypted.exception.message"));
}
// Check if stream is PEM encoded
PemInfo pemInfo = PemUtil.decode(new ByteArrayInputStream(streamContents));
byte[] encPvk = null;
if (pemInfo != null) {
// It is - get DER from PEM
encPvk = pemInfo.getContent();
}
// If we haven't got the encrypted bytes via PEM then assume it is DER encoded
if (encPvk == null) {
encPvk = streamContents;
}
// try to read PKCS#8 info
PKCS8EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = null;
try {
encryptedPrivateKeyInfo = new PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo.getInstance(encPvk));
} catch (Exception e) {
// Not a valid PKCS #8 private key
throw new CryptoException(res.getString("NotValidPkcs8.exception.message"));
}
// decrypt and create PrivateKey object from ASN.1 structure
try {
InputDecryptorProvider decProv = new JceOpenSSLPKCS8DecryptorProviderBuilder().setProvider("BC").build(password.toCharArray());
PrivateKeyInfo privateKeyInfo = encryptedPrivateKeyInfo.decryptPrivateKeyInfo(decProv);
return new JcaPEMKeyConverter().getPrivateKey(privateKeyInfo);
} catch (Exception ex) {
throw new CryptoException(res.getString("NoLoadPkcs8PrivateKey.exception.message"), ex);
}
}
use of org.kse.crypto.CryptoException in project keystore-explorer by kaikramer.
the class Pkcs10Util method getCsrEncodedDerPem.
/**
* DER encode a CSR and PEM the encoding.
*
* @return The PEM'd encoding
* @param csr
* The CSR
* @throws CryptoException
* If a problem occurs getting the PEM encoded CSR
*/
public static String getCsrEncodedDerPem(PKCS10CertificationRequest csr) throws CryptoException {
try {
// Base 64 encoding of CSR
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DEROutputStream deros = new DEROutputStream(baos);
deros.writeObject(csr.toASN1Structure().toASN1Primitive());
String tmp = new String(Base64.encode(baos.toByteArray()));
// Header
String csrStr = BEGIN_CSR_FORM_1 + "\n";
// Limit line lengths between header and footer
for (int i = 0; i < tmp.length(); i += MAX_PRINTABLE_ENC_LINE_LENGTH) {
int lineLength;
if ((i + MAX_PRINTABLE_ENC_LINE_LENGTH) > tmp.length()) {
lineLength = (tmp.length() - i);
} else {
lineLength = MAX_PRINTABLE_ENC_LINE_LENGTH;
}
csrStr += tmp.substring(i, (i + lineLength)) + "\n";
}
// Footer
csrStr += END_CSR_FORM_1 + "\n";
return csrStr;
} catch (IOException ex) {
throw new CryptoException(res.getString("NoPemPkcs10Csr.exception.message"), ex);
}
}
use of org.kse.crypto.CryptoException in project keystore-explorer by kaikramer.
the class Pkcs10Util method verifyCsr.
/**
* Verify a PKCS #10 certificate signing request (CSR).
*
* @param csr The certificate signing request
* @return True if successfully verified
* @throws CryptoException
* If there was a problem verifying the CSR
*/
public static boolean verifyCsr(PKCS10CertificationRequest csr) throws CryptoException {
try {
PublicKey pubKey = new JcaPKCS10CertificationRequest(csr).getPublicKey();
ContentVerifierProvider contentVerifierProvider = new JcaContentVerifierProviderBuilder().setProvider("BC").build(pubKey);
return csr.isSignatureValid(contentVerifierProvider);
} catch (InvalidKeyException e) {
throw new CryptoException(res.getString("NoVerifyPkcs10Csr.exception.message"), e);
} catch (OperatorCreationException e) {
throw new CryptoException(res.getString("NoVerifyPkcs10Csr.exception.message"), e);
} catch (NoSuchAlgorithmException e) {
throw new CryptoException(res.getString("NoVerifyPkcs10Csr.exception.message"), e);
} catch (PKCSException e) {
throw new CryptoException(res.getString("NoVerifyPkcs10Csr.exception.message"), e);
}
}
use of org.kse.crypto.CryptoException in project keystore-explorer by kaikramer.
the class Pkcs10Util method generateCsr.
/**
* Create a PKCS #10 certificate signing request (CSR) using the supplied
* certificate, private key and signature algorithm.
*
* @param cert
* The certificate
* @param privateKey
* The private key
* @param signatureType
* Signature
* @param challenge
* Challenge, optional, pass null if not required
* @param unstructuredName
* An optional company name, pass null if not required
* @param useExtensions
* Use extensions from cert for extensionRequest attribute?
* @throws CryptoException
* If there was a problem generating the CSR
* @return The CSR
*/
public static PKCS10CertificationRequest generateCsr(X509Certificate cert, PrivateKey privateKey, SignatureType signatureType, String challenge, String unstructuredName, boolean useExtensions, Provider provider) throws CryptoException {
try {
JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(cert.getSubjectX500Principal(), cert.getPublicKey());
// add challenge attribute
if (challenge != null) {
// PKCS#9 2.0: SHOULD use UTF8String encoding
csrBuilder.addAttribute(pkcs_9_at_challengePassword, new DERUTF8String(challenge));
}
if (unstructuredName != null) {
csrBuilder.addAttribute(pkcs_9_at_unstructuredName, new DERUTF8String(unstructuredName));
}
if (useExtensions) {
// add extensionRequest attribute with all extensions from the certificate
Certificate certificate = Certificate.getInstance(cert.getEncoded());
Extensions extensions = certificate.getTBSCertificate().getExtensions();
if (extensions != null) {
csrBuilder.addAttribute(pkcs_9_at_extensionRequest, extensions.toASN1Primitive());
}
}
// fall back to bouncy castle provider if given provider does not support the requested algorithm
if (provider != null && provider.getService("Signature", signatureType.jce()) == null) {
provider = new BouncyCastleProvider();
}
ContentSigner contentSigner = null;
if (provider == null) {
contentSigner = new JcaContentSignerBuilder(signatureType.jce()).build(privateKey);
} else {
contentSigner = new JcaContentSignerBuilder(signatureType.jce()).setProvider(provider).build(privateKey);
}
PKCS10CertificationRequest csr = csrBuilder.build(contentSigner);
if (!verifyCsr(csr)) {
throw new CryptoException(res.getString("NoVerifyGenPkcs10Csr.exception.message"));
}
return csr;
} catch (CertificateEncodingException e) {
throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e);
} catch (OperatorCreationException e) {
throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e);
}
}
Aggregations