List of usage examples for org.bouncycastle.x509 X509V3CertificateGenerator setNotAfter
public void setNotAfter(Date date)
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/*ww w.j a v a 2 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 www .ja v 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 w w . j av a 2s .co 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 www.j av a 2 s . c o m*/ * @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/*www . java 2 s.c o m*/ */ 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//w ww.j a va 2 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// ww w. j ava 2 s .com * @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 {/*from www .j a va 2s. c o 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; } }
From source file:org.jmrtd.test.lds.SODFileTest.java
License:Open Source License
public static SODFile createTestObject() { try {//from ww w . ja v a2s. c o 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); int[] dgPresenceList = { LDSFile.EF_DG1_TAG, LDSFile.EF_DG2_TAG }; COMFile com = new COMFile("1.7", "4.0.0", dgPresenceList); // 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() + "\""); // } // // // 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; } }
From source file:org.kopi.ebics.certificate.X509Generator.java
License:Open Source License
/** * Returns an <code>X509Certificate</code> from a given * <code>KeyPair</code> and limit dates validations * @param keypair the given key pair/*from ww w. j a va 2 s. c o m*/ * @param issuer the certificate issuer * @param notBefore the begin validity date * @param notAfter the end validity date * @param keyusage the certificate key usage * @return the X509 certificate * @throws GeneralSecurityException * @throws IOException */ public X509Certificate generate(KeyPair keypair, String issuer, Date notBefore, Date notAfter, int keyusage) throws GeneralSecurityException, IOException { X509V3CertificateGenerator generator; BigInteger serial; X509Certificate certificate; ASN1EncodableVector vector; serial = BigInteger.valueOf(generateSerial()); generator = new X509V3CertificateGenerator(); generator.setSerialNumber(serial); generator.setIssuerDN(new X509Principal(issuer)); generator.setNotBefore(notBefore); generator.setNotAfter(notAfter); generator.setSubjectDN(new X509Principal(issuer)); generator.setPublicKey(keypair.getPublic()); generator.setSignatureAlgorithm(X509Constants.SIGNATURE_ALGORITHM); generator.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(true)); generator.addExtension(X509Extensions.SubjectKeyIdentifier, false, getSubjectKeyIdentifier(keypair.getPublic())); generator.addExtension(X509Extensions.AuthorityKeyIdentifier, false, getAuthorityKeyIdentifier(keypair.getPublic(), issuer, serial)); vector = new ASN1EncodableVector(); vector.add(KeyPurposeId.id_kp_emailProtection); generator.addExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(new DERSequence(vector))); switch (keyusage) { case X509Constants.SIGNATURE_KEY_USAGE: generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.nonRepudiation)); break; case X509Constants.AUTHENTICATION_KEY_USAGE: generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.digitalSignature)); break; case X509Constants.ENCRYPTION_KEY_USAGE: generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.keyAgreement)); break; default: generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature)); break; } certificate = generator.generate(keypair.getPrivate(), "BC", new SecureRandom()); certificate.checkValidity(new Date()); certificate.verify(keypair.getPublic()); return certificate; }