List of usage examples for org.bouncycastle.asn1.x509 KeyPurposeId id_kp_serverAuth
KeyPurposeId id_kp_serverAuth
To view the source code for org.bouncycastle.asn1.x509 KeyPurposeId id_kp_serverAuth.
Click Source Link
From source file:at.ac.tuwien.ifs.tita.business.security.TiTASecurity.java
License:Apache License
/** * Generates a fresh Certificate for a Users KeyPair. * //from w w w . ja v a 2s . c om * @param pair the KeyPair to create a Certificate for. * @param userName the Issuer of the Certificate * @return a 10 Year valid Certificate for the User. * @throws TiTASecurityException If an error occurs during the generation Process. */ private static X509Certificate generateV3Certificate(KeyPair pair, String userName) throws TiTASecurityException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(new X500Principal("CN=" + userName + " Certificate")); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + VALID_TIME_RANGE)); certGen.setSubjectDN(new X500Principal("CN=" + userName + " 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)); X509Certificate targetCertificate = null; try { targetCertificate = certGen.generate(pair.getPrivate(), "BC"); } catch (NoSuchProviderException e) { log.error("Could create a certificate for: " + userName + "."); throw new TiTASecurityException("Error while Generating a Certificate for: " + userName + ". Specified provider was not found.\n" + e.getMessage()); } catch (NoSuchAlgorithmException e) { log.error("Could create a certificate for: " + userName + "."); throw new TiTASecurityException("Error while Generating a Certificate for: " + userName + ". Specified algorithm was not found.\n" + e.getMessage()); } catch (SignatureException e) { log.error("Could create a certificate for: " + userName + "."); throw new TiTASecurityException("Error while Generating a Certificate for: " + userName + ". Signature is not valid.\n" + e.getMessage()); } catch (CertificateEncodingException e) { log.error("Could create a certificate for: " + userName + "."); throw new TiTASecurityException("Error while Generating a Certificate for: " + userName + ". Wrong encoding for Signature.\n" + e.getMessage()); } catch (InvalidKeyException e) { log.error("Could create a certificate for: " + userName + "."); throw new TiTASecurityException("Error while Generating a Certificate for: " + userName + ". The Key is not valid.\n" + e.getMessage()); } return targetCertificate; }
From source file:chapter6.PKCS10CertCreateExample.java
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") == false) { System.out.println("Request failed to verify!!"); System.exit(1);//from w ww .j av a2 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(new X500Principal(request.getCertificationRequestInfo().getSubject().getEncoded())); 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:chapter6.X509V3CreateExample.java
public static X509Certificate generateV3Certificate(KeyPair pair) throws Exception { 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"); // Extension ::= SEQUENCE { // extnID OBJECT IDENTIFIER, // critical BOOLEAN DEFAULT FALSE // extnValue OCTET STRING } 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(), CryptoDefs.Provider.BC.getName()); }
From source file:com.difference.historybook.server.CertManager.java
License:Apache License
/** * Create a self-signed certificate and store in a keystore (if it doesn't already exist) * /*from w w w. j a va 2 s. c om*/ * @param keystore path to the keystore to save to * @param password password to use to encrypt keystore * @param alias name to give the certificate in the keystore * @param x500String X500 name for the certificate. (e.g. "CN=localhost,OU=issuer) * @param duration length of time a newly created certificate should remain valid (in seconds) * * @throws @RuntimeException if an error occurs in creating the certificate */ public static void initialize(Path keystore, String password, String alias, String commonName, String organization, long duration) { if (keystore.toFile().exists()) { LOG.info("Keystore {} found.", keystore); return; } try { Security.addProvider(new BouncyCastleProvider()); // generate a key pair KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", PROVIDER_NAME); keyPairGenerator.initialize(KEY_LENGTH, new SecureRandom()); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PublicKey pubKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); // build name X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE); nameBuilder.addRDN(BCStyle.CN, commonName); nameBuilder.addRDN(BCStyle.O, organization); nameBuilder.addRDN(BCStyle.OU, organization); X500Name issuerName = nameBuilder.build(); X500Name subjectName = issuerName; // build serial BigInteger serial = BigInteger.valueOf(new Random().nextInt()); // build a certificate generator X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuerName, serial, new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000), // yesterday new Date(System.currentTimeMillis() + duration * 1000), subjectName, pubKey); KeyUsage usage = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment); certBuilder.addExtension(Extension.keyUsage, true, usage); ASN1EncodableVector purposes = new ASN1EncodableVector(); purposes.add(KeyPurposeId.id_kp_serverAuth); certBuilder.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes)); X509Certificate[] chain = new X509Certificate[1]; chain[0] = signCertificate(certBuilder, keyPair.getPrivate()); KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null, null); keyStore.setKeyEntry(alias, privateKey, password.toCharArray(), chain); keyStore.store(new FileOutputStream(keystore.toFile()), password.toCharArray()); Files.setPosixFilePermissions(keystore, ImmutableSet.of(PosixFilePermission.OWNER_READ)); LOG.info("Created keystore at {}.", keystore); } catch (NoSuchAlgorithmException | NoSuchProviderException | CertificateException | KeyStoreException | IOException | OperatorCreationException e) { LOG.error(e.getLocalizedMessage()); throw new RuntimeException(e); } }
From source file:com.enioka.jqm.pki.CertificateRequest.java
License:Open Source License
public void generateCA(String prettyName) { this.prettyName = prettyName; Subject = "CN=JQM-CA,OU=ServerProducts,O=Oxymores,C=FR"; size = 4096;//from w w w . ja va 2 s . c om EKU = new KeyPurposeId[4]; EKU[0] = KeyPurposeId.id_kp_codeSigning; EKU[1] = KeyPurposeId.id_kp_serverAuth; EKU[2] = KeyPurposeId.id_kp_clientAuth; EKU[3] = KeyPurposeId.id_kp_emailProtection; keyUsage = KeyUsage.cRLSign | KeyUsage.keyCertSign; generateAll(); }
From source file:com.enioka.jqm.pki.CertificateRequest.java
License:Open Source License
public void generateServerCert(String prettyName, X509CertificateHolder authority, PrivateKey issuerPrivateKey, String subject) {/*from w w w .ja va 2s . co m*/ this.prettyName = prettyName; authorityCertificate = authority; authorityKey = issuerPrivateKey; this.Subject = subject; size = 2048; EKU = new KeyPurposeId[1]; EKU[0] = KeyPurposeId.id_kp_serverAuth; keyUsage = KeyUsage.digitalSignature | KeyUsage.keyEncipherment; generateAll(); }
From source file:com.example.androidtest.SslUtil.java
License:Open Source License
/** * Generates a new, self-signed X509 V3 certificate for a KeyPair. * /*from w ww . j a v a2 s . c o m*/ * @param pair the {@link KeyPair} to be used * @param name X.500 distinguished name * @param notBefore not valid before this date * @param notAfter not valid after this date * @param serialNumber serial number * @return the new certificate * @throws GeneralSecurityException on error generating the certificate */ @SuppressWarnings("deprecation") public static X509Certificate generateX509V3Certificate(KeyPair pair, String name, Date notBefore, Date notAfter, BigInteger serialNumber) throws GeneralSecurityException { java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); X509Name dnName = new X509Name(name); certGen.setSerialNumber(serialNumber); certGen.setIssuerDN(dnName); certGen.setSubjectDN(dnName); // note: same as issuer certGen.setNotBefore(notBefore); certGen.setNotAfter(notAfter); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); // For self-signed certificates, OpenSSL 0.9.6 has specific requirements // about certificate and extension content. Quoting the `man verify`: // // In OpenSSL 0.9.6 and later all certificates whose subject name matches // the issuer name of the current certificate are subject to further // tests. The relevant authority key identifier components of the current // certificate (if present) must match the subject key identifier (if // present) and issuer and serial number of the candidate issuer, in // addition the keyUsage extension of the candidate issuer (if present) // must permit certificate signing. // // In the code that follows, // - the KeyUsage extension permits cert signing (KeyUsage.keyCertSign); // - the Authority Key Identifier extension is added, matching the // subject key identifier, and using the issuer, and serial number. certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.keyCertSign)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); AuthorityKeyIdentifier authIdentifier = createAuthorityKeyIdentifier(pair.getPublic(), dnName, serialNumber); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, true, authIdentifier); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, true, new SubjectKeyIdentifierStructure(pair.getPublic())); certGen.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "googletv@test.test"))); // This method is deprecated, but Android Eclair does not provide the // generate() methods. X509Certificate cert = certGen.generateX509Certificate(pair.getPrivate(), "BC"); return cert; }
From source file:com.intirix.cloudpasswordmanager.services.ssl.CertPinningServiceImplUnitSpec.java
License:Apache License
public static X509Certificate generateV3Certificate(KeyPair pair) throws InvalidKeyException, NoSuchProviderException, SignatureException { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(new X500Principal("CN=Test Certificate")); certGen.setNotBefore(new Date(System.currentTimeMillis() - 10000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 10000)); 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"); }
From source file:com.peterphi.std.crypto.keygen.CaHelper.java
License:Open Source License
static private X509V3CertificateGenerator addCaExtensions(X509V3CertificateGenerator gen, PublicKey pubKey) throws Exception { gen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); gen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyCertSign | KeyUsage.cRLSign)); gen.addExtension(X509Extensions.ExtendedKeyUsage, getExtendedKeyUsageCriticality(), new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); // gen.addExtension(X509Extensions.SubjectAlternativeName, false, // new GeneralNames(new GeneralName(GeneralName.rfc822Name, // "test@test.test"))); // netscape-cert-type "2.16.840.1.113730.1.1" // * bit-0 SSL client - 128 // * bit-1 SSL server - 64 // * bit-2 S/MIME - 32 // * bit-3 Object Signing - 16 // * bit-4 Reserved - 8 // * bit-5 SSL CA - 4 // * bit-6 S/MIME CA - 2 // * bit-7 Object Signing CA - 1 gen.addExtension(netscapeCertType, false, new DERBitString(new byte[] { Byte.MAX_VALUE })); // was 4 addSubjectKeyIdentifier(gen, pubKey); addAuthorityKeyIdentifier(gen, pubKey); return gen;// w w w . ja v a 2 s . c o m }
From source file:com.peterphi.std.crypto.keygen.CaHelper.java
License:Open Source License
@SuppressWarnings("unused") static private X509V3CertificateGenerator addServerExtensions(X509V3CertificateGenerator gen, PublicKey pubKey) throws Exception { gen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); gen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment)); gen.addExtension(X509Extensions.ExtendedKeyUsage, getExtendedKeyUsageCriticality(), new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); // gen.addExtension(X509Extensions.SubjectAlternativeName, false, // new GeneralNames(new GeneralName(GeneralName.rfc822Name, // "test@test.test"))); // netscape-cert-type "2.16.840.1.113730.1.1" // * bit-0 SSL client - 128 // * bit-1 SSL server - 64 // * bit-2 S/MIME - 32 // * bit-3 Object Signing - 16 // * bit-4 Reserved - 8 // * bit-5 SSL CA - 4 // * bit-6 S/MIME CA - 2 // * bit-7 Object Signing CA - 1 gen.addExtension(netscapeCertType, false, new DERBitString(new byte[] { -16 })); // was 4 addSubjectKeyIdentifier(gen, pubKey); addAuthorityKeyIdentifier(gen, pubKey); return gen;//w w w .ja v a 2 s.c o m }