List of usage examples for org.bouncycastle.x509 X509V3CertificateGenerator setNotAfter
public void setNotAfter(Date date)
From source file:de.alpharogroup.crypto.factories.CertFactory.java
License:Open Source License
/** * Factory method for creating a new {@link X509Certificate} object from the given parameters. * * @param publicKey/*from w ww .j ava 2s . c o m*/ * the public key * @param privateKey * the private key * @param serialNumber * the serial number * @param subject * the subject * @param issuer * the issuer * @param signatureAlgorithm * the signature algorithm * @param start * the start * @param end * the end * @return the new {@link X509Certificate} object * @throws Exception * is thrown if if a security error occur */ public static X509Certificate newX509Certificate(final PublicKey publicKey, final PrivateKey privateKey, final BigInteger serialNumber, final String subject, final String issuer, final String signatureAlgorithm, final Date start, final Date end) throws Exception { final X500Principal subjectPrincipal = new X500Principal(subject); final X500Principal issuerPrincipal = new X500Principal(issuer); final X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); certificateGenerator.setPublicKey(publicKey); certificateGenerator.setSerialNumber(serialNumber); certificateGenerator.setSubjectDN(subjectPrincipal); certificateGenerator.setIssuerDN(issuerPrincipal); certificateGenerator.setNotBefore(start); certificateGenerator.setNotAfter(end); certificateGenerator.setSignatureAlgorithm(signatureAlgorithm); final X509Certificate certificate = certificateGenerator.generate(privateKey); return certificate; }
From source file:de.mendelson.util.security.keygeneration.KeyGenerator.java
/** * Generates a self-signed X509 Version 3 certificate * *//*from ww w. ja v a 2 s. co m*/ private X509Certificate generateCertificate(PublicKey publicKey, PrivateKey privateKey, KeyGenerationValues generationValues) throws Exception { //Stores certificate attributes Hashtable<ASN1ObjectIdentifier, String> attributes = new Hashtable<ASN1ObjectIdentifier, String>(); Vector<ASN1ObjectIdentifier> order = new Vector<ASN1ObjectIdentifier>(); attributes.put(X509Name.CN, generationValues.getCommonName()); order.add(0, X509Name.CN); attributes.put(X509Name.OU, generationValues.getOrganisationUnit()); order.add(0, X509Name.OU); attributes.put(X509Name.O, generationValues.getOrganisationName()); order.add(0, X509Name.O); attributes.put(X509Name.L, generationValues.getLocalityName()); order.add(0, X509Name.L); attributes.put(X509Name.ST, generationValues.getStateName()); order.add(0, X509Name.ST); attributes.put(X509Name.C, generationValues.getCountryCode()); order.add(0, X509Name.C); attributes.put(X509Name.E, generationValues.getEmailAddress()); order.add(0, X509Name.E); X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); // Set the issuer distinguished name certificateGenerator.setIssuerDN(new X509Principal(order, attributes)); //add a key extension if this is requested if (generationValues.getKeyExtension() != null) { certificateGenerator.addExtension(X509Extensions.KeyUsage, true, generationValues.getKeyExtension()); } //add a extended key extension if this is requested if (generationValues.getExtendedKeyExtension() != null) { certificateGenerator.addExtension(X509Extensions.ExtendedKeyUsage, false, generationValues.getExtendedKeyExtension()); } // Valid before and after dates now to iValidity days in the future Date startDate = new Date(System.currentTimeMillis()); long duration = TimeUnit.DAYS.toMillis(generationValues.getKeyValidInDays()); Date endDate = new Date(startDate.getTime() + duration); certificateGenerator.setNotBefore(startDate); certificateGenerator.setNotAfter(endDate); certificateGenerator.setSubjectDN(new X509Principal(order, attributes)); certificateGenerator.setPublicKey(publicKey); certificateGenerator.setSignatureAlgorithm(generationValues.getSignatureAlgorithm()); BigInteger serialNumber = new BigInteger(Long.toString(System.currentTimeMillis() / 1000)); certificateGenerator.setSerialNumber(serialNumber); // Generate an X.509 certificate, based on the current issuer and subject X509Certificate cert = certificateGenerator.generate(privateKey, "BC"); // Return the certificate return cert; }
From source file:de.perdian.apps.devlauncher.impl.ConnectorListener.java
License:Apache License
private Key ensureKeyInStore(Path keystoreFile, KeyStore keyStore) throws GeneralSecurityException, IOException { Key key = this.lookupKeyFromStore(keyStore); if (key == null) { log.info("Creating new TLS key to enable HTTPS access"); // No key available, so we have to create the key from scratch and // make it available in the store Security.addProvider(new BouncyCastleProvider()); KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024); KeyPair keyPair = keyPairGenerator.generateKeyPair(); X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); v3CertGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); v3CertGen.setIssuerDN(new X509Principal("CN=" + "localhost" + ", OU=None, O=None L=None, C=None")); v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30)); v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10))); v3CertGen.setSubjectDN(new X509Principal("CN=" + "localhost" + ", OU=None, O=None L=None, C=None")); v3CertGen.setPublicKey(keyPair.getPublic()); v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption"); X509Certificate certificate = v3CertGen.generateX509Certificate(keyPair.getPrivate()); // Store the key (including the certificate) into the keystore keyStore.setKeyEntry(TLS_KEY_NAME, keyPair.getPrivate(), TLS_KEY_PASSWORD.toCharArray(), new java.security.cert.Certificate[] { certificate }); // Write the keystore into the target file log.debug("Updating KeyStore at: " + keystoreFile); if (!Files.exists(keystoreFile.getParent())) { Files.createDirectories(keystoreFile.getParent()); }/*from w w w . j a v a 2 s. co m*/ try (OutputStream keyStoreStream = new BufferedOutputStream(Files.newOutputStream(keystoreFile))) { keyStore.store(keyStoreStream, KEYSTORE_PASSWORD.toCharArray()); keyStoreStream.flush(); } } return key; }
From source file:de.rub.nds.burp.utilities.attacks.signatureFaking.helper.CertificateHandler.java
License:Open Source License
public void createFakedCertificate() throws CertificateHandlerException { try {// w ww. j av a 2 s. com Logging.getInstance().log(getClass(), "Faking the found certificate", Logging.DEBUG); KeyPairGenerator kpg = KeyPairGenerator.getInstance(originalPublicKey.getAlgorithm()); kpg.initialize(((RSAPublicKey) certificate.getPublicKey()).getModulus().bitLength()); fakedKeyPair = kpg.generateKeyPair(); X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); v3CertGen.setSubjectDN(certificate.getSubjectX500Principal()); v3CertGen.setIssuerDN(certificate.getIssuerX500Principal()); v3CertGen.setNotAfter(certificate.getNotAfter()); v3CertGen.setNotBefore(certificate.getNotBefore()); v3CertGen.setSerialNumber(new BigInteger(64, new Random())); v3CertGen.setSignatureAlgorithm(certificate.getSigAlgName()); v3CertGen.setPublicKey(fakedKeyPair.getPublic()); fakedCertificate = v3CertGen.generate(fakedKeyPair.getPrivate()); } catch (CertificateEncodingException | SecurityException | SignatureException | InvalidKeyException | NoSuchAlgorithmException e) { throw new CertificateHandlerException(e); } }
From source file:edu.ucsb.eucalyptus.keys.KeyTool.java
License:Open Source License
public X509Certificate getCertificate(KeyPair keyPair, String certDn) { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); X500Principal dnName = new X500Principal(certDn); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(dnName);/* w ww . j a va 2 s . c om*/ certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); Calendar cal = Calendar.getInstance(); certGen.setNotBefore(cal.getTime()); cal.add(Calendar.YEAR, 5); certGen.setNotAfter(cal.getTime()); certGen.setSubjectDN(dnName); certGen.setPublicKey(keyPair.getPublic()); certGen.setSignatureAlgorithm(this.keySigningAlgorithm); try { X509Certificate cert = certGen.generate(keyPair.getPrivate(), PROVIDER); return cert; } catch (Exception e) { LOG.fatal(e, e); System.exit(1); return null; } }
From source file:fabric.common.Crypto.java
License:Open Source License
/** * Generates a certificate, signed by the issuer, binding the subject's name * to their public key.// www . java 2s.c o m */ public static X509Certificate createCertificate(String subjectName, PublicKey subjectKey, String issuerName, PrivateKey issuerKey) throws GeneralSecurityException { Calendar expiry = Calendar.getInstance(); expiry.add(Calendar.YEAR, 1); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(new X509Name("CN=" + issuerName)); certGen.setSubjectDN(new X509Name("CN=" + subjectName)); certGen.setSignatureAlgorithm("SHA1withRSA"); certGen.setPublicKey(subjectKey); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(expiry.getTime()); return certGen.generate(issuerKey); }
From source file:gov.nih.nci.firebird.service.signing.DigitalSigningHelper.java
License:Open Source License
private X509V3CertificateGenerator buildX509V3CertificateGenerator(PublicKey publicKey, X509Certificate caCert, DigitalSigningDistinguishedName distinguishedName, long serialNumber, int validDays) throws CertificateEncodingException, CertificateParsingException { X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); // Calculate Expiration Date Calendar notBeforeCal = Calendar.getInstance(); Date notBeforeDate = notBeforeCal.getTime(); Calendar notAfterCal = Calendar.getInstance(); notAfterCal.add(Calendar.DAY_OF_YEAR, validDays); Date notAfterDate = notAfterCal.getTime(); //// w w w . jav a2 s. com // create the certificate - version 3 // v3CertGen.reset(); v3CertGen.setSerialNumber(BigInteger.valueOf(serialNumber)); v3CertGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(caCert)); v3CertGen.setNotBefore(notBeforeDate); v3CertGen.setNotAfter(notAfterDate); v3CertGen.setSubjectDN(new X509Principal(getAttributeOrder(), buildAttributes(distinguishedName))); v3CertGen.setPublicKey(publicKey); v3CertGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); // // extensions // v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(publicKey)); v3CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0)); return v3CertGen; }
From source file:hu.akarnokd.utils.crypto.KeystoreManager.java
License:Apache License
/** * Generate a X509 certificate for the given keypair. * The distinguished names must be in format: CN=cName, OU=orgUnit, O=org, L=city, S=state, C=countryCode * use backslash to escape a comma/*from w w w .j a v a 2 s . com*/ * @param keypair the keypair * @param months the validity length in months * @param issuerDN the issuer distinguished name: "CN=David Karnok,OU=EMI,O=MTA SZTAKI" * @param subjectDN the subject distinguished name: "CN=David Karnok,OU=EMI,O=MTA SZTAKI" * @param domain domain of the server to store in the subject alternative name extension * @param signAlgorithm the signing algorithm to use * @return the generated X509 certificate */ public X509Certificate createX509Certificate(KeyPair keypair, int months, String issuerDN, String subjectDN, String domain, String signAlgorithm) { try { // calendar for date calculations GregorianCalendar cal = new GregorianCalendar(); // extract keypair components PublicKey pubKey = keypair.getPublic(); PrivateKey privKey = keypair.getPrivate(); // generate a random serial number SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(System.currentTimeMillis()); byte[] serialNo = new byte[8]; random.nextBytes(serialNo); BigInteger serial = new BigInteger(serialNo).abs(); // create the certificate generator X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.reset(); // set certificate attributes certGen.setSerialNumber(serial); cal.setTimeInMillis(System.currentTimeMillis()); certGen.setNotBefore(cal.getTime()); cal.add(GregorianCalendar.MONTH, months); certGen.setNotAfter(cal.getTime()); certGen.setPublicKey(pubKey); certGen.setSignatureAlgorithm(signAlgorithm); certGen.setIssuerDN(new X509Name(issuerDN)); certGen.setSubjectDN(new X509Name(subjectDN)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey)); // create subject alternative name boolean isCritical = subjectDN == null || "".equals(subjectDN.trim()); DERSequence othernameSeq = new DERSequence( new ASN1Encodable[] { new DERObjectIdentifier("1.3.6.1.5.5.7.8.5"), new DERTaggedObject(true, 0, new DERUTF8String(domain)) }); GeneralName othernameGen = new GeneralName(GeneralName.otherName, othernameSeq); GeneralNames subjectAlternatives = new GeneralNames(othernameGen); certGen.addExtension(X509Extensions.SubjectAlternativeName, isCritical, subjectAlternatives); // finally generate the certificate X509Certificate cert = certGen.generateX509Certificate(privKey, BC_PROVIDER.getName(), new SecureRandom()); cert.checkValidity(new Date()); cert.verify(pubKey); return cert; } catch (NoSuchAlgorithmException ex) { throw new KeystoreFault(ex); } catch (CertificateException ex) { throw new KeystoreFault(ex); } catch (SignatureException ex) { throw new KeystoreFault(ex); } catch (NoSuchProviderException ex) { throw new KeystoreFault(ex); } catch (InvalidKeyException ex) { throw new KeystoreFault(ex); } }
From source file:io.aos.crypto.spl06.PKCS10CertCreateExample.java
License:Apache License
public static X509Certificate[] buildChain() throws Exception { // create the certification request KeyPair pair = Utils.generateRSAKeyPair(); PKCS10CertificationRequest request = PKCS10ExtensionExample.generateRequest(pair); // create a root certificate KeyPair rootPair = Utils.generateRSAKeyPair(); X509Certificate rootCert = X509V1CreateExample.generateV1Certificate(rootPair); // validate the certification request if (!request.verify("BC")) { System.out.println("request failed to verify!"); System.exit(1);//from w ww . ja v a 2 s . c om } // 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)); // extract the extension request attribute ASN1Set attributes = request.getCertificationRequestInfo().getAttributes(); for (int i = 0; i != attributes.size(); i++) { Attribute attr = Attribute.getInstance(attributes.getObjectAt(i)); // process extension request if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0)); 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()); } } } X509Certificate issuedCert = certGen.generateX509Certificate(rootPair.getPrivate()); return new X509Certificate[] { issuedCert, rootCert }; }
From source file:io.aos.crypto.spl06.X509V3CreateExample.java
License:Apache License
public static X509Certificate generateV3Certificate(KeyPair pair) throws InvalidKeyException, NoSuchProviderException, SignatureException { // generate the certificate X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(new X500Principal("CN=Test Certificate")); certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X500Principal("CN=Test Certificate")); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); 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)); certGen.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test"))); return certGen.generateX509Certificate(pair.getPrivate(), "BC"); }