List of usage examples for org.bouncycastle.x509 X509V3CertificateGenerator setSerialNumber
public void setSerialNumber(BigInteger serialNumber)
From source file:com.vmware.demo.SamlUtils.java
License:Open Source License
/** * Generate a public x509 cert, based on a key. * * @param key KeyPair used to generate public Cert, private key in KeyPair not exposed. * @param issuer If generating an SSL Cert, issuer needs to match hostname * @return/*from w w w .jav a 2 s.c om*/ * @throws SamlException */ public static X509Certificate generateCert(KeyPair key, String issuer) throws SamlException { X509Certificate binCert; try { X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); // create the certificate - version 3 v3CertGen.reset(); v3CertGen.setSerialNumber(BigInteger.valueOf(1)); v3CertGen.setIssuerDN(new X509Principal(issuer)); v3CertGen.setNotBefore(new Date(System.currentTimeMillis())); v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10))); //10 years v3CertGen.setSubjectDN(new X509Principal(issuer)); v3CertGen.setPublicKey(key.getPublic()); v3CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); // add the extensions v3CertGen.addExtension(org.bouncycastle.asn1.x509.X509Extensions.BasicConstraints, false, new BasicConstraints(true)); // generate the actual cert binCert = v3CertGen.generate(key.getPrivate()); // check the cert binCert.checkValidity(new Date()); binCert.verify(key.getPublic()); } catch (Exception e) { throw new SamlException("Failed to generate certificate.", e); } return binCert; }
From source file:cybervillains.ca.CertificateCreator.java
License:Open Source License
/** * Creates a typical Certification Authority (CA) certificate. * //from w w w .j a va 2 s . c o m * @throws SecurityException * @throws InvalidKeyException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws CertificateException */ @SuppressWarnings("deprecation") public static X509Certificate createTypicalMasterCert(final KeyPair keyPair) throws SignatureException, InvalidKeyException, SecurityException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException { X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); X509Principal issuer = new X509Principal( "O=CyberVillians.com,OU=CyberVillians Certification Authority,C=US"); // Create v3CertGen.setSerialNumber(BigInteger.valueOf(1)); v3CertGen.setIssuerDN(issuer); v3CertGen.setSubjectDN(issuer); // Set validity period v3CertGen .setNotBefore(new Date(System.currentTimeMillis() - 12 /* months */ * (1000L * 60 * 60 * 24 * 30))); v3CertGen .setNotAfter(new Date(System.currentTimeMillis() + 240 /* months */ * (1000L * 60 * 60 * 24 * 30))); // Set signature algorithm & public key v3CertGen.setPublicKey(keyPair.getPublic()); v3CertGen.setSignatureAlgorithm(CertificateCreator.SIGN_ALGO); // Add typical extensions for signing cert v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.getPublic())); v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0)); v3CertGen.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.cRLSign | KeyUsage.keyCertSign)); DERSequence typicalCAExtendedKeyUsages = new DERSequence( new ASN1Encodable[] { new DERObjectIdentifier(ExtendedKeyUsageConstants.serverAuth), new DERObjectIdentifier(ExtendedKeyUsageConstants.OCSPSigning), new DERObjectIdentifier(ExtendedKeyUsageConstants.verisignUnknown) }); v3CertGen.addExtension(X509Extensions.ExtendedKeyUsage, false, typicalCAExtendedKeyUsages); X509Certificate cert = v3CertGen.generate(keyPair.getPrivate(), "BC"); cert.checkValidity(new Date()); cert.verify(keyPair.getPublic()); return cert; }
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 a v a2 s .co 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 . java 2 s .c o 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()); }//w ww. j a v a2 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 {//from w w w .j a va 2s .co m 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);//from w w w .jav a2s.c o m 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.//from w w w . j av a 2 s . com */ 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(); ///*from w w w . j av a 2s. c om*/ // 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// ww w .java2s. c o m * @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); } }