Search in sources :

Example 96 with SubjectPublicKeyInfo

use of com.android.apksig.internal.x509.SubjectPublicKeyInfo in project cdap by caskdata.

the class KeyStores method getCertificate.

/**
 * Generate an X.509 certificate
 *
 * @param dn Distinguished name for the owner of the certificate, it will also be the signer of the certificate.
 * @param pair Key pair used for signing the certificate.
 * @param days Validity of the certificate.
 * @param algorithm Name of the signature algorithm used.
 * @return A X.509 certificate
 */
private static Certificate getCertificate(String dn, KeyPair pair, int days, String algorithm) throws IOException, OperatorCreationException, CertificateException {
    BouncyCastleProvider provider = new BouncyCastleProvider();
    // Calculate the validity interval of the certificate
    Date from = new Date();
    Date to = new Date(from.getTime() + TimeUnit.DAYS.toMillis(days));
    // Generate a random number to use as the serial number for the certificate
    BigInteger sn = new BigInteger(64, new SecureRandom());
    // Create the name of the owner based on the provided distinguished name
    X500Name owner = new X500Name(dn);
    // Create an info objects with the provided information, which will be used to create the certificate
    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());
    AsymmetricKeyParameter privateKeyParam = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    ContentSigner signer = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyParam);
    X509CertificateHolder certHolder = new X509v3CertificateBuilder(owner, sn, from, to, owner, publicKeyInfo).build(signer);
    return new JcaX509CertificateConverter().setProvider(provider).getCertificate(certHolder);
}
Also used : ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) DefaultDigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder) Date(java.util.Date) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DefaultSignatureAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder) BcRSAContentSignerBuilder(org.bouncycastle.operator.bc.BcRSAContentSignerBuilder) AsymmetricKeyParameter(org.bouncycastle.crypto.params.AsymmetricKeyParameter) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 97 with SubjectPublicKeyInfo

use of com.android.apksig.internal.x509.SubjectPublicKeyInfo in project dpc-app by CMSgov.

the class PublicKeyHandlerTest method testEncryptionRoundTrip.

@Test
void testEncryptionRoundTrip() throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IOException, InvalidKeySpecException {
    final String plainText = "This should be encrypted";
    final Cipher cipher = Cipher.getInstance("RSA");
    final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    final KeyPair keyPair = kpg.generateKeyPair();
    final String encoded = Base64.getMimeEncoder().encodeToString(keyPair.getPublic().getEncoded());
    final String key = String.format("-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----\n", encoded);
    final SubjectPublicKeyInfo publicKeyInfo = PublicKeyHandler.parsePEMString(key);
    cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate());
    final byte[] cipherText = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
    // Reconstruct the public key and try to decrypt
    X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyInfo.getEncoded());
    final PublicKey rsa = KeyFactory.getInstance("RSA").generatePublic(spec);
    cipher.init(Cipher.DECRYPT_MODE, rsa);
    final byte[] decrypted = cipher.doFinal(cipherText);
    assertEquals(plainText, new String(decrypted), "Should have matching plain text");
}
Also used : X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) Cipher(javax.crypto.Cipher) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 98 with SubjectPublicKeyInfo

use of com.android.apksig.internal.x509.SubjectPublicKeyInfo in project aaa by opendaylight.

the class ODLKeyTool method createKeyStoreWithSelfSignCert.

/**
 * Create a keystore that has self sign private/public keys.
 *
 * @param keyStoreName
 *            the keystore name
 * @param keystorePassword
 *            the keystore password
 * @param distinguishedName
 *            the generated key's Distinguished Name
 * @param keyAlias
 *            the private key alias
 * @param validity
 *            the key validity
 * @param keyAlg
 *            the algorithm that will be used to generate the key
 * @param keySize
 *            the key size
 * @param signAlg
 *            the signing algorithm
 * @return keystore object
 */
public KeyStore createKeyStoreWithSelfSignCert(final String keyStoreName, final String keystorePassword, final String distinguishedName, final String keyAlias, final int validity, final String keyAlg, final int keySize, final String signAlg) {
    try {
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(keyAlg);
        keyPairGenerator.initialize(keySize);
        final KeyPair keyPair = keyPairGenerator.generateKeyPair();
        final long currTime = System.currentTimeMillis();
        final SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
        final X509v3CertificateBuilder x509V3CertBuilder = new X509v3CertificateBuilder(new X500Name(distinguishedName), getSecureRandomeInt(), new Date(currTime), new Date(currTime + KeyStoreConstant.DAY_TIME * validity), new X500Name(distinguishedName), keyInfo);
        final X509CertificateHolder x509Cert = x509V3CertBuilder.build(new JcaContentSignerBuilder(signAlg).build(keyPair.getPrivate()));
        final KeyStore ctlKeyStore = KeyStore.getInstance("JKS");
        ctlKeyStore.load(null, keystorePassword.toCharArray());
        final Certificate[] chain = new Certificate[] { new JcaX509CertificateConverter().getCertificate(x509Cert) };
        ctlKeyStore.setKeyEntry(keyAlias, keyPair.getPrivate(), keystorePassword.toCharArray(), chain);
        LOG.info("{} is created", keyStoreName);
        return ctlKeyStore;
    } catch (final NoSuchAlgorithmException | SecurityException | KeyStoreException | CertificateException | IOException | OperatorCreationException e) {
        LOG.error("Fatal error creating keystore", e);
        return null;
    }
}
Also used : KeyPair(java.security.KeyPair) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) CertificateException(java.security.cert.CertificateException) KeyPairGenerator(java.security.KeyPairGenerator) X500Name(org.bouncycastle.asn1.x500.X500Name) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) KeyStore(java.security.KeyStore) Date(java.util.Date) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 99 with SubjectPublicKeyInfo

use of com.android.apksig.internal.x509.SubjectPublicKeyInfo in project aaa by opendaylight.

the class ODLKeyTool method generateCertificateReq.

/**
 * Generate a certificate signing request based on the given keystore
 * private/public key.
 *
 * @param keyStore
 *            object
 * @param keystorePassword
 *            the keystore password
 * @param keyAlias
 *            Alias of the given keystore's private key.
 * @param signAlg
 *            the signing algorithm
 * @param withTag
 *            true to add the certificate request tag to the certificate
 *            request string.
 * @return certificate request as string.
 */
public String generateCertificateReq(final KeyStore keyStore, final String keystorePassword, final String keyAlias, final String signAlg, final boolean withTag) {
    try {
        if (keyStore.containsAlias(keyAlias)) {
            final X509Certificate odlCert = (X509Certificate) keyStore.getCertificate(keyAlias);
            final PublicKey pubKey = odlCert.getPublicKey();
            final PrivateKey privKey = (PrivateKey) keyStore.getKey(keyAlias, keystorePassword.toCharArray());
            final String subject = odlCert.getSubjectDN().getName();
            final X500Name xName = new X500Name(subject);
            final SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded());
            final PKCS10CertificationRequestBuilder csrb = new PKCS10CertificationRequestBuilder(xName, subPubKeyInfo);
            final ContentSigner contSigner = new JcaContentSignerBuilder(signAlg).build(privKey);
            final String certReq = Base64.getEncoder().encodeToString(csrb.build(contSigner).getEncoded());
            return !withTag ? certReq : new StringBuilder().append(KeyStoreConstant.BEGIN_CERTIFICATE_REQUEST).append('\n').append(certReq).append('\n').append(KeyStoreConstant.END_CERTIFICATE_REQUEST).toString();
        }
        LOG.info("KeyStore does not contain alias {}", keyAlias);
        return StringUtils.EMPTY;
    } catch (final NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | OperatorCreationException | IOException e) {
        LOG.error("Failed to generate certificate request", e);
        return StringUtils.EMPTY;
    }
}
Also used : PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) X500Name(org.bouncycastle.asn1.x500.X500Name) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) X509Certificate(java.security.cert.X509Certificate) UnrecoverableKeyException(java.security.UnrecoverableKeyException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException)

Example 100 with SubjectPublicKeyInfo

use of com.android.apksig.internal.x509.SubjectPublicKeyInfo in project jruby-openssl by jruby.

the class PKey method readECPrivateKey.

public static KeyPair readECPrivateKey(final KeyFactory ecFactory, final byte[] input) throws IOException, InvalidKeySpecException {
    try {
        ECPrivateKeyStructure pKey = new ECPrivateKeyStructure((ASN1Sequence) ASN1Primitive.fromByteArray(input));
        AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, pKey.getParameters());
        PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey.toASN1Primitive());
        SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo(algId, pKey.getPublicKey().getBytes());
        PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privInfo.getEncoded());
        X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubInfo.getEncoded());
        // KeyFactory            fact = KeyFactory.getInstance("ECDSA", provider);
        ECPrivateKey privateKey = (ECPrivateKey) ecFactory.generatePrivate(privSpec);
        if (algId.getParameters() instanceof ASN1ObjectIdentifier) {
            privateKey = ECPrivateKeyWithName.wrap(privateKey, (ASN1ObjectIdentifier) algId.getParameters());
        }
        return new KeyPair(ecFactory.generatePublic(pubSpec), privateKey);
    } catch (ClassCastException ex) {
        throw new IOException("wrong ASN.1 object found in stream", ex);
    }
// catch (Exception ex) {
// throw new IOException("problem parsing EC private key: " + ex);
// }
}
Also used : ECPrivateKey(java.security.interfaces.ECPrivateKey) KeyPair(java.security.KeyPair) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) ECPrivateKeyStructure(org.bouncycastle.asn1.sec.ECPrivateKeyStructure) IOException(java.io.IOException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Aggregations

SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)219 X500Name (org.bouncycastle.asn1.x500.X500Name)92 IOException (java.io.IOException)85 Date (java.util.Date)75 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)75 ContentSigner (org.bouncycastle.operator.ContentSigner)65 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)64 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)61 BigInteger (java.math.BigInteger)54 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)53 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)50 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)42 KeyPair (java.security.KeyPair)39 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)35 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)32 SubjectPublicKeyInfo (com.github.zhenwei.core.asn1.x509.SubjectPublicKeyInfo)30 KeyPairGenerator (java.security.KeyPairGenerator)30 PublicKey (java.security.PublicKey)30 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)30 InvalidKeyException (java.security.InvalidKeyException)28