Search in sources :

Example 86 with SubjectPublicKeyInfo

use of com.android.apksig.internal.x509.SubjectPublicKeyInfo in project incubator-pulsar by apache.

the class MessageCryptoBc method loadPublicKey.

private PublicKey loadPublicKey(byte[] keyBytes) throws Exception {
    Reader keyReader = new StringReader(new String(keyBytes));
    PublicKey publicKey = null;
    try (PEMParser pemReader = new PEMParser(keyReader)) {
        Object pemObj = pemReader.readObject();
        JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
        SubjectPublicKeyInfo keyInfo = null;
        X9ECParameters ecParam = null;
        if (pemObj instanceof ASN1ObjectIdentifier) {
            // make sure this is EC Parameter we're handling. In which case
            // we'll store it and read the next object which should be our
            // EC Public Key
            ASN1ObjectIdentifier ecOID = (ASN1ObjectIdentifier) pemObj;
            ecParam = ECNamedCurveTable.getByOID(ecOID);
            if (ecParam == null) {
                throw new PEMException("Unable to find EC Parameter for the given curve oid: " + ((ASN1ObjectIdentifier) pemObj).getId());
            }
            pemObj = pemReader.readObject();
        } else if (pemObj instanceof X9ECParameters) {
            ecParam = (X9ECParameters) pemObj;
            pemObj = pemReader.readObject();
        }
        if (pemObj instanceof X509CertificateHolder) {
            keyInfo = ((X509CertificateHolder) pemObj).getSubjectPublicKeyInfo();
        } else {
            keyInfo = (SubjectPublicKeyInfo) pemObj;
        }
        publicKey = pemConverter.getPublicKey(keyInfo);
        if (ecParam != null && ECDSA.equals(publicKey.getAlgorithm())) {
            ECParameterSpec ecSpec = new ECParameterSpec(ecParam.getCurve(), ecParam.getG(), ecParam.getN(), ecParam.getH(), ecParam.getSeed());
            KeyFactory keyFactory = KeyFactory.getInstance(ECDSA, BouncyCastleProvider.PROVIDER_NAME);
            ECPublicKeySpec keySpec = new ECPublicKeySpec(((BCECPublicKey) publicKey).getQ(), ecSpec);
            publicKey = keyFactory.generatePublic(keySpec);
        }
    } catch (IOException | NoSuchAlgorithmException | NoSuchProviderException | InvalidKeySpecException e) {
        throw new Exception(e);
    }
    return publicKey;
}
Also used : BCECPublicKey(org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey) PublicKey(java.security.PublicKey) X9ECParameters(org.bouncycastle.asn1.x9.X9ECParameters) Reader(java.io.Reader) CryptoKeyReader(org.apache.pulsar.client.api.CryptoKeyReader) StringReader(java.io.StringReader) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) ECPublicKeySpec(org.bouncycastle.jce.spec.ECPublicKeySpec) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) ShortBufferException(javax.crypto.ShortBufferException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) CryptoException(org.apache.pulsar.client.api.PulsarClientException.CryptoException) PEMException(org.bouncycastle.openssl.PEMException) IOException(java.io.IOException) BadPaddingException(javax.crypto.BadPaddingException) NoSuchProviderException(java.security.NoSuchProviderException) PEMParser(org.bouncycastle.openssl.PEMParser) ECParameterSpec(org.bouncycastle.jce.spec.ECParameterSpec) PEMException(org.bouncycastle.openssl.PEMException) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) StringReader(java.io.StringReader) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) NoSuchProviderException(java.security.NoSuchProviderException) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) KeyFactory(java.security.KeyFactory)

Example 87 with SubjectPublicKeyInfo

use of com.android.apksig.internal.x509.SubjectPublicKeyInfo in project zookeeper by apache.

the class QuorumSSLTest method buildEndEntityCert.

public X509Certificate buildEndEntityCert(KeyPair keyPair, X509Certificate caCert, PrivateKey caPrivateKey, String hostname, String ipAddress, String crlPath, Integer ocspPort) throws Exception {
    X509CertificateHolder holder = new JcaX509CertificateHolder(caCert);
    ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(caPrivateKey);
    List<GeneralName> generalNames = new ArrayList<>();
    if (hostname != null) {
        generalNames.add(new GeneralName(GeneralName.dNSName, hostname));
    }
    if (ipAddress != null) {
        generalNames.add(new GeneralName(GeneralName.iPAddress, ipAddress));
    }
    SubjectPublicKeyInfo entityKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(PublicKeyFactory.createKey(keyPair.getPublic().getEncoded()));
    X509ExtensionUtils extensionUtils = new BcX509ExtensionUtils();
    JcaX509v3CertificateBuilder jcaX509v3CertificateBuilder = new JcaX509v3CertificateBuilder(holder.getSubject(), new BigInteger(128, new Random()), certStartTime, certEndTime, new X500Name("CN=Test End Entity Certificate"), keyPair.getPublic());
    X509v3CertificateBuilder certificateBuilder = jcaX509v3CertificateBuilder.addExtension(Extension.authorityKeyIdentifier, false, extensionUtils.createAuthorityKeyIdentifier(holder)).addExtension(Extension.subjectKeyIdentifier, false, extensionUtils.createSubjectKeyIdentifier(entityKeyInfo)).addExtension(Extension.basicConstraints, true, new BasicConstraints(false)).addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
    if (!generalNames.isEmpty()) {
        certificateBuilder.addExtension(Extension.subjectAlternativeName, true, new GeneralNames(generalNames.toArray(new GeneralName[] {})));
    }
    if (crlPath != null) {
        DistributionPointName distPointOne = new DistributionPointName(new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, "file://" + crlPath)));
        certificateBuilder.addExtension(Extension.cRLDistributionPoints, false, new CRLDistPoint(new DistributionPoint[] { new DistributionPoint(distPointOne, null, null) }));
    }
    if (ocspPort != null) {
        certificateBuilder.addExtension(Extension.authorityInfoAccess, false, new AuthorityInformationAccess(X509ObjectIdentifiers.ocspAccessMethod, new GeneralName(GeneralName.uniformResourceIdentifier, "http://" + hostname + ":" + ocspPort)));
    }
    return new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(signer));
}
Also used : AuthorityInformationAccess(org.bouncycastle.asn1.x509.AuthorityInformationAccess) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) ArrayList(java.util.ArrayList) DistributionPointName(org.bouncycastle.asn1.x509.DistributionPointName) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) X500Name(org.bouncycastle.asn1.x500.X500Name) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Random(java.util.Random) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) BigInteger(java.math.BigInteger) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BcX509ExtensionUtils(org.bouncycastle.cert.bc.BcX509ExtensionUtils) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) X509ExtensionUtils(org.bouncycastle.cert.X509ExtensionUtils) BcX509ExtensionUtils(org.bouncycastle.cert.bc.BcX509ExtensionUtils) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint)

Example 88 with SubjectPublicKeyInfo

use of com.android.apksig.internal.x509.SubjectPublicKeyInfo in project axis-axis2-java-core by apache.

the class JettyServer method generateKeys.

private void generateKeys() throws Exception {
    SecureRandom random = new SecureRandom();
    // Generate key pair
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024, random);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();
    // Generate certificate
    X500Name dn = new X500Name("cn=localhost,o=Apache");
    BigInteger serial = BigInteger.valueOf(random.nextInt());
    Date notBefore = new Date();
    Date notAfter = new Date(notBefore.getTime() + 3600000L);
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(dn, serial, notBefore, notAfter, dn, subPubKeyInfo);
    X509CertificateHolder certHolder = certBuilder.build(new JcaContentSignerBuilder("SHA1WithRSA").build(privateKey));
    X509Certificate cert = new JcaX509CertificateConverter().getCertificate(certHolder);
    // Build key store
    keyStoreFile = File.createTempFile("keystore", "jks", null);
    String keyStorePassword = generatePassword(random);
    String keyPassword = generatePassword(random);
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(null, null);
    keyStore.setKeyEntry(CERT_ALIAS, privateKey, keyPassword.toCharArray(), new X509Certificate[] { cert });
    writeKeyStore(keyStore, keyStoreFile, keyStorePassword);
    // Build trust store
    KeyStore trustStore = KeyStore.getInstance("JKS");
    trustStore.load(null, null);
    trustStore.setCertificateEntry(CERT_ALIAS, cert);
    serverSslContextFactory = new SslContextFactory();
    serverSslContextFactory.setKeyStorePath(keyStoreFile.getAbsolutePath());
    serverSslContextFactory.setKeyStorePassword(keyStorePassword);
    serverSslContextFactory.setKeyManagerPassword(keyPassword);
    serverSslContextFactory.setCertAlias(CERT_ALIAS);
    clientSslContext = SSLContext.getInstance("TLS");
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(trustStore);
    clientSslContext.init(null, tmfactory.getTrustManagers(), null);
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) SecureRandom(java.security.SecureRandom) KeyPairGenerator(java.security.KeyPairGenerator) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) KeyStore(java.security.KeyStore) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) BigInteger(java.math.BigInteger)

Example 89 with SubjectPublicKeyInfo

use of com.android.apksig.internal.x509.SubjectPublicKeyInfo in project overthere by xebialabs.

the class BouncycastleGenerateSshKey method generate.

@Override
public SshKeyPair generate(final String username, int keySize) {
    try {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(keySize);
        java.security.KeyPair key = keyGen.generateKeyPair();
        PrivateKey priv = key.getPrivate();
        PublicKey pub = key.getPublic();
        String privateKey = new String(Base64.encode(priv.getEncoded(), 0, priv.getEncoded().length));
        String publicKey1 = new String(Base64.encode(pub.getEncoded(), 0, pub.getEncoded().length));
        String publicKey = new String(Base64.encode(publicKey1.getBytes(), 0, publicKey1.getBytes().length));
        RSAKeyPairGenerator rsaKeyPairGenerator = new RSAKeyPairGenerator();
        rsaKeyPairGenerator.init(new RSAKeyGenerationParameters(BigInteger.valueOf(0x10001), CryptoServicesRegistrar.getSecureRandom(), keySize, PrimeCertaintyCalculator.getDefaultCertainty(keySize)));
        AsymmetricCipherKeyPair asymmetricCipherKeyPair = rsaKeyPairGenerator.generateKeyPair();
        PrivateKeyInfo pkInfo = PrivateKeyInfoFactory.createPrivateKeyInfo(asymmetricCipherKeyPair.getPrivate());
        SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(asymmetricCipherKeyPair.getPublic());
        return new SshKeyPair(username, privateKey, publicKey, "");
    } catch (Exception e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}
Also used : PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) RSAKeyPairGenerator(org.bouncycastle.crypto.generators.RSAKeyPairGenerator) KeyPairGenerator(java.security.KeyPairGenerator) RSAKeyPairGenerator(org.bouncycastle.crypto.generators.RSAKeyPairGenerator) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) AsymmetricCipherKeyPair(org.bouncycastle.crypto.AsymmetricCipherKeyPair) RSAKeyGenerationParameters(org.bouncycastle.crypto.params.RSAKeyGenerationParameters) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo)

Example 90 with SubjectPublicKeyInfo

use of com.android.apksig.internal.x509.SubjectPublicKeyInfo in project jmulticard by ctt-gob-es.

the class McElieceKeyFactorySpi method engineGeneratePublic.

/**
 * Converts, if possible, a key specification into a
 * {@link BCMcEliecePublicKey}.  {@link X509EncodedKeySpec}.
 *
 * @param keySpec the key specification
 * @return the McEliece public key
 * @throws InvalidKeySpecException if the key specification is not supported.
 */
protected PublicKey engineGeneratePublic(KeySpec keySpec) throws InvalidKeySpecException {
    if (keySpec instanceof X509EncodedKeySpec) {
        // get the DER-encoded Key according to X.509 from the spec
        byte[] encKey = ((X509EncodedKeySpec) keySpec).getEncoded();
        // decode the SubjectPublicKeyInfo data structure to the pki object
        SubjectPublicKeyInfo pki;
        try {
            pki = SubjectPublicKeyInfo.getInstance(ASN1Primitive.fromByteArray(encKey));
        } catch (IOException e) {
            throw new InvalidKeySpecException(e.toString());
        }
        try {
            if (PQCObjectIdentifiers.mcEliece.equals(pki.getAlgorithm().getAlgorithm())) {
                McEliecePublicKey key = McEliecePublicKey.getInstance(pki.parsePublicKey());
                return new BCMcEliecePublicKey(new McEliecePublicKeyParameters(key.getN(), key.getT(), key.getG()));
            } else {
                throw new InvalidKeySpecException("Unable to recognise OID in McEliece public key");
            }
        } catch (IOException cce) {
            throw new InvalidKeySpecException("Unable to decode X509EncodedKeySpec: " + cce.getMessage());
        }
    }
    throw new InvalidKeySpecException("Unsupported key specification: " + keySpec.getClass() + ".");
}
Also used : X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) McEliecePublicKeyParameters(org.bouncycastle.pqc.crypto.mceliece.McEliecePublicKeyParameters) IOException(java.io.IOException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) McEliecePublicKey(org.bouncycastle.pqc.asn1.McEliecePublicKey)

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