List of usage examples for org.bouncycastle.x509 X509V3CertificateGenerator generate
public X509Certificate generate(PrivateKey key) throws CertificateEncodingException, IllegalStateException, NoSuchAlgorithmException, SignatureException, InvalidKeyException
From source file:at.tugraz.ist.akm.keystore.ApplicationKeyStore.java
License:Apache License
private void createNewCertificate() throws InvalidKeyException, SecurityException, SignatureException, NoSuchAlgorithmException, CertificateEncodingException, IllegalStateException, NoSuchProviderException { Security.addProvider(new BouncyCastleProvider()); X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator(); certGenerator.setSerialNumber(BigInteger.valueOf(Math.abs(mRandom.nextInt() + 1))); certGenerator.setIssuerDN(new X500Principal(CertificateDefaultAttributes.ISSUER)); certGenerator.setSubjectDN(new X500Principal(CertificateDefaultAttributes.SUBJECT)); certGenerator.setNotBefore(new Date( System.currentTimeMillis() - CertificateDefaultAttributes.VALID_DURATION_BEFORE_NOW_MILLISECONDS)); certGenerator.setNotAfter(new Date( System.currentTimeMillis() + CertificateDefaultAttributes.VALID_DURATION_FROM_NOW_MILLISECONDS)); KeyPairGenerator keyGenerator = KeyPairGenerator .getInstance(CertificateDefaultAttributes.KEYPAIR_GENERATOR); keyGenerator.initialize(CertificateDefaultAttributes.KEYPAIR_LENGTH_BITS); KeyPair newKeyPair = keyGenerator.generateKeyPair(); certGenerator.setPublicKey(newKeyPair.getPublic()); certGenerator.setSignatureAlgorithm(CertificateDefaultAttributes.ENCRYPTION_ALGORITHM); X509Certificate newCertificate = certGenerator.generate(newKeyPair.getPrivate()); mCertificate = newCertificate;/* w w w. j a v a 2s . com*/ mKeyPair = newKeyPair; }
From source file:com.nokia.tools.vct.internal.common.secure.core.KeyStoreManager.java
License:Open Source License
public X509Certificate createCertificate(KeyPair keys, int years, Map<String, String> fields) throws CoreException { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setNotBefore(new GregorianCalendar(Locale.getDefault()).getTime()); GregorianCalendar gregorianCalendar = new GregorianCalendar(); gregorianCalendar.add(Calendar.YEAR, 1); certGen.setNotAfter(gregorianCalendar.getTime()); certGen.setPublicKey(keys.getPublic()); StringBuffer userInformation = new StringBuffer(); UUID uuid = UUID.randomUUID(); ByteBuffer bb = ByteBuffer.allocate(17); bb.put((byte) 0); bb.putLong(uuid.getMostSignificantBits()); bb.putLong(uuid.getLeastSignificantBits()); BigInteger bigInteger = new BigInteger(bb.array()); userInformation.append("SERIALNUMBER=").append(bigInteger.toString()); for (Map.Entry<String, String> field : fields.entrySet()) { userInformation.append(','); userInformation.append(field.getKey()); userInformation.append('='); userInformation.append(escapeRFC2253(field.getValue())); }/*from w w w .j a v a2s .co m*/ X500Principal principal = new X500Principal(userInformation.toString()); certGen.setIssuerDN(principal); certGen.setSubjectDN(principal); certGen.setSignatureAlgorithm(SIGNATURE_SHA1_RSA); X509Certificate certificate; try { certificate = certGen.generate(keys.getPrivate()); } catch (Exception ex) { IStatus status = new Status(IStatus.ERROR, SecurityCorePlugin.PLUGIN_ID, "Failed to generate certificate", ex); SecurityCorePlugin.getDefault().getLog().log(status); throw new CoreException(status); } return certificate; }
From source file:com.streamreduce.util.CAGenerator.java
License:Apache License
public static X509Certificate generateCACert(KeyPair keyPair) throws Exception { Date startDate = new Date(System.currentTimeMillis()); // time from which certificate is valid Calendar expiry = Calendar.getInstance(); expiry.add(Calendar.DAY_OF_YEAR, 1000 * 365); Date expiryDate = expiry.getTime(); // time after which certificate is not valid BigInteger serialNumber = new BigInteger(Long.toString(System.currentTimeMillis())); // serial number for certificate X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); X500Principal dnName = new X500Principal("CN=Nodeable Client"); certGen.setSerialNumber(serialNumber); certGen.setIssuerDN(dnName);//ww w . j a v a 2 s . c o m certGen.setNotBefore(startDate); certGen.setNotAfter(expiryDate); certGen.setSubjectDN(dnName); certGen.setPublicKey(keyPair.getPublic()); certGen.setSignatureAlgorithm("MD5withRSA"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(keyPair.getPublic())); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.getPublic())); return certGen.generate(keyPair.getPrivate()); // note: private key of CA }
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 ww . ja v a 2s.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: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/* w w w. j a v a 2 s. c om*/ * 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.rub.nds.burp.utilities.attacks.signatureFaking.helper.CertificateHandler.java
License:Open Source License
public void createFakedCertificate() throws CertificateHandlerException { try {// www . j a v a 2 s . 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:fabric.common.Crypto.java
License:Open Source License
/** * Generates a certificate, signed by the issuer, binding the subject's name * to their public key.//w ww. j av a 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:net.java.bd.tools.security.OnlineKeytool.java
License:Open Source License
/** * Creates a self signed certificate using the public key * from the "online.crt" file. See BD-ROM specification part 3.2, * version 2.2 Annex DD./* ww w . ja v a2 s . com*/ * The certificate fields other than the key pair do not matter. * The certificate is just a place holder in the keystore. * The private key is created from the BDA binary file. * <p> * @throws java.lang.Exception */ public void createSelfSignedCert() throws Exception { DataInputStream dis = new DataInputStream(new FileInputStream(crtFile)); String typeIndicator = SecurityUtil.readISO646String(dis, 4); if (!typeIndicator.equals("OCRT")) { throw new RuntimeException("Invalid TypeIndicator: " + typeIndicator + " in " + crtFile); } String versionNo = SecurityUtil.readISO646String(dis, 4); if (!versionNo.equals("0200")) { throw new RuntimeException("Invalid Version No:" + versionNo + " in " + crtFile); } // reserved bytes dis.skipBytes(32); int certVerNo = dis.readInt(); if (certVerNo != 0) { throw new RuntimeException("Invalid Certificate Version No:" + certVerNo); } int contentOwnerId = dis.readInt(); if (debug) { System.out.println("Content owner ID:" + contentOwnerId); } // reserved bytes dis.skipBytes(32); String contentOwnerName = SecurityUtil.readISO646String(dis, 256); if (debug) { System.out.println("Content owner Name:" + contentOwnerName); } String dn = "cn=" + contentOwnerName; // used in cert // read the public key modulus 'n' byte[] buf = new byte[256]; int read = dis.read(buf); if (read == -1) { throw new IOException("Reached end of file before finished reading the file:" + crtFile); } BigInteger modulus = new BigInteger(1, buf); /*HexDumpEncoder hexDump = null; if (debug) { System.out.println("public modulus:"); hexDump = new HexDumpEncoder(); System.out.println(hexDump.encodeBuffer(modulus.toByteArray())); }*/ BigInteger exponent = BigInteger.valueOf(65537); RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent); KeyFactory factory = KeyFactory.getInstance("RSA"); PublicKey publicKey = factory.generatePublic(spec); // create a self signed cert for importing into the keystore. X509V3CertificateGenerator cg = new X509V3CertificateGenerator(); cg.reset(); Calendar calendar = Calendar.getInstance(); calendar.set(0000, 1, 1); Date validFrom = calendar.getTime(); calendar.clear(); calendar.set(9999, 1, 1); Date validTo = calendar.getTime(); cg.setNotBefore(validFrom); cg.setNotAfter(validTo); cg.setPublicKey(publicKey); cg.setSignatureAlgorithm("SHA1WITHRSA"); cg.setSubjectDN(new X509Name(dn)); cg.setIssuerDN(new X509Name(dn)); SecureRandom prng = SecureRandom.getInstance("SHA1PRNG"); BigInteger serNo = new BigInteger(32, prng); cg.setSerialNumber(serNo); this.cert = cg.generate(this.privateKey); // read the BDA signature; not currently used //int read = dis.read(buf); //if (read == -1) { // throw new IOException("Reached end of file before finished reading the file:" + // crtFile); //} dis.close(); }
From source file:net.java.bd.tools.security.SecurityUtil.java
License:Open Source License
private void generateSelfSignedCertificate(String issuer, String alias, String keyPassword, boolean isRootCert) throws Exception { Date validFrom, validTo;/*w ww .ja v a2 s .co m*/ // For forcing GeneralizedTime DER encoding, with Bouncy Castle Provider // make the range before 1950 and after 2050. The BD-J spec recommends // using the default validity period used below Calendar calendar = Calendar.getInstance(); calendar.set(0000, 1, 1); validFrom = calendar.getTime(); calendar.clear(); calendar.set(9999, 1, 1); validTo = calendar.getTime(); // Generate a new keypair for this certificate KeyPair keyPair = generateKeyPair(); X509V3CertificateGenerator cg = new X509V3CertificateGenerator(); cg.reset(); X509Name name = new X509Name(issuer, new X509BDJEntryConverter()); // Generate Serial Number SecureRandom prng = SecureRandom.getInstance("SHA1PRNG"); BigInteger serNo = new BigInteger(32, prng); cg.setSerialNumber(serNo); if (!isRootCert) { appCertSerNo = serNo; } cg.setIssuerDN(name); cg.setNotBefore(validFrom); cg.setNotAfter(validTo); cg.setSubjectDN(name); cg.setPublicKey(keyPair.getPublic()); cg.setSignatureAlgorithm("SHA1WITHRSA"); if (isRootCert) { // Need to add root cert extensions. if (isBindingUnitCert) { // This certificate is used only for signing cg.addExtension(X509Extensions.KeyUsage.getId(), true, new X509KeyUsage(X509KeyUsage.digitalSignature)); } else { int usage = X509KeyUsage.digitalSignature + X509KeyUsage.keyCertSign; cg.addExtension(X509Extensions.KeyUsage.getId(), true, new X509KeyUsage(usage)); } cg.addExtension(X509Extensions.IssuerAlternativeName.getId(), false, getRfc822Name(altName)); cg.addExtension(X509Extensions.BasicConstraints.getId(), true, new BasicConstraints(true)); } // For an app cert, most of the extensions will be added when generating // a certificate in response to the certificate request file. cg.addExtension(X509Extensions.SubjectAlternativeName.getId(), false, getRfc822Name(altName)); Certificate cert = cg.generate(keyPair.getPrivate()); store.setKeyEntry(alias, keyPair.getPrivate(), keyPassword.toCharArray(), new Certificate[] { cert }); FileOutputStream fos = new FileOutputStream(keystoreFile); store.store(fos, keystorePassword.toCharArray()); fos.close(); }
From source file:net.java.bd.tools.security.SecurityUtil.java
License:Open Source License
void issueCert(String csrfile, String certfile, String alias, String keypass) throws Exception { PKCS10CertificationRequest csr = new PKCS10CertificationRequest(convertFromBASE64(csrfile)); String subject = csr.getCertificationRequestInfo().getSubject().toString(); // Generate the app certificate X509V3CertificateGenerator cg = new X509V3CertificateGenerator(); cg.reset();//from ww w.j av a2s.co m X509Certificate rootCert = (X509Certificate) store.getCertificate(alias); if (rootCert == null) { System.out .println("ERROR: Aborting application certificate creation." + " No root certificate to sign."); cleanup(); // removes the self signed certificate from the keystore System.exit(1); } cg.setIssuerDN(new X509Name(true, rootCert.getSubjectDN().getName(), new X509BDJEntryConverter())); cg.setSubjectDN(new X509Name(subject, new X509BDJEntryConverter())); cg.setNotBefore(rootCert.getNotBefore()); cg.setNotAfter(rootCert.getNotAfter()); cg.setPublicKey(csr.getPublicKey()); cg.setSerialNumber(appCertSerNo); // BD-J mandates using SHA1WithRSA as a signature Algorithm cg.setSignatureAlgorithm("SHA1WITHRSA"); cg.addExtension(X509Extensions.KeyUsage.getId(), true, new X509KeyUsage(X509KeyUsage.digitalSignature)); // FIXME: Ideally this should be pulled out from the original app cert's // extension. Email on X500Name is not encoded with UTF8String. cg.addExtension(X509Extensions.SubjectAlternativeName.getId(), false, getRfc822Name(altName)); // Assuming that the root certificate was generated using our tool, // the certificate should have IssuerAlternativeNames as an extension. if (rootCert.getIssuerAlternativeNames() == null) { System.out.println("ERROR: the root certificate must have an alternate name"); System.exit(1); } List issuerName = (List) rootCert.getIssuerAlternativeNames().iterator().next(); cg.addExtension(X509Extensions.IssuerAlternativeName.getId(), false, getRfc822Name((String) issuerName.get(1))); PrivateKey privateKey = (PrivateKey) store.getKey(alias, keypass.toCharArray()); X509Certificate cert = cg.generate(privateKey); // Now, write leaf certificate System.out.println("Writing cert to " + certfile + "."); FileOutputStream str = new FileOutputStream(certfile); str.write(cert.getEncoded()); str.close(); }