Search in sources :

Example 61 with X500Name

use of org.openecard.bouncycastle.asn1.x500.X500Name in project jetty-bootstrap by teknux-org.

the class JettyKeystoreGeneratorBuilder method generateCertificate.

private static Certificate generateCertificate(KeyPair keyPair, String domainName, String signatureAlgorithm, String rdnOuValue, String rdnOValue, int dateNotBeforeNumberOfDays, int dateNotAfterNumberOfDays) throws JettyKeystoreException {
    X500NameBuilder issuerX500Namebuilder = new X500NameBuilder(BCStyle.INSTANCE);
    if (rdnOuValue != null) {
        issuerX500Namebuilder.addRDN(BCStyle.OU, rdnOuValue);
    }
    if (rdnOValue != null) {
        issuerX500Namebuilder.addRDN(BCStyle.O, rdnOValue);
    }
    X500Name issuer = issuerX500Namebuilder.addRDN(BCStyle.CN, domainName).build();
    BigInteger serial = BigInteger.valueOf(Math.abs(new SecureRandom().nextInt()));
    Date dateNotBefore = new Date(System.currentTimeMillis() - (dateNotBeforeNumberOfDays * DAY_IN_MILLIS));
    Date dateNotAfter = new Date(System.currentTimeMillis() + (dateNotAfterNumberOfDays * DAY_IN_MILLIS));
    X500NameBuilder subjectX500Namebuilder = new X500NameBuilder(BCStyle.INSTANCE);
    if (rdnOuValue != null) {
        subjectX500Namebuilder.addRDN(BCStyle.OU, rdnOuValue);
    }
    if (rdnOValue != null) {
        subjectX500Namebuilder.addRDN(BCStyle.O, rdnOValue);
    }
    X500Name subject = subjectX500Namebuilder.addRDN(BCStyle.CN, domainName).build();
    SubjectPublicKeyInfo publicKeyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(keyPair.getPublic().getEncoded()));
    X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(issuer, serial, dateNotBefore, dateNotAfter, subject, publicKeyInfo);
    Provider provider = new BouncyCastleProvider();
    try {
        ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(provider).build(keyPair.getPrivate());
        return new JcaX509CertificateConverter().setProvider(provider).getCertificate(x509v3CertificateBuilder.build(signer));
    } catch (OperatorCreationException | CertificateException e) {
        throw new JettyKeystoreException(JettyKeystoreException.ERROR_CREATE_CERTIFICATE, "Can not generate certificate", e);
    }
}
Also used : X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) CertificateException(java.security.cert.CertificateException) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) Provider(java.security.Provider) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) BigInteger(java.math.BigInteger) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 62 with X500Name

use of org.openecard.bouncycastle.asn1.x500.X500Name in project athenz by yahoo.

the class ZTSClientTest method testGenerateInstanceRefreshRequestSubDomain.

@Test
public void testGenerateInstanceRefreshRequestSubDomain() {
    File privkey = new File("./src/test/resources/test_private_k0.pem");
    PrivateKey privateKey = Crypto.loadPrivateKey(privkey);
    InstanceRefreshRequest req = ZTSClient.generateInstanceRefreshRequest("coretech.system", "test", privateKey, "aws", 3600);
    assertNotNull(req);
    PKCS10CertificationRequest certReq = Crypto.getPKCS10CertRequest(req.getCsr());
    assertEquals("coretech.system.test", Crypto.extractX509CSRCommonName(certReq));
    X500Name x500name = certReq.getSubject();
    RDN cnRdn = x500name.getRDNs(BCStyle.CN)[0];
    assertEquals("coretech.system.test", IETFUtils.valueToString(cnRdn.getFirst().getValue()));
    assertEquals("test.coretech-system.aws.athenz.cloud", Crypto.extractX509CSRDnsNames(certReq).get(0));
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) PrivateKey(java.security.PrivateKey) X500Name(org.bouncycastle.asn1.x500.X500Name) File(java.io.File) RDN(org.bouncycastle.asn1.x500.RDN) Test(org.testng.annotations.Test)

Example 63 with X500Name

use of org.openecard.bouncycastle.asn1.x500.X500Name in project athenz by yahoo.

the class SelfCertSignerFactory method create.

@Override
public CertSigner create() {
    // extract the private key for this self cert signer
    final String pKeyFileName = System.getProperty(ZTSConsts.ZTS_PROP_SELF_SIGNER_PRIVATE_KEY_FNAME);
    final String pKeyPassword = System.getProperty(ZTSConsts.ZTS_PROP_SELF_SIGNER_PRIVATE_KEY_PASSWORD);
    final String csrDn = System.getProperty(ZTSConsts.ZTS_PROP_SELF_SIGNER_CERT_DN, "cn=Self Signed Athenz CA,o=Athenz,c=US");
    if (pKeyFileName == null) {
        LOGGER.error("No private key path available for Self Cert Signer Factory");
        return null;
    }
    File caKey = new File(pKeyFileName);
    PrivateKey caPrivateKey = Crypto.loadPrivateKey(caKey, pKeyPassword);
    // now generate a CSR for our own CA and self sign it
    String csr = null;
    try {
        csr = Crypto.generateX509CSR(caPrivateKey, csrDn, null);
    } catch (OperatorCreationException | IOException ex) {
        LOGGER.error("Unable to generate X509 CSR for dn: " + csrDn + ", error: " + ex.getMessage());
        return null;
    }
    // generate our self signed certificate
    X500Principal subject = new X500Principal(csrDn);
    X500Name issuer = X500Name.getInstance(subject.getEncoded());
    PKCS10CertificationRequest certReq = Crypto.getPKCS10CertRequest(csr);
    X509Certificate caCertificate = Crypto.generateX509Certificate(certReq, caPrivateKey, issuer, 30 * 24 * 60, true);
    return new SelfCertSigner(caPrivateKey, caCertificate);
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) PrivateKey(java.security.PrivateKey) X500Principal(javax.security.auth.x500.X500Principal) IOException(java.io.IOException) X500Name(org.bouncycastle.asn1.x500.X500Name) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) File(java.io.File) X509Certificate(java.security.cert.X509Certificate)

Example 64 with X500Name

use of org.openecard.bouncycastle.asn1.x500.X500Name in project portal by ixinportal.

the class GenUtil method GenP10.

public static String GenP10(String userid, String subject, String alg) throws GenP10Exception {
    if (!"".equalsIgnoreCase(userid)) {
        if (keyMap.containsKey(userid)) {
            throw new GenP10Exception("用户唯一标识【" + userid + "】不能重复");
        }
    } else {
        throw new GenP10Exception("用户唯一标识不能为空");
    }
    KeyPairGenerator kpg = null;
    try {
        kpg = KeyPairGenerator.getInstance(alg);
    } catch (NoSuchAlgorithmException e1) {
        throw new GenP10Exception("输入秘钥对产生算法不正确:" + alg);
    }
    if ("SM2".equalsIgnoreCase(alg)) {
        kpg.initialize(256);
    } else {
        kpg.initialize(2048);
    }
    KeyPair kp = kpg.generateKeyPair();
    keyMap.put(userid, kp);
    byte[] publickey = kp.getPublic().getEncoded();
    final String pubAlg = kp.getPublic().getAlgorithm();
    String sAlg = null;
    try {
        sAlg = AlgorithmId.get(pubAlg).getOID().toString();
    } catch (NoSuchAlgorithmException e1) {
        throw new GenP10Exception("输入秘钥对产生算法不正确:" + sAlg);
    }
    SubjectPublicKeyInfo spki = null;
    if (sAlg.equals("1.2.156.10197.1.301")) {
        spki = SubjectPublicKeyInfo.getInstance(publickey);
    } else {
        spki = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(publickey));
    }
    if ("".equals(subject)) {
        subject = "CN=defaultName";
    }
    X500Name x500 = new X500Name(subject);
    PKCS10CertificationRequestBuilder prb = new PKCS10CertificationRequestBuilder(x500, spki);
    ContentSigner signer = null;
    PrivateKey privateKey = kp.getPrivate();
    final Signature sign;
    try {
        if (privateKey.getAlgorithm().equals("SM2")) {
            sign = Signature.getInstance("SM3withSM2");
        } else {
            sign = Signature.getInstance("SHA1withRSA");
        }
        sign.initSign(privateKey);
    } catch (NoSuchAlgorithmException e) {
        throw new GenP10Exception("输入秘钥对产生算法不正确:SHA1withRSA");
    } catch (InvalidKeyException e) {
        throw new GenP10Exception("无效的私钥信息");
    }
    signer = new ContentSigner() {

        ByteArrayOutputStream originStream = new ByteArrayOutputStream();

        public byte[] getSignature() {
            try {
                sign.update(this.originStream.toByteArray());
                return sign.sign();
            } catch (SignatureException e) {
                throw new RuntimeException(e);
            }
        }

        public OutputStream getOutputStream() {
            return this.originStream;
        }

        public AlgorithmIdentifier getAlgorithmIdentifier() {
            try {
                return new AlgorithmIdentifier(AlgorithmId.get(pubAlg).getOID().toString());
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e);
            }
        }
    };
    PKCS10CertificationRequestHolder pr = prb.build(signer);
    try {
        return new String(Base64.encode(pr.getEncoded()));
    } catch (IOException e) {
        throw new GenP10Exception("产生CSR错误,请检查输入参数");
    }
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) GenP10Exception(com.itrus.Exception.GenP10Exception) ContentSigner(org.bouncycastle.operator.ContentSigner) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) KeyPairGenerator(java.security.KeyPairGenerator) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) X500Name(org.bouncycastle.asn1.x500.X500Name) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SignatureException(java.security.SignatureException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) PKCS10CertificationRequestHolder(org.bouncycastle.pkcs.PKCS10CertificationRequestHolder) Signature(java.security.Signature)

Example 65 with X500Name

use of org.openecard.bouncycastle.asn1.x500.X500Name in project groovity by disney.

the class TestKeys method testCertificate.

@Test
public void testCertificate() throws Exception {
    URI keyLoc = new URI("mem:myCertificate");
    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
    generator.initialize(2048);
    KeyPair keyPair = generator.generateKeyPair();
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(new X500Name("CN=Some authority, OU=DATG, O=Disney, C=US"), new BigInteger(64, new SecureRandom()), // yesterday
    new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000), // 10 years
    new Date(System.currentTimeMillis() + 10 * 365 * 24 * 60 * 60 * 1000), new X500Name("DN=mySubject"), SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));
    JcaContentSignerBuilder builder = new JcaContentSignerBuilder("SHA256withRSA");
    ContentSigner signer = builder.build(keyPair.getPrivate());
    byte[] certBytes = certBuilder.build(signer).getEncoded();
    Certificate cert = CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(certBytes));
    URIParcel<Certificate> certParcel = new URIParcel<Certificate>(Certificate.class, keyLoc);
    certParcel.put(cert);
    byte[] rawBytes = URIParcel.get(keyLoc, byte[].class);
    Assert.assertTrue("Expected X509 certificate", new String(rawBytes).startsWith("-----BEGIN CERTIFICATE-----"));
    Certificate rc = URIParcel.get(keyLoc, Certificate.class);
    Assert.assertEquals(keyPair.getPublic(), rc.getPublicKey());
}
Also used : KeyPair(java.security.KeyPair) URIParcel(com.disney.uriparcel.URIParcel) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) KeyPairGenerator(java.security.KeyPairGenerator) X500Name(org.bouncycastle.asn1.x500.X500Name) URI(java.net.URI) Date(java.util.Date) ByteArrayInputStream(java.io.ByteArrayInputStream) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) BigInteger(java.math.BigInteger) Certificate(java.security.cert.Certificate) Test(org.junit.Test)

Aggregations

X500Name (org.bouncycastle.asn1.x500.X500Name)193 X509Certificate (java.security.cert.X509Certificate)88 Date (java.util.Date)71 BigInteger (java.math.BigInteger)63 X500Name (sun.security.x509.X500Name)53 IOException (java.io.IOException)49 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)47 ContentSigner (org.bouncycastle.operator.ContentSigner)45 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)44 RDN (org.bouncycastle.asn1.x500.RDN)43 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)42 KeyPair (java.security.KeyPair)41 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)41 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)36 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)33 PrivateKey (java.security.PrivateKey)32 KeyPairGenerator (java.security.KeyPairGenerator)31 GeneralName (org.bouncycastle.asn1.x509.GeneralName)31 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)28 SecureRandom (java.security.SecureRandom)27