Search in sources :

Example 16 with PrivateKey

use of java.security.PrivateKey in project android_frameworks_base by ParanoidAndroid.

the class AndroidKeyStoreTest method testKeyStore_SetKeyEntry_Encrypted_Success.

public void testKeyStore_SetKeyEntry_Encrypted_Success() throws Exception {
    setupPassword();
    mKeyStore.load(null, null);
    final CertificateFactory f = CertificateFactory.getInstance("X.509");
    final Certificate caCert = f.generateCertificate(new ByteArrayInputStream(FAKE_CA_1));
    KeyFactory keyFact = KeyFactory.getInstance("RSA");
    PrivateKey privKey = keyFact.generatePrivate(new PKCS8EncodedKeySpec(FAKE_KEY_1));
    final Certificate[] chain = new Certificate[2];
    chain[0] = f.generateCertificate(new ByteArrayInputStream(FAKE_USER_1));
    chain[1] = caCert;
    mKeyStore.setKeyEntry(TEST_ALIAS_1, privKey, null, chain);
    Entry actualEntry = mKeyStore.getEntry(TEST_ALIAS_1, null);
    assertNotNull("Retrieved entry should exist", actualEntry);
    assertTrue("Retrieved entry should be of type PrivateKeyEntry", actualEntry instanceof PrivateKeyEntry);
    PrivateKeyEntry actual = (PrivateKeyEntry) actualEntry;
    assertPrivateKeyEntryEquals(actual, FAKE_KEY_1, FAKE_USER_1, FAKE_CA_1);
}
Also used : TrustedCertificateEntry(java.security.KeyStore.TrustedCertificateEntry) PrivateKeyEntry(java.security.KeyStore.PrivateKeyEntry) Entry(java.security.KeyStore.Entry) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) ByteArrayInputStream(java.io.ByteArrayInputStream) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) CertificateFactory(java.security.cert.CertificateFactory) PrivateKeyEntry(java.security.KeyStore.PrivateKeyEntry) KeyFactory(java.security.KeyFactory) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 17 with PrivateKey

use of java.security.PrivateKey in project OpenAttestation by OpenAttestation.

the class Pkcs12 method getRsaCredentialX509.

public RsaCredentialX509 getRsaCredentialX509(String keyAlias, String keyPassword) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException, FileNotFoundException, CertificateEncodingException {
    // load the key pair
    //NoSuchAlgorithmException, UnrecoverableEntryException, KeyStoreException
    KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) keystore.getEntry(keyAlias, new KeyStore.PasswordProtection(keyPassword.toCharArray()));
    if (pkEntry != null) {
        PrivateKey myPrivateKey = pkEntry.getPrivateKey();
        Certificate myCertificate = pkEntry.getCertificate();
        if (myCertificate instanceof X509Certificate) {
            //CertificateEncodingException, NoSuchAlgorithmException
            return new RsaCredentialX509(myPrivateKey, (X509Certificate) myCertificate);
        }
        throw new IllegalArgumentException("Key has a certificate that is not X509: " + myCertificate.getType());
    //PublicKey myPublicKey = pkEntry.getCertificate().getPublicKey();
    //return new RsaCredential(myPrivateKey, myPublicKey);
    }
    // key pair not found
    throw new FileNotFoundException("Keystore does not contain the specified key");
}
Also used : PrivateKey(java.security.PrivateKey) FileNotFoundException(java.io.FileNotFoundException) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 18 with PrivateKey

use of java.security.PrivateKey in project OpenAttestation by OpenAttestation.

the class Diagnostic method trySignature.

private static void trySignature() {
    String algorithmName = "SHA1withRSA";
    try {
        // generate keypair
        // NoSuchAlgorithmException, NoSuchProviderException
        KeyPair keyPair = KeyPairGenerator.getInstance("RSA", "BC").generateKeyPair();
        PrivateKey privateKey = keyPair.getPrivate();
        String plaintext = "This is the message being signed";
        // generate signature
        // NoSuchAlgorithmException, NoSuchProviderException
        Signature instance = Signature.getInstance("SHA1withRSAEncryption", "BC");
        // InvalidKeyException
        instance.initSign(privateKey);
        // SignatureException
        instance.update((plaintext).getBytes());
        byte[] signature = instance.sign();
        System.out.println("Generated SHA1 with RSA signature of length: " + signature.length);
    } catch (NoSuchProviderException e) {
        System.err.println("Cannot use provider: BC: " + e.toString());
    } catch (NoSuchAlgorithmException e) {
        System.err.println("Cannot use algorithm: " + algorithmName + ": " + e.toString());
    } catch (InvalidKeyException e) {
        System.err.println("Cannot use key: " + e.toString());
    } catch (SignatureException e) {
        System.err.println("Cannot generate signature: " + e.toString());
    }
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) Signature(java.security.Signature) JDKDigestSignature(org.bouncycastle.jce.provider.JDKDigestSignature) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SignatureException(java.security.SignatureException) NoSuchProviderException(java.security.NoSuchProviderException) InvalidKeyException(java.security.InvalidKeyException)

Example 19 with PrivateKey

use of java.security.PrivateKey in project Openfire by igniterealtime.

the class CertificateManager method installCert.

/**
     * Imports a new signed certificate and its private key into the keystore. The certificate input
     * stream may contain the signed certificate as well as its CA chain.
     *
     * @param keyStore    key store where the certificate will be stored.
     * @param trustStore  key store where ca certificates are stored.
     * @param keyPassword password of the keystore.
     * @param alias the alias of the the new signed certificate.
     * @param pkInputStream the stream containing the private key.
     * @param passPhrase is the password phrased used when creating the private key.
     * @param inputStream the stream containing the signed certificate.
     * @return true if the certificate was successfully imported.
     * @throws Exception if no certificates were found in the inputStream.
     */
public static boolean installCert(KeyStore keyStore, KeyStore trustStore, String keyPassword, String alias, InputStream pkInputStream, final String passPhrase, InputStream inputStream) throws Exception {
    // Check that there is a certificate for the specified alias
    X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias);
    if (certificate != null) {
        Log.warn("Certificate already exists for alias: " + alias);
        return false;
    }
    PrivateKey privKey = parsePrivateKey(pkInputStream, passPhrase);
    Collection<X509Certificate> certs = parseCertificates(inputStream);
    if (certs.isEmpty()) {
        throw new Exception("No certificates were found");
    }
    List<X509Certificate> newCerts;
    if (certs.size() == 1) {
        // Reply has only one certificate
        newCerts = establishCertChain(keyStore, trustStore, certificate, certs.iterator().next());
    } else {
        // Reply has a chain of certificates
        newCerts = validateReply(keyStore, trustStore, alias, certificate, certs);
    }
    if (newCerts == null) {
        return false;
    }
    keyStore.setKeyEntry(alias, privKey, keyPassword.toCharArray(), newCerts.toArray(new X509Certificate[newCerts.size()]));
    // Notify listeners that a new certificate has been created (and signed)
    for (CertificateEventListener listener : listeners) {
        try {
            listener.certificateCreated(keyStore, alias, newCerts.get(0));
            if (newCerts.size() > 1) {
                listener.certificateSigned(keyStore, alias, newCerts);
            }
        } catch (Exception e) {
            Log.error(e.getMessage(), e);
        }
    }
    return true;
}
Also used : PrivateKey(java.security.PrivateKey) X509Certificate(java.security.cert.X509Certificate) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) KeyStoreException(java.security.KeyStoreException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) CertException(org.bouncycastle.cert.CertException) CertPathBuilderException(java.security.cert.CertPathBuilderException) PKCSException(org.bouncycastle.pkcs.PKCSException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 20 with PrivateKey

use of java.security.PrivateKey in project Openfire by igniterealtime.

the class CertificateManager method createX509V3Certificate.

/**
     * Creates an X509 version3 certificate.
     *
     * @param kp           KeyPair that keeps the public and private keys for the new certificate.
     * @param days       time to live
     * @param issuerBuilder     IssuerDN builder
     * @param subjectBuilder    SubjectDN builder
     * @param domain       Domain of the server.
     * @param signAlgoritm Signature algorithm. This can be either a name or an OID.
     * @return X509 V3 Certificate
     * @throws GeneralSecurityException
     * @throws IOException
     */
public static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int days, X500NameBuilder issuerBuilder, X500NameBuilder subjectBuilder, String domain, String signAlgoritm) throws GeneralSecurityException, IOException {
    PublicKey pubKey = kp.getPublic();
    PrivateKey privKey = kp.getPrivate();
    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed((new Date().getTime()));
    random.nextBytes(serno);
    BigInteger serial = (new java.math.BigInteger(serno)).abs();
    X500Name issuerDN = issuerBuilder.build();
    X500Name subjectDN = subjectBuilder.build();
    // builder
    JcaX509v3CertificateBuilder certBuilder = new //
    JcaX509v3CertificateBuilder(//
    issuerDN, //
    serial, //
    new Date(), //
    new Date(System.currentTimeMillis() + days * (1000L * 60 * 60 * 24)), //
    subjectDN, //
    pubKey);
    // add subjectAlternativeName extension
    boolean critical = subjectDN.getRDNs().length == 0;
    ASN1Sequence othernameSequence = new DERSequence(new ASN1Encodable[] { new ASN1ObjectIdentifier("1.3.6.1.5.5.7.8.5"), new DERUTF8String(domain) });
    GeneralName othernameGN = new GeneralName(GeneralName.otherName, othernameSequence);
    GeneralNames subjectAltNames = new GeneralNames(new GeneralName[] { othernameGN });
    certBuilder.addExtension(Extension.subjectAlternativeName, critical, subjectAltNames);
    // add keyIdentifiers extensions
    JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils();
    certBuilder.addExtension(Extension.subjectKeyIdentifier, false, utils.createSubjectKeyIdentifier(pubKey));
    certBuilder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(pubKey));
    try {
        // build the certificate
        ContentSigner signer = new JcaContentSignerBuilder(signAlgoritm).build(privKey);
        X509CertificateHolder cert = certBuilder.build(signer);
        // verify the validity
        if (!cert.isValidOn(new Date())) {
            throw new GeneralSecurityException("Certificate validity not valid");
        }
        // verify the signature (self-signed)
        ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder().build(pubKey);
        if (!cert.isSignatureValid(verifierProvider)) {
            throw new GeneralSecurityException("Certificate signature not valid");
        }
        return new JcaX509CertificateConverter().getCertificate(cert);
    } catch (OperatorCreationException | CertException e) {
        throw new GeneralSecurityException(e);
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) PrivateKey(java.security.PrivateKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) X500Name(org.bouncycastle.asn1.x500.X500Name) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider) PublicKey(java.security.PublicKey) GeneralSecurityException(java.security.GeneralSecurityException) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) CertException(org.bouncycastle.cert.CertException) Date(java.util.Date) JcaContentVerifierProviderBuilder(org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) GeneralName(org.bouncycastle.asn1.x509.GeneralName)

Aggregations

PrivateKey (java.security.PrivateKey)517 X509Certificate (java.security.cert.X509Certificate)217 KeyFactory (java.security.KeyFactory)169 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)144 Certificate (java.security.cert.Certificate)127 PublicKey (java.security.PublicKey)120 ByteArrayInputStream (java.io.ByteArrayInputStream)118 KeyStore (java.security.KeyStore)93 CertificateFactory (java.security.cert.CertificateFactory)92 IOException (java.io.IOException)81 Key (java.security.Key)74 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)73 PrivateKeyEntry (java.security.KeyStore.PrivateKeyEntry)70 Entry (java.security.KeyStore.Entry)60 TrustedCertificateEntry (java.security.KeyStore.TrustedCertificateEntry)60 KeyPair (java.security.KeyPair)59 SecretKey (javax.crypto.SecretKey)48 InvalidKeyException (java.security.InvalidKeyException)47 KeyStoreException (java.security.KeyStoreException)46 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)46