Search in sources :

Example 16 with CryptoException

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);
    }
}
Also used : ECPrivateKey(java.security.interfaces.ECPrivateKey) RSAPrivateCrtKey(java.security.interfaces.RSAPrivateCrtKey) IOException(java.io.IOException) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) DSAParams(java.security.interfaces.DSAParams) DERSequence(org.bouncycastle.asn1.DERSequence) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) BigInteger(java.math.BigInteger) CryptoException(org.kse.crypto.CryptoException)

Example 17 with CryptoException

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);
    }
}
Also used : InputDecryptorProvider(org.bouncycastle.operator.InputDecryptorProvider) ByteArrayInputStream(java.io.ByteArrayInputStream) PemInfo(org.kse.utilities.pem.PemInfo) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) JceOpenSSLPKCS8DecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) CryptoException(org.kse.crypto.CryptoException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) CryptoException(org.kse.crypto.CryptoException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) EncryptedPrivateKeyInfo(javax.crypto.EncryptedPrivateKeyInfo) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo)

Example 18 with CryptoException

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);
    }
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) IOException(java.io.IOException) CryptoException(org.kse.crypto.CryptoException) DEROutputStream(org.bouncycastle.asn1.DEROutputStream)

Example 19 with CryptoException

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);
    }
}
Also used : JcaPKCS10CertificationRequest(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest) JcaContentVerifierProviderBuilder(org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder) PublicKey(java.security.PublicKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) CryptoException(org.kse.crypto.CryptoException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) PKCSException(org.bouncycastle.pkcs.PKCSException) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider)

Example 20 with CryptoException

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);
    }
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) JcaPKCS10CertificationRequest(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) CertificateEncodingException(java.security.cert.CertificateEncodingException) Extensions(org.bouncycastle.asn1.x509.Extensions) CryptoException(org.kse.crypto.CryptoException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Aggregations

CryptoException (org.kse.crypto.CryptoException)80 GeneralSecurityException (java.security.GeneralSecurityException)22 IOException (java.io.IOException)21 X509Certificate (java.security.cert.X509Certificate)21 KeyStore (java.security.KeyStore)16 KeyStoreException (java.security.KeyStoreException)13 BigInteger (java.math.BigInteger)11 DError (org.kse.gui.error.DError)10 ByteArrayInputStream (java.io.ByteArrayInputStream)9 File (java.io.File)9 DefaultMutableTreeNode (javax.swing.tree.DefaultMutableTreeNode)9 ByteBuffer (java.nio.ByteBuffer)8 CertificateException (java.security.cert.CertificateException)8 PrivateKey (java.security.PrivateKey)7 KeyFactory (java.security.KeyFactory)6 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)6 CertificateFactory (java.security.cert.CertificateFactory)6 DSAPrivateKey (java.security.interfaces.DSAPrivateKey)6 RSAPrivateCrtKey (java.security.interfaces.RSAPrivateCrtKey)6 Cipher (javax.crypto.Cipher)6