Search in sources :

Example 21 with PrivateKey

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

the class CertificateManager method installReply.

/**
     * Installs the Certificate Authority reply returned as part of the signing request. The certificate
     * being signed will get its certificate chain updated with the imported certificate(s). An exception
     * will be thrown if the replied certificate does not match a local certificate or if the signing
     * authority is not known by the server (i.e. keystore and truststore files)
     *
     * The identity of the entity that has signed the reply is verified against the provided trust store.
     *
     * The
     *
     * @param keyStore    key store where the certificate is stored.
     * @param trustStore  key store where ca certificates are stored.
     * @param keyPassword password of the keystore.
     * @param alias the alias of the existing certificate being signed.
     * @param inputStream the stream containing the CA reply.
     * @return true if the CA reply was successfully processed.
     * @throws Exception
     */
public static boolean installReply(KeyStore keyStore, KeyStore trustStore, char[] keyPassword, String alias, 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 not found for alias: " + alias);
        return false;
    }
    // Retrieve the private key of the stored certificate
    PrivateKey privKey = (PrivateKey) keyStore.getKey(alias, keyPassword);
    // Load certificates found in the PEM input stream
    Collection<X509Certificate> certs = parseCertificates(inputStream);
    if (certs.isEmpty()) {
        throw new Exception("Reply has no certificates");
    }
    List<X509Certificate> newCerts;
    if (certs.size() == 1) {
        // Reply has only one certificate
        newCerts = establishCertChain(keyStore, trustStore, null, certs.iterator().next());
    } else {
        // Reply has a chain of certificates
        newCerts = validateReply(keyStore, trustStore, alias, null, certs);
    }
    if (newCerts == null) {
        return false;
    }
    keyStore.setKeyEntry(alias, privKey, keyPassword, newCerts.toArray(new X509Certificate[newCerts.size()]));
    // Notify listeners that a new certificate has been created
    for (CertificateEventListener listener : listeners) {
        try {
            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 22 with PrivateKey

use of java.security.PrivateKey in project PushSms by koush.

the class MiddlewareService method getOrCreateKeyPair.

// create/read the keypair as necessary
private void getOrCreateKeyPair() {
    String encodedKeyPair = settings.getString("keypair", null);
    if (encodedKeyPair != null) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            ByteArrayInputStream bin = new ByteArrayInputStream(Base64.decode(encodedKeyPair, Base64.DEFAULT));
            ObjectInputStream in = new ObjectInputStream(bin);
            rsaPublicKeySpec = new RSAPublicKeySpec((BigInteger) in.readObject(), (BigInteger) (in.readObject()));
            RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec((BigInteger) in.readObject(), (BigInteger) (in.readObject()));
            PublicKey pub = keyFactory.generatePublic(rsaPublicKeySpec);
            PrivateKey priv = keyFactory.generatePrivate(rsaPrivateKeySpec);
            keyPair = new KeyPair(pub, priv);
            return;
        } catch (Exception e) {
            Log.e(LOGTAG, "KeyPair load error", e);
        }
    }
    try {
        KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
        gen.initialize(2048);
        keyPair = gen.generateKeyPair();
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        rsaPublicKeySpec = keyFactory.getKeySpec(keyPair.getPublic(), RSAPublicKeySpec.class);
        RSAPrivateKeySpec privateKeySpec = keyFactory.getKeySpec(keyPair.getPrivate(), RSAPrivateKeySpec.class);
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(bout);
        out.writeObject(rsaPublicKeySpec.getModulus());
        out.writeObject(rsaPublicKeySpec.getPublicExponent());
        out.writeObject(privateKeySpec.getModulus());
        out.writeObject(privateKeySpec.getPrivateExponent());
        out.flush();
        settings.edit().putString("keypair", Base64.encodeToString(bout.toByteArray(), Base64.DEFAULT)).commit();
        settings.edit().putBoolean("needs_register", true).commit();
    } catch (Exception e) {
        Log.wtf(LOGTAG, "KeyPair generation error", e);
        keyPair = null;
    }
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) KeyPairGenerator(java.security.KeyPairGenerator) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectOutputStream(java.io.ObjectOutputStream) RemoteException(android.os.RemoteException) IOException(java.io.IOException) RSAPrivateKeySpec(java.security.spec.RSAPrivateKeySpec) ByteArrayInputStream(java.io.ByteArrayInputStream) BigInteger(java.math.BigInteger) KeyFactory(java.security.KeyFactory) ObjectInputStream(java.io.ObjectInputStream)

Example 23 with PrivateKey

use of java.security.PrivateKey in project jjwt by jwtk.

the class EllipticCurveSigner method doSign.

protected byte[] doSign(byte[] data) throws InvalidKeyException, java.security.SignatureException, JwtException {
    PrivateKey privateKey = (PrivateKey) key;
    Signature sig = createSignatureInstance();
    sig.initSign(privateKey);
    sig.update(data);
    return transcodeSignatureToConcat(sig.sign(), getSignatureByteArrayLength(alg));
}
Also used : PrivateKey(java.security.PrivateKey) ECPrivateKey(java.security.interfaces.ECPrivateKey) Signature(java.security.Signature)

Example 24 with PrivateKey

use of java.security.PrivateKey in project jjwt by jwtk.

the class RsaSigner method doSign.

protected byte[] doSign(byte[] data) throws InvalidKeyException, java.security.SignatureException {
    PrivateKey privateKey = (PrivateKey) key;
    Signature sig = createSignatureInstance();
    sig.initSign(privateKey);
    sig.update(data);
    return sig.sign();
}
Also used : PrivateKey(java.security.PrivateKey) Signature(java.security.Signature)

Example 25 with PrivateKey

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

the class Certificates method createSelfSignedCertificate.

public void createSelfSignedCertificate(File certificatePath, File privateKeyPath, String hostName) throws GeneralSecurityException, IOException, OperatorCreationException {
    installCleanupHook(certificatePath, privateKeyPath);
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(DEFAULT_ENCRYPTION);
    keyGen.initialize(2048, random);
    KeyPair keypair = keyGen.generateKeyPair();
    // Prepare the information required for generating an X.509 certificate.
    X500Name owner = new X500Name("CN=" + hostName);
    X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(owner, new BigInteger(64, random), NOT_BEFORE, NOT_AFTER, owner, keypair.getPublic());
    PrivateKey privateKey = keypair.getPrivate();
    ContentSigner signer = new JcaContentSignerBuilder("SHA512WithRSAEncryption").build(privateKey);
    X509CertificateHolder certHolder = builder.build(signer);
    X509Certificate cert = new JcaX509CertificateConverter().setProvider(PROVIDER).getCertificate(certHolder);
    //check so that cert is valid
    cert.verify(keypair.getPublic());
    //write to disk
    writePem("CERTIFICATE", cert.getEncoded(), certificatePath);
    writePem("PRIVATE KEY", privateKey.getEncoded(), privateKeyPath);
    // Mark as done so we don't clean up certificates
    cleanupRequired = false;
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) ContentSigner(org.bouncycastle.operator.ContentSigner) BigInteger(java.math.BigInteger) KeyPairGenerator(java.security.KeyPairGenerator) X500Name(org.bouncycastle.asn1.x500.X500Name) X509Certificate(java.security.cert.X509Certificate)

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