List of usage examples for org.bouncycastle.asn1.x509 X509Extensions AuthorityKeyIdentifier
ASN1ObjectIdentifier AuthorityKeyIdentifier
To view the source code for org.bouncycastle.asn1.x509 X509Extensions AuthorityKeyIdentifier.
Click Source Link
From source file:org.neociclo.odetteftp.util.OnTheFlyHelper.java
License:Apache License
public static X509Certificate generateEndEntityCert(PublicKey entityKey, PrivateKey caKey, X509Certificate caCert) throws Exception { installBouncyCastleProviderIfNecessary(); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(caCert.getSubjectX500Principal()); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + VALIDITY_PERIOD)); certGen.setSubjectDN(new X500Principal("CN=Test End Certificate")); certGen.setPublicKey(entityKey);//w w w. j a va 2 s . c o m certGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(entityKey)); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); return certGen.generate(caKey, BC_PROVIDER); }
From source file:org.nimbustools.auto_common.ezpz_ca.CAFactory.java
License:Apache License
public X509Certificate create(String baseName, int months, KeyPair keyPair) throws Exception { final X509Principal newprincipal = new X509Principal("O=Auto,OU=" + baseName + ",CN=CA"); this.certGen.reset(); /*/*from w w w . j a v a 2 s . c o m*/ "The entity that created the certificate is responsible for assigning it a serial number to distinguish it from other certificates it issues. This information is used in numerous ways, for example when a certificate is revoked its serial number is placed in a Certificate Revocation List (CRL)" */ this.certGen.setSerialNumber(BigInteger.ZERO); final Calendar expires = Calendar.getInstance(); expires.add(Calendar.MONTH, months); this.certGen.setNotBefore(new Date(System.currentTimeMillis() - 10000)); this.certGen.setNotAfter(expires.getTime()); this.certGen.setSubjectDN(newprincipal); this.certGen.setIssuerDN(newprincipal); this.certGen.setSignatureAlgorithm("SHA1withRSA"); final PublicKey pubkey = keyPair.getPublic(); this.certGen.setPublicKey(pubkey); // begin X509/BC security nastiness, not sure these are the very best // choices but it is working... final ByteArrayInputStream in = new ByteArrayInputStream(pubkey.getEncoded()); final SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) new DERInputStream(in).readObject()); final SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki); final ByteArrayInputStream in2 = new ByteArrayInputStream(newprincipal.getEncoded()); final GeneralNames generalNames = new GeneralNames((ASN1Sequence) new DERInputStream(in2).readObject()); final AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(spki, generalNames, BigInteger.ZERO); this.certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); /* this.certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); */ this.certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, ski); this.certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, aki); this.certGen.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.cRLSign | KeyUsage.keyCertSign)); return this.certGen.generateX509Certificate(keyPair.getPrivate()); }
From source file:org.nimbustools.auto_common.ezpz_ca.EzPzCA.java
License:Apache License
public X509CRL generateCRL() throws SignatureException, InvalidKeyException, NoSuchProviderException, CertificateEncodingException { this.crlGen.setThisUpdate(new Date()); final Calendar expires = Calendar.getInstance(); // this is fake, expiration does not matter expires.add(Calendar.MONTH, GenerateNewCert.VALIDITY_MONTHS); this.crlGen.setNextUpdate(expires.getTime()); // this is how you'd actually add an entry if we wanted one: //this.crlGen.addCRLEntry(BigInteger.ONE, new Date(), CRLReason.PRIVILEGE_WITHDRAWN); this.crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier( new SubjectPublicKeyInfo(new AlgorithmIdentifier("RSA"), this.caX509.getEncoded()))); this.crlGen.addExtension(X509Extensions.CRLNumber, false, new CRLNumber(BigInteger.ONE)); return this.crlGen.generateX509CRL(this.caPrivate, "BC"); }
From source file:org.nuxeo.ecm.platform.signature.core.pki.CertServiceImpl.java
License:Open Source License
protected X509Certificate createCertificateFromCSR(PKCS10CertificationRequest csr) throws CertException { X509Certificate cert;//w w w .j a v a 2s. c o m try { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(getRootCertificate().getIssuerX500Principal()); certGen.setSubjectDN(csr.getCertificationRequestInfo().getSubject()); certGen.setNotBefore(getCertStartDate()); certGen.setNotAfter(getCertEndDate()); certGen.setPublicKey(csr.getPublicKey("BC")); certGen.setSignatureAlgorithm(CERT_SIGNATURE_ALGORITHM); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(csr.getPublicKey("BC"))); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(getRootCertificate())); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); ASN1Set attributes = csr.getCertificationRequestInfo().getAttributes(); for (int i = 0; i != attributes.size(); i++) { Attribute attr = Attribute.getInstance(attributes.getObjectAt(i)); if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0)); @SuppressWarnings("rawtypes") Enumeration e = extensions.oids(); while (e.hasMoreElements()) { DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement(); X509Extension ext = extensions.getExtension(oid); certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets()); } } } KeyPair rootKeyPair = getKeyPair(rootService.getRootKeyStore(), rootService.getRootKeyAlias(), rootService.getRootCertificateAlias(), rootService.getRootKeyPassword()); cert = certGen.generate(rootKeyPair.getPrivate(), "BC"); } catch (CertificateParsingException e) { throw new CertException(e); } catch (CertificateEncodingException e) { throw new CertException(e); } catch (InvalidKeyException e) { throw new CertException(e); } catch (IllegalStateException e) { throw new CertException(e); } catch (NoSuchProviderException e) { throw new CertException(e); } catch (NoSuchAlgorithmException e) { throw new CertException(e); } catch (java.security.SignatureException e) { throw new CertException(e); } LOG.debug("Certificate generated for subject: " + cert.getSubjectDN()); return cert; }
From source file:org.objectweb.proactive.core.security.CertTools.java
License:Open Source License
/** * DOCUMENT ME!// w w w.j a v a 2 s .co m * * @param dn DOCUMENT ME! * @param validity DOCUMENT ME! * @param policyId DOCUMENT ME! * @param privKey DOCUMENT ME! * @param pubKey DOCUMENT ME! * @param isCA DOCUMENT ME! * * @return DOCUMENT ME! * * @throws NoSuchAlgorithmException DOCUMENT ME! * @throws SignatureException DOCUMENT ME! * @throws InvalidKeyException DOCUMENT ME! * @throws IllegalStateException * @throws CertificateEncodingException */ public static X509Certificate genSelfCert(String dn, long validity, String policyId, PrivateKey privKey, PublicKey pubKey, boolean isCA) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateEncodingException, IllegalStateException { // Create self signed certificate String sigAlg = "SHA1WithRSA"; Date firstDate = new Date(); // Set back startdate ten minutes to avoid some problems with wrongly set clocks. firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000)); Date lastDate = new Date(); // validity in days = validity*24*60*60*1000 milliseconds lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000))); X509V3CertificateGenerator certgen = new X509V3CertificateGenerator(); // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this // bean is created. byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed((new Date().getTime())); random.nextBytes(serno); certgen.setSerialNumber((new java.math.BigInteger(serno)).abs()); certgen.setNotBefore(firstDate); certgen.setNotAfter(lastDate); certgen.setSignatureAlgorithm(sigAlg); certgen.setSubjectDN(CertTools.stringToBcX509Name(dn)); certgen.setIssuerDN(CertTools.stringToBcX509Name(dn)); certgen.setPublicKey(pubKey); // Basic constranits is always critical and MUST be present at-least in CA-certificates. BasicConstraints bc = new BasicConstraints(isCA); certgen.addExtension(X509Extensions.BasicConstraints.getId(), true, bc); // Put critical KeyUsage in CA-certificates if (isCA == true) { int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign; X509KeyUsage ku = new X509KeyUsage(keyusage); certgen.addExtension(X509Extensions.KeyUsage.getId(), true, ku); } // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Mozilla. try { if (isCA == true) { SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded())) .readObject()); SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded())) .readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); certgen.addExtension(X509Extensions.SubjectKeyIdentifier.getId(), false, ski); certgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), false, aki); } } catch (IOException e) { // do nothing } // CertificatePolicies extension if supplied policy ID, always non-critical if (policyId != null) { PolicyInformation pi = new PolicyInformation(new DERObjectIdentifier(policyId)); DERSequence seq = new DERSequence(pi); certgen.addExtension(X509Extensions.CertificatePolicies.getId(), false, seq); } X509Certificate selfcert = certgen.generate(privKey); return selfcert; }
From source file:org.objectweb.proactive.core.security.CertTools.java
License:Open Source License
public static X509Certificate genCert(String dn, long validity, String policyId, PrivateKey privKey, PublicKey pubKey, boolean isCA, String caDn, PrivateKey caPrivateKey, PublicKey acPubKey) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateEncodingException, IllegalStateException {// ww w. j a v a 2s.c o m // Create self signed certificate String sigAlg = "SHA1WithRSA"; Date firstDate = new Date(); // Set back startdate ten minutes to avoid some problems with wrongly set clocks. firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000)); Date lastDate = new Date(); // validity in days = validity*24*60*60*1000 milliseconds lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000))); X509V3CertificateGenerator certgen = new X509V3CertificateGenerator(); // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this // bean is created. byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed((new Date().getTime())); random.nextBytes(serno); certgen.setSerialNumber((new java.math.BigInteger(serno)).abs()); certgen.setNotBefore(firstDate); certgen.setNotAfter(lastDate); certgen.setSignatureAlgorithm(sigAlg); certgen.setSubjectDN(CertTools.stringToBcX509Name(dn)); certgen.setIssuerDN(CertTools.stringToBcX509Name(caDn)); certgen.setPublicKey(pubKey); // Basic constranits is always critical and MUST be present at-least in CA-certificates. BasicConstraints bc = new BasicConstraints(isCA); certgen.addExtension(X509Extensions.BasicConstraints.getId(), true, bc); // Put critical KeyUsage in CA-certificates if (false) { //if (isCA == true) { int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign; X509KeyUsage ku = new X509KeyUsage(keyusage); certgen.addExtension(X509Extensions.KeyUsage.getId(), true, ku); } // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Mozilla. try { if (false) { //if (isCA == true) { SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded())) .readObject()); SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(acPubKey.getEncoded())) .readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); certgen.addExtension(X509Extensions.SubjectKeyIdentifier.getId(), false, ski); certgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), false, aki); } } catch (IOException e) { // do nothing } // CertificatePolicies extension if supplied policy ID, always non-critical if (policyId != null) { PolicyInformation pi = new PolicyInformation(new DERObjectIdentifier(policyId)); DERSequence seq = new DERSequence(pi); certgen.addExtension(X509Extensions.CertificatePolicies.getId(), false, seq); } X509Certificate cert = certgen.generate(caPrivateKey); return cert; }
From source file:org.opcfoundation.ua.utils.CertificateUtils.java
License:Open Source License
/** * //from w w w. j av a 2s. co m * @param commonName - Common Name (CN) for generated certificate * @param organisation - Organisation (O) for generated certificate * @param applicationUri - Alternative name (one of x509 extensiontype) for generated certificate. Must not be null * @param validityTime - the time that the certificate is valid (in days) * @return * @throws IOException * @throws InvalidKeySpecException * @throws NoSuchAlgorithmException * @throws CertificateEncodingException * @throws InvalidKeyException * @throws IllegalStateException * @throws NoSuchProviderException * @throws SignatureException * @throws CertificateParsingException */ public static org.opcfoundation.ua.transport.security.KeyPair createApplicationInstanceCertificate( String commonName, String organisation, String applicationUri, int validityTime) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException, CertificateEncodingException, InvalidKeyException, IllegalStateException, NoSuchProviderException, SignatureException, CertificateParsingException { if (applicationUri == null) throw new NullPointerException("applicationUri must not be null"); //Add provider for generator Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); //Initializes generator SecureRandom srForCert = new SecureRandom(); RSAKeyPairGenerator genForCert = new RSAKeyPairGenerator(); //Used for generating prime Random r = new Random(System.currentTimeMillis()); int random = -1; while (random < 3) { random = r.nextInt(32); } //calculate(generate) possible value for public modulus //used method is "monte carlo -algorithm", so we calculate it as long as it generates value. BigInteger value = null; while (value == null) { value = BigInteger.probablePrime(random, new SecureRandom()); } //Generate (Java) keypair genForCert.init(new RSAKeyGenerationParameters(value, srForCert, KEY_SIZE, 80)); AsymmetricCipherKeyPair keypairForCert = genForCert.generateKeyPair(); //Extract the keys from parameters logger.debug("Generated keypair, extracting components and creating public structure for certificate"); RSAKeyParameters clientPublicKey = (RSAKeyParameters) keypairForCert.getPublic(); RSAPrivateCrtKeyParameters clientPrivateKey = (RSAPrivateCrtKeyParameters) keypairForCert.getPrivate(); // used to get proper encoding for the certificate RSAPublicKeyStructure clientPkStruct = new RSAPublicKeyStructure(clientPublicKey.getModulus(), clientPublicKey.getExponent()); logger.debug("New public key is '" + makeHexString(clientPkStruct.getEncoded()) + ", exponent=" + clientPublicKey.getExponent() + ", modulus=" + clientPublicKey.getModulus()); // JCE format needed for the certificate - because getEncoded() is necessary... PublicKey certPubKey = KeyFactory.getInstance("RSA") .generatePublic(new RSAPublicKeySpec(clientPublicKey.getModulus(), clientPublicKey.getExponent())); // and this one for the KeyStore PrivateKey certPrivKey = KeyFactory.getInstance("RSA").generatePrivate( new RSAPrivateCrtKeySpec(clientPublicKey.getModulus(), clientPublicKey.getExponent(), clientPrivateKey.getExponent(), clientPrivateKey.getP(), clientPrivateKey.getQ(), clientPrivateKey.getDP(), clientPrivateKey.getDQ(), clientPrivateKey.getQInv())); //The data for the certificate.. Calendar expiryTime = Calendar.getInstance(); expiryTime.add(Calendar.DAY_OF_YEAR, validityTime); X509Name certificateX509Name = new X509Name( "CN=" + commonName + ", O=" + organisation + ", C=" + System.getProperty("user.country")); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); BigInteger serial = BigInteger.valueOf(System.currentTimeMillis()); certGen.setSerialNumber(serial); //Issuer and subject must be the same (because this is self signed) certGen.setIssuerDN(certificateX509Name); certGen.setSubjectDN(certificateX509Name); //expiry & start time for this certificate certGen.setNotBefore(new Date(System.currentTimeMillis() - 1000 * 60 * 60)); //take 60 minutes (1000 ms * 60 s * 60) away from system clock (in case there is some lag in system clocks) certGen.setNotAfter(expiryTime.getTime()); certGen.setPublicKey(certPubKey); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); //******* X.509 V3 Extensions ***************** SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(certPubKey.getEncoded())).readObject()); SubjectKeyIdentifier ski = new SubjectKeyIdentifier(apki); /*certGen.addExtension(X509Extensions.SubjectKeyIdentifier, true, new DEROctetString(ski//new SubjectKeyIdentifier Structure(apki/*certPubKey))); */ certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, ski); certGen.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, /*new DEROctetString(new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation | KeyUsage.dataEncipherment | KeyUsage.keyCertSign ))*/new KeyUsage( KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation | KeyUsage.dataEncipherment | KeyUsage.keyCertSign)); BasicConstraints b = new BasicConstraints(false); Vector<KeyPurposeId> extendedKeyUsages = new Vector<KeyPurposeId>(); extendedKeyUsages.add(KeyPurposeId.id_kp_serverAuth); extendedKeyUsages.add(KeyPurposeId.id_kp_clientAuth); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, /*new DEROctetString(new ExtendedKeyUsage(extendedKeyUsages))*/new ExtendedKeyUsage( extendedKeyUsages)); // create the extension value ASN1EncodableVector names = new ASN1EncodableVector(); names.add(new GeneralName(GeneralName.uniformResourceIdentifier, applicationUri)); // GeneralName dnsName = new GeneralName(GeneralName.dNSName, applicationUri); // names.add(dnsName); final GeneralNames subjectAltNames = new GeneralNames(new DERSequence(names)); certGen.addExtension(X509Extensions.SubjectAlternativeName, true, subjectAltNames); // AuthorityKeyIdentifier final GeneralNames certificateIssuer = new GeneralNames(new GeneralName(certificateX509Name)); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki, certificateIssuer, serial); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, aki); //***** generate certificate ***********/ X509Certificate cert = certGen.generate(certPrivKey, "BC"); //Encapsulate Certificate and private key to CertificateKeyPair Cert certificate = new Cert(cert); org.opcfoundation.ua.transport.security.PrivKey UAkey = new org.opcfoundation.ua.transport.security.PrivKey( (RSAPrivateKey) certPrivKey); return new org.opcfoundation.ua.transport.security.KeyPair(certificate, UAkey); }
From source file:org.opcfoundation.ua.utils.CertificateUtils.java
License:Open Source License
/** * generates new certificate chain and returns it.. * first certificate in the returned chain is the issued certificate and the second one is CA certificate * /*from w w w.ja va2 s . c o m*/ * @return certificates * @throws Exception */ public static X509Certificate[] createCertificateChain() throws Exception { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); // create the keys KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC"); keyGen.initialize(1024, new SecureRandom()); KeyPair pair = keyGen.generateKeyPair(); X509Certificate rootCert = generateRootCertificate(pair); //Create certificate request PKCS10CertificationRequest request = createCertificateRequest(); // validate the certification request if (!request.verify("BC")) { System.out.println("request failed to verify!"); System.exit(1); } // create the certificate using the information in the request X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(rootCert.getSubjectX500Principal()); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(request.getCertificationRequestInfo().getSubject()); certGen.setPublicKey(request.getPublicKey("BC")); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(rootCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(request.getPublicKey("BC"))); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); X509Certificate issuedCert = certGen.generate(pair.getPrivate()); X509Certificate[] chain = { issuedCert, rootCert }; //Write certificates to file so we are able to retrieve the also te private key /* URL certURL = CertificateUtils.class.getResource( "createdCerts.pem" ); URLConnection connection = certURL.openConnection(); InputStream is = connection.getInputStream(); CertificateFactory servercf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) servercf.generateCertificate(is); PEMWriter testWriter = new PEMWriter(new OutputStreamWriter(System.out)); testWriter.writeObject(cert);*/ return chain; }
From source file:org.openmaji.implementation.security.utility.cert.CertUtil.java
License:Open Source License
/** * Creates a lower level certificate, adding authority key-id and subject * key-id extensions to the resulting certificate (version 3). * /* ww w . j a v a 2 s . co m*/ * @param pubKey * @param serialNumber * @param name * @param notBefore * @param notAfter * @param signatureAlgorithm * @param issuerPrivKey * @param issuerCert * @param friendlyName * @return X509Certificate * @throws Exception */ public static X509Certificate createCert(PublicKey pubKey, BigInteger serialNumber, String name, Date notBefore, Date notAfter, String signatureAlgorithm, PrivateKey issuerPrivKey, X509Certificate issuerCert, String friendlyName) throws Exception { byte[] nameBytes = new X500Principal(name).getEncoded(); // // create the certificate - version 3 // v3CertGen.reset(); v3CertGen.setSerialNumber(serialNumber); v3CertGen.setIssuerDN(new X509Principal(issuerCert.getSubjectX500Principal().getEncoded())); v3CertGen.setNotBefore(notBefore); v3CertGen.setNotAfter(notAfter); v3CertGen.setSubjectDN(new X509Principal(nameBytes)); v3CertGen.setPublicKey(pubKey); v3CertGen.setSignatureAlgorithm(signatureAlgorithm); // // add the extensions // v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, createSubjectKeyId(pubKey)); v3CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, createAuthorityKeyId(issuerCert.getPublicKey(), new X509Principal(issuerCert.getSubjectX500Principal().getEncoded()), serialNumber)); v3CertGen.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(false)); v3CertGen.addExtension(MiscObjectIdentifiers.netscapeCertType, false, new NetscapeCertType(NetscapeCertType.sslServer | NetscapeCertType.sslClient | NetscapeCertType.objectSigning | NetscapeCertType.smime)); X509Certificate cert = v3CertGen.generateX509Certificate(issuerPrivKey); if (friendlyName != null) { PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) cert; bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(friendlyName)); bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, createSubjectKeyId(pubKey)); } return cert; }
From source file:org.openmaji.implementation.security.utility.cert.CertUtil.java
License:Open Source License
/** * Generate a certificate which is a "copy" of another certificate, but * resigned by a different issuer./*from www . j a v a 2s.c om*/ * * @param initialCert * @param serialNumber * @param signatureAlgorithm * @param issuerPrivKey * @param issuerCert * @return X509Certificate */ public static X509Certificate resignCert(X509Certificate initialCert, BigInteger serialNumber, String signatureAlgorithm, PrivateKey issuerPrivKey, X509Certificate issuerCert) throws Exception { // // create the certificate - version 3 // v3CertGen.reset(); v3CertGen.setSerialNumber(serialNumber); v3CertGen.setIssuerDN(new X509Principal(issuerCert.getSubjectX500Principal().getEncoded())); v3CertGen.setNotBefore(initialCert.getNotBefore()); v3CertGen.setNotAfter(initialCert.getNotAfter()); v3CertGen.setSubjectDN(new X509Principal(initialCert.getSubjectX500Principal().getEncoded())); v3CertGen.setPublicKey(initialCert.getPublicKey()); v3CertGen.setSignatureAlgorithm(signatureAlgorithm); // // add the extensions // v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, createSubjectKeyId(initialCert.getPublicKey())); v3CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, createAuthorityKeyId(issuerCert.getPublicKey(), new X509Principal(issuerCert.getSubjectX500Principal().getEncoded()), serialNumber)); v3CertGen.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(false)); v3CertGen.addExtension(MiscObjectIdentifiers.netscapeCertType, false, new NetscapeCertType( NetscapeCertType.sslClient | NetscapeCertType.objectSigning | NetscapeCertType.smime)); X509Certificate cert = v3CertGen.generateX509Certificate(issuerPrivKey); return cert; }