List of usage examples for org.bouncycastle.x509 X509V3CertificateGenerator setSerialNumber
public void setSerialNumber(BigInteger serialNumber)
From source file:org.guanxi.common.security.SecUtils.java
License:Mozilla Public License
/** * Generates a self signed public/private key pair and puts them and the associated certificate in * a KeyStore./*from w w w . j a v a 2 s . c o m*/ * * @param cn The CN of the X509 containing the public key, e.g. "cn=guanxi_sp,ou=smo,o=uhi" * @param keystoreFile The full path and name of the KeyStore to create or add the certificate to * @param keystorePassword The password for the KeyStore * @param privateKeyPassword The password for the private key associated with the public key certificate * @param privateKeyAlias The alias under which the private key will be stored * @param keyType The type of key, RSA or DSA * @throws GuanxiException if an error occurred */ public void createSelfSignedKeystore(String cn, String keystoreFile, String keystorePassword, String privateKeyPassword, String privateKeyAlias, String keyType) throws GuanxiException { try { KeyStore ks = KeyStore.getInstance("JKS"); // Does the keystore exist? File keyStore = new File(keystoreFile); if (keyStore.exists()) { FileInputStream fis = new FileInputStream(keystoreFile); ks.load(fis, keystorePassword.toCharArray()); fis.close(); } else ks.load(null, null); // Generate a new public/private key pair KeyPairGenerator keyGen = null; if (keyType.toLowerCase().equals("rsa")) { keyGen = KeyPairGenerator.getInstance("RSA"); } else if (keyType.toLowerCase().equals("dsa")) { keyGen = KeyPairGenerator.getInstance("DSA"); } keyGen.initialize(1024, new SecureRandom()); KeyPair keypair = keyGen.generateKeyPair(); PrivateKey privkey = keypair.getPrivate(); PublicKey pubkey = keypair.getPublic(); /* Set the attributes of the X509 Certificate that will contain the public key. * This is a self signed certificate so the issuer and subject will be the same. */ Hashtable<DERObjectIdentifier, String> attrs = new Hashtable<DERObjectIdentifier, String>(); Vector<DERObjectIdentifier> ordering = new Vector<DERObjectIdentifier>(); ordering.add(X509Name.CN); attrs.put(X509Name.CN, cn); X509Name issuerDN = new X509Name(ordering, attrs); X509Name subjectDN = new X509Name(ordering, attrs); // Certificate valid from now Date validFrom = new Date(); validFrom.setTime(validFrom.getTime() - (10 * 60 * 1000)); Date validTo = new Date(); validTo.setTime(validTo.getTime() + (20 * (24 * 60 * 60 * 1000))); // Initialise the X509 Certificate information... X509V3CertificateGenerator x509 = new X509V3CertificateGenerator(); if (keyType.toLowerCase().equals("rsa")) { x509.setSignatureAlgorithm("SHA1withRSA"); } else if (keyType.toLowerCase().equals("dsa")) { x509.setSignatureAlgorithm("SHA1withDSA"); } x509.setIssuerDN(issuerDN); x509.setSubjectDN(subjectDN); x509.setPublicKey(pubkey); x509.setNotBefore(validFrom); x509.setNotAfter(validTo); x509.setSerialNumber(new BigInteger(128, new Random())); // ...generate it... X509Certificate[] cert = new X509Certificate[1]; cert[0] = x509.generate(privkey, "BC"); // ...and add the self signed certificate as the certificate chain java.security.cert.Certificate[] chain = new java.security.cert.Certificate[1]; chain[0] = cert[0]; // Under the alias, store the X509 Certificate and it's public key... ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), cert); // ...and the chain... ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), chain); // ...and write the keystore to disk FileOutputStream fos = new FileOutputStream(keystoreFile); ks.store(fos, keystorePassword.toCharArray()); fos.close(); } catch (Exception se) { /* We'll end up here if a security manager is installed and it refuses us * permission to add the BouncyCastle provider */ throw new GuanxiException(se); } }
From source file:org.guanxi.idp.Bootstrap.java
License:Mozilla Public License
public boolean createSelfSignedKeystore(String cn, String keystoreFile, String keystorePassword, String privateKeyPassword, String privateKeyAlias) { KeyStore ks = null;/* ww w. j a va 2s . c o m*/ try { ks = KeyStore.getInstance("JKS"); ks.load(null, null); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA"); keyGen.initialize(1024, new SecureRandom()); KeyPair keypair = keyGen.generateKeyPair(); PrivateKey privkey = keypair.getPrivate(); PublicKey pubkey = keypair.getPublic(); Hashtable<DERObjectIdentifier, String> attrs = new Hashtable<DERObjectIdentifier, String>(); Vector<DERObjectIdentifier> ordering = new Vector<DERObjectIdentifier>(); ordering.add(X509Name.CN); attrs.put(X509Name.CN, cn); X509Name issuerDN = new X509Name(ordering, attrs); X509Name subjectDN = new X509Name(ordering, attrs); Date validFrom = new Date(); validFrom.setTime(validFrom.getTime() - (10 * 60 * 1000)); Date validTo = new Date(); validTo.setTime(validTo.getTime() + (20 * (24 * 60 * 60 * 1000))); X509V3CertificateGenerator x509 = new X509V3CertificateGenerator(); x509.setSignatureAlgorithm("SHA1withDSA"); x509.setIssuerDN(issuerDN); x509.setSubjectDN(subjectDN); x509.setPublicKey(pubkey); x509.setNotBefore(validFrom); x509.setNotAfter(validTo); x509.setSerialNumber(new BigInteger(128, new Random())); X509Certificate[] cert = new X509Certificate[1]; cert[0] = x509.generate(privkey, "BC"); java.security.cert.Certificate[] chain = new java.security.cert.Certificate[1]; chain[0] = cert[0]; ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), cert); ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), chain); ks.store(new FileOutputStream(keystoreFile), keystorePassword.toCharArray()); String IDP_RFC_CERT = "WEB-INF/guanxi_idp/keystore/guanxi_idp_cert.txt"; PEMWriter pemWriter = new PEMWriter(new FileWriter(servletContext.getRealPath(IDP_RFC_CERT))); pemWriter.writeObject(cert[0]); pemWriter.close(); return true; } catch (Exception se) { return false; } }
From source file:org.guanxi.sp.engine.form.RegisterGuardFormController.java
License:Mozilla Public License
/** * Handles the nitty gritty of signing a CSR * * @param rootCert The certificate of the root authority who will vouch for the entity * @param rootPrivKey The private key of the root authority who will vouch for the entity * @param csr The entitie's CSR//from ww w. j a v a2 s . c o m * @param keyType The type of the key, e.g. "RSA", "DSA" * @return A certificate chain as an array of X509Certificate instances or null if an * error occurred */ private X509Certificate[] createSignedCert(X509Certificate rootCert, PrivateKey rootPrivKey, PKCS10CertificationRequest csr, String keyType) { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); try { Date validFrom = new Date(); validFrom.setTime(validFrom.getTime() - (10 * 60 * 1000)); Date validTo = new Date(); validTo.setTime(validTo.getTime() + (20 * (24 * 60 * 60 * 1000))); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(rootCert.getSubjectX500Principal()); certGen.setNotBefore(validFrom); certGen.setNotAfter(validTo); certGen.setSubjectDN(csr.getCertificationRequestInfo().getSubject()); certGen.setPublicKey(csr.getPublicKey("BC")); if (keyType.toLowerCase().equals("rsa")) certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); if (keyType.toLowerCase().equals("dsa")) certGen.setSignatureAlgorithm("DSAWithSHA1"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(rootCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(csr.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_clientAuth)); X509Certificate issuedCert = certGen.generate(rootPrivKey, "BC"); return new X509Certificate[] { issuedCert, rootCert }; } catch (Exception e) { logger.error(e); return null; } }
From source file:org.intermine.web.security.KeySigner.java
License:GNU General Public License
/** * Create a self-signed X.509 Certificate * * Should be eventually replaced with X509v3CertificateBuilder. * * @param subject Who we trust.//from w ww. j av a 2 s . co m * @param key The key we are asserting that we trust. * @return A certificate wrapping the key, signed by us. * @throws SigningException If we cannot generate the certificate for some reason. */ public X509Certificate generateCertificate(String subject, PublicKey key) throws SigningException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); X509V3CertificateGenerator cert = new X509V3CertificateGenerator(); cert.setSerialNumber(BigInteger.valueOf(1)); //or generate a random number cert.setSubjectDN(new X509Principal("CN=" + subject)); //see examples to add O,OU etc cert.setIssuerDN(new X509Principal(issuer)); //same since it is self-signed cert.setPublicKey(key); cert.setNotBefore(new Date()); cert.setNotAfter(new Date(System.currentTimeMillis() + 1000L * 60L * 60L * 24L * days)); cert.setSignatureAlgorithm(algorithm); try { return cert.generate(signingKey, "BC"); } catch (CertificateEncodingException e) { throw new SigningException(e); } catch (InvalidKeyException e) { throw new SigningException(e); } catch (IllegalStateException e) { throw new SigningException(e); } catch (NoSuchProviderException e) { throw new SigningException(e); } catch (NoSuchAlgorithmException e) { throw new SigningException("Unknown algorithm", e); } catch (SignatureException e) { throw new SigningException(e); } }
From source file:org.jcryptool.visual.jctca.Util.java
License:Open Source License
public static X509Certificate certificateForKeyPair(String principal, String country, String street, String zip, String city, String unit, String organisation, String mail, PublicKey pub, PrivateKey priv, BigInteger serialNumber, X509Certificate caCert, Date expiryDate, Date startDate, PrivateKey caKey) { try {//from w ww .j av a2 s . c o m KeyPair keyPair = new KeyPair(pub, priv); // public/private key pair // that we are creating // certificate for X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); X509Name subjectName = new X509Name("CN=" + principal + ", " + //$NON-NLS-1$ //$NON-NLS-2$ "ST=" + street + ", " + //$NON-NLS-1$ //$NON-NLS-2$ "L=" + zip + " " + city + ", " + "C=" + country + ", " + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ "OU=" + unit + ", " + //$NON-NLS-1$ //$NON-NLS-2$ "O=" + organisation + ", " + //$NON-NLS-1$ //$NON-NLS-2$ "E=" + mail); //$NON-NLS-1$ certGen.setSerialNumber(serialNumber); if (caCert != null) { certGen.setIssuerDN(caCert.getSubjectX500Principal()); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); // FIXME not working any more with BouncyCastle 1.51 // certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure( // keyPair.getPublic())); } else { 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.setNotBefore(startDate); certGen.setNotAfter(expiryDate); certGen.setSubjectDN(subjectName); certGen.setPublicKey(keyPair.getPublic()); certGen.setSignatureAlgorithm("SHA512withRSA");//$NON-NLS-1$ X509Certificate cert; cert = certGen.generate(caKey, "BC");//$NON-NLS-1$ return cert; } catch (CertificateEncodingException e) { LogUtil.logError(e); } catch (InvalidKeyException e) { LogUtil.logError(e); } catch (IllegalStateException e) { LogUtil.logError(e); } catch (NoSuchProviderException e) { LogUtil.logError(e); } catch (NoSuchAlgorithmException e) { LogUtil.logError(e); } catch (SignatureException e) { LogUtil.logError(e); } catch (CertificateParsingException e) { LogUtil.logError(e); } return null; // note: private key of CA }
From source file:org.jcryptool.visual.sigVerification.cert.CertGeneration.java
License:Open Source License
/** * this method creates the x.509 certificate and the needed keypair * @param x - the number value of the certificate (root=1) * @return the generated certificate//from w ww . j a v a 2 s . c om * @throws Exception */ public X509Certificate createCertificate(int x) throws Exception { this.x = x; X509Certificate cert = null; KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(CERTIFICATE_ALGORITHM); keyPairGenerator.initialize(CERTIFICATE_BITS, new SecureRandom()); KeyPair keyPair = keyPairGenerator.generateKeyPair(); // GENERATE THE X509 CERTIFICATE X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); v3CertGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); v3CertGen.setIssuerDN(new X509Principal(CERTIFICATE_DN)); v3CertGen.setNotBefore(now); v3CertGen.setNotAfter(end); v3CertGen.setSubjectDN(new X509Principal(CERTIFICATE_DN)); v3CertGen.setPublicKey(keyPair.getPublic()); v3CertGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); cert = v3CertGen.generateX509Certificate(keyPair.getPrivate()); saveCert(cert, keyPair.getPrivate()); return cert; }
From source file:org.jcryptool.visual.sigVerification.cert.CertGeneration.java
License:Open Source License
/** * this method creates the needed keypair and the x.509 certificate valid till the given date * @param x - the number value of the certificate (root=1) * @param newend - the new not after date * @return the generated certificate/*from ww w . ja va 2 s .c om*/ */ public X509Certificate createCertificateNew(int x, Date newend) throws Exception { this.x = x; X509Certificate cert = null; KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(CERTIFICATE_ALGORITHM); keyPairGenerator.initialize(CERTIFICATE_BITS, new SecureRandom()); KeyPair keyPair = keyPairGenerator.generateKeyPair(); // GENERATE THE X509 CERTIFICATE X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); v3CertGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); v3CertGen.setIssuerDN(new X509Principal(CERTIFICATE_DN)); v3CertGen.setNotBefore(now); v3CertGen.setNotAfter(newend); v3CertGen.setSubjectDN(new X509Principal(CERTIFICATE_DN)); v3CertGen.setPublicKey(keyPair.getPublic()); v3CertGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); cert = v3CertGen.generateX509Certificate(keyPair.getPrivate()); saveCert(cert, keyPair.getPrivate()); return cert; }
From source file:org.jcryptool.visual.ssl.protocol.Crypto.java
License:Open Source License
/** * Generates a default certificate with the given key pair {@link pubKey} * The certificate will be singed with the {@link sigKey} and uses the * {@link strHash} with and the {@link strSignature} algorithm. * * @param key// www.j a va2 s. c o m * @throws CertificateEncodingException * @throws InvalidKeyException * @throws IllegalStateException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws SignatureException */ public X509Certificate generateX509(KeyPair pubKey, KeyPair sigKey, String strHash, String strSignature) throws CertificateEncodingException, InvalidKeyException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException { Calendar notBefore = Calendar.getInstance(); Calendar notAfter = Calendar.getInstance(); notAfter.set(Calendar.YEAR, notBefore.get(Calendar.YEAR) + 1); notAfter.set(Calendar.HOUR, 23); notAfter.set(Calendar.MINUTE, 59); notAfter.set(Calendar.SECOND, 59); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); X500Principal certName = new X500Principal("CN=Test Server Certificate"); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(certName); certGen.setNotAfter(notAfter.getTime()); certGen.setNotBefore(notBefore.getTime()); certGen.setSubjectDN(certName); certGen.setPublicKey(pubKey.getPublic()); certGen.setSignatureAlgorithm(strHash + "With" + strSignature); X509Certificate cert = certGen.generate(sigKey.getPrivate(), "BC"); return cert; }
From source file:org.jivesoftware.util.CertificateManager.java
License:Open Source License
/** * Creates an X509 version3 certificate. * * @param kp KeyPair that keeps the public and private keys for the new certificate. * @param months time to live/*from ww w. j av a 2 s . c o m*/ * @param issuerDN Issuer string e.g "O=Grid,OU=OGSA,CN=ACME" * @param subjectDN Subject string e.g "O=Grid,OU=OGSA,CN=John Doe" * @param domain Domain of the server. * @param signAlgoritm Signature algorithm. This can be either a name or an OID. * @return X509 V3 Certificate * @throws GeneralSecurityException * @throws IOException */ private static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int months, String issuerDN, String subjectDN, String domain, String signAlgoritm) throws GeneralSecurityException, IOException { PublicKey pubKey = kp.getPublic(); PrivateKey privKey = kp.getPrivate(); byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed((new Date().getTime())); random.nextBytes(serno); BigInteger serial = (new java.math.BigInteger(serno)).abs(); X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator(); certGenerator.reset(); certGenerator.setSerialNumber(serial); certGenerator.setIssuerDN(new X509Name(issuerDN)); certGenerator.setNotBefore(new Date(System.currentTimeMillis())); certGenerator.setNotAfter(new Date(System.currentTimeMillis() + months * (1000L * 60 * 60 * 24 * 30))); certGenerator.setSubjectDN(new X509Name(subjectDN)); certGenerator.setPublicKey(pubKey); certGenerator.setSignatureAlgorithm(signAlgoritm); // Generate the subject alternative name boolean critical = subjectDN == null || "".equals(subjectDN.trim()); ASN1Sequence othernameSequence = new DERSequence( new ASN1Encodable[] { new DERObjectIdentifier("1.3.6.1.5.5.7.8.5"), new DERTaggedObject(true, 0, new DERUTF8String(domain)) }); GeneralName othernameGN = new GeneralName(GeneralName.otherName, othernameSequence); GeneralNames subjectAltNames = new GeneralNames(new GeneralName[] { othernameGN }); // Add subject alternative name extension certGenerator.addExtension(X509Extensions.SubjectAlternativeName, critical, subjectAltNames); X509Certificate cert = certGenerator.generateX509Certificate(privKey, "BC", new SecureRandom()); cert.checkValidity(new Date()); cert.verify(pubKey); return cert; }
From source file:org.jmrtd.test.api.lds.SODFileTest.java
License:Open Source License
public static SODFile createTestObject() { try {// w w w. j a va 2 s . co m Security.insertProviderAt(BC_PROVIDER, 4); Date today = Calendar.getInstance().getTime(); DG1File dg1File = DG1FileTest.createTestObject(); byte[] dg1Bytes = dg1File.getEncoded(); DG2File dg2File = DG2FileTest.getDefaultTestObject(); byte[] dg2Bytes = dg2File.getEncoded(); // DG15File dg15File = DG15FileTest.createTestObject(); // byte[] dg15Bytes = dg15File.getEncoded(); KeyPair keyPair = createTestKeyPair(); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); Date dateOfIssuing = today; Date dateOfExpiry = today; String digestAlgorithm = "SHA-256"; String signatureAlgorithm = "SHA256withRSA"; X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator(); certGenerator.setSerialNumber(BigInteger.ONE); certGenerator.setIssuerDN(new X509Name( "C=NL, O=State of the Netherlands, OU=Ministry of the Interior and Kingdom Relations, CN=CSCA NL")); certGenerator.setSubjectDN(new X509Name( "C=NL, O=State of the Netherlands, OU=Ministry of the Interior and Kingdom Relations, CN=DS-01 NL, OID.2.5.4.5=1")); certGenerator.setNotBefore(dateOfIssuing); certGenerator.setNotAfter(dateOfExpiry); certGenerator.setPublicKey(publicKey); certGenerator.setSignatureAlgorithm(signatureAlgorithm); X509Certificate docSigningCert = (X509Certificate) certGenerator.generate(privateKey, BC_PROVIDER_NAME); Map<Integer, byte[]> hashes = new HashMap<Integer, byte[]>(); MessageDigest digest = MessageDigest.getInstance(digestAlgorithm); hashes.put(1, digest.digest(dg1Bytes)); hashes.put(2, digest.digest(dg2Bytes)); // hashes.put(15, digest.digest(dg15Bytes)); // byte[] encryptedDigest = new byte[128]; // Arbitrary value. Use a private key to generate a real signature? SODFile sod = new SODFile(digestAlgorithm, signatureAlgorithm, hashes, privateKey, docSigningCert); File outputDir = new File("tmp"); if (!outputDir.exists()) { if (!outputDir.mkdirs()) { fail("Could not make output dir \"" + outputDir.getAbsolutePath() + "\""); } } if (!outputDir.isDirectory()) { fail("Could not make output dir \"" + outputDir.getAbsolutePath() + "\""); } int[] dgPresenceList = { LDSFile.EF_DG1_TAG, LDSFile.EF_DG2_TAG }; COMFile com = new COMFile("1.7", "4.0.0", dgPresenceList); FileOutputStream comOut = new FileOutputStream(new File(outputDir, "EF_COM.bin")); comOut.write(com.getEncoded()); comOut.flush(); comOut.close(); FileOutputStream dg1Out = new FileOutputStream(new File(outputDir, "DataGroup1.bin")); dg1Out.write(dg1File.getEncoded()); dg1Out.flush(); dg1Out.close(); FileOutputStream dg2Out = new FileOutputStream(new File(outputDir, "DataGroup2.bin")); dg2Out.write(dg2File.getEncoded()); dg2Out.flush(); dg2Out.close(); FileOutputStream sodOut = new FileOutputStream(new File(outputDir, "EF_SOD.bin")); sodOut.write(sod.getEncoded()); sodOut.flush(); sodOut.close(); return sod; } catch (Exception e) { e.printStackTrace(); return null; } }