List of usage examples for org.bouncycastle.asn1.x509 GeneralNames GeneralNames
private GeneralNames(ASN1Sequence seq)
From source file:org.mailster.core.crypto.CertificateUtilities.java
License:Open Source License
/** * Generate a sample V3 certificate to use as an intermediate or end entity * certificate depending on the <code>isEndEntity</code> argument. *//* w ww .ja va 2s .com*/ private static X509Certificate generateV3Certificate(String DN, boolean isEndEntity, PublicKey entityKey, PrivateKey caKey, X509Certificate caCert) throws Exception { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setIssuerDN(caCert.getSubjectX500Principal()); certGen.setSubjectDN(new X509Name(true, X509Name.DefaultLookUp, DN)); setSerialNumberAndValidityPeriod(certGen, false, DEFAULT_VALIDITY_PERIOD); certGen.setPublicKey(entityKey); certGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(caCert.getEncoded(), new GeneralNames(new GeneralName( new X509Name(true, X509Name.DefaultLookUp, caCert.getSubjectDN().getName()))), caCert.getSerialNumber())); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(entityKey)); if (isEndEntity) { certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); } else { certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); } return certGen.generate(caKey, "BC"); }
From source file:org.metaeffekt.dcc.commons.pki.CertificateManager.java
License:Apache License
private DistributionPoint[] createCrlDistributionPoints() { List<DistributionPoint> list = new ArrayList<>(); Set<String> keys = getArrayKeys(PROPERTY_PREFIX_CRL_DISTRIBUTION_POINT); for (String dpPrefix : keys) { final String uriKey = dpPrefix + ".uri"; String uri = getMandatoryProperty(uriKey); DistributionPointName dpName = new DistributionPointName( new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, uri))); list.add(new DistributionPoint(dpName, null, null)); }//from www. j av a2 s .co m if (list.isEmpty()) return null; return list.toArray(new DistributionPoint[list.size()]); }
From source file:org.nimbustools.auto_common.ezpz_ca.CAFactory.java
License:Apache License
public X509Certificate create(String baseName, int months, KeyPair keyPair) throws Exception { final X509Principal newprincipal = new X509Principal("O=Auto,OU=" + baseName + ",CN=CA"); this.certGen.reset(); /*//from w ww . j ava 2 s . c o m "The entity that created the certificate is responsible for assigning it a serial number to distinguish it from other certificates it issues. This information is used in numerous ways, for example when a certificate is revoked its serial number is placed in a Certificate Revocation List (CRL)" */ this.certGen.setSerialNumber(BigInteger.ZERO); final Calendar expires = Calendar.getInstance(); expires.add(Calendar.MONTH, months); this.certGen.setNotBefore(new Date(System.currentTimeMillis() - 10000)); this.certGen.setNotAfter(expires.getTime()); this.certGen.setSubjectDN(newprincipal); this.certGen.setIssuerDN(newprincipal); this.certGen.setSignatureAlgorithm("SHA1withRSA"); final PublicKey pubkey = keyPair.getPublic(); this.certGen.setPublicKey(pubkey); // begin X509/BC security nastiness, not sure these are the very best // choices but it is working... final ByteArrayInputStream in = new ByteArrayInputStream(pubkey.getEncoded()); final SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) new DERInputStream(in).readObject()); final SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki); final ByteArrayInputStream in2 = new ByteArrayInputStream(newprincipal.getEncoded()); final GeneralNames generalNames = new GeneralNames((ASN1Sequence) new DERInputStream(in2).readObject()); final AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(spki, generalNames, BigInteger.ZERO); this.certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); /* this.certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); */ this.certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, ski); this.certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, aki); this.certGen.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.cRLSign | KeyUsage.keyCertSign)); return this.certGen.generateX509Certificate(keyPair.getPrivate()); }
From source file:org.nuxeo.ecm.platform.signature.core.pki.CertServiceImpl.java
License:Open Source License
protected CertificationRequest generateCSR(KeyPair keyPair, UserInfo userInfo) throws CertException { CertificationRequest csr;/*from ww w . j a v a2 s . c om*/ GeneralNames subjectAltName = new GeneralNames( new GeneralName(GeneralName.rfc822Name, userInfo.getUserFields().get(CNField.Email))); Vector<DERObjectIdentifier> objectIdentifiers = new Vector<DERObjectIdentifier>(); Vector<X509Extension> extensionValues = new Vector<X509Extension>(); objectIdentifiers.add(X509Extensions.SubjectAlternativeName); extensionValues.add(new X509Extension(false, new DEROctetString(subjectAltName))); X509Extensions extensions = new X509Extensions(objectIdentifiers, extensionValues); Attribute attribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, new DERSet(extensions)); try { csr = new PKCS10CertificationRequest(CERT_SIGNATURE_ALGORITHM, userInfo.getX500Principal(), keyPair.getPublic(), new DERSet(attribute), keyPair.getPrivate()); } catch (InvalidKeyException e) { throw new CertException(e); } catch (NoSuchAlgorithmException e) { throw new CertException(e); } catch (NoSuchProviderException e) { throw new CertException(e); } catch (java.security.SignatureException e) { throw new CertException(e); } catch (Exception e) { throw new CertException(e); } return csr; }
From source file:org.opcfoundation.ua.transport.security.BcCertificateProvider.java
License:Open Source License
/** * Generates a new certificate using the Bouncy Castle implementation. * <p>/* w ww . j av a 2 s.c o m*/ * The method is used from * {@link CertificateUtils#createApplicationInstanceCertificate(String, String, String, int, String...)} * and * {@link CertificateUtils#renewApplicationInstanceCertificate(String, String, String, int, org.opcfoundation.ua.transport.security.KeyPair, String...)} * * @param domainName * the X500 domain name for the certificate * @param publicKey * the public key of the cert * @param privateKey * the private key of the cert * @param issuerKeys * the certificate and private key of the issuer * @param from * validity start time * @param to * validity end time * @param serialNumber * a unique serial number for the certificate * @param applicationUri * the OPC UA ApplicationUri of the application - added to * SubjectAlternativeName * @param hostNames * the additional host names to add to SubjectAlternativeName * @return the generated certificate * @throws GeneralSecurityException * if the generation fails * @throws IOException * if the generation fails due to an IO exception */ @Override public X509Certificate generateCertificate(String domainName, PublicKey publicKey, PrivateKey privateKey, KeyPair issuerKeys, Date from, Date to, BigInteger serial, String applicationUri, String... hostNames) throws IOException, GeneralSecurityException { JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); X509v3CertificateBuilder certBldr; AuthorityKeyIdentifier authorityKeyIdentifier; PrivateKey signerKey; if (issuerKeys == null) { X500Name dn = new X500Name(domainName); certBldr = new JcaX509v3CertificateBuilder(dn, serial, from, to, dn, publicKey); authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(publicKey); signerKey = privateKey; } else { X509Certificate caCert = issuerKeys.getCertificate().getCertificate(); certBldr = new JcaX509v3CertificateBuilder(caCert, serial, from, to, new X500Principal(domainName), publicKey); authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(caCert); signerKey = issuerKeys.getPrivateKey().getPrivateKey(); } certBldr.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier) .addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(publicKey)) .addExtension(Extension.basicConstraints, false, new BasicConstraints(false)).addExtension( Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation | KeyUsage.dataEncipherment | KeyUsage.keyCertSign)); // BC 1.49: certBldr.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage( new KeyPurposeId[] { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth })); // create the extension value // URI Name List<GeneralName> names = new ArrayList<GeneralName>(); names.add(new GeneralName(GeneralName.uniformResourceIdentifier, applicationUri)); // Add DNS name from ApplicationUri boolean hasDNSName = false; String uriHostName = null; try { String[] appUriParts = applicationUri.split("[:/]"); if (appUriParts.length > 1) { uriHostName = appUriParts[1]; if (!uriHostName.toLowerCase().equals("localhost")) { GeneralName dnsName = new GeneralName(GeneralName.dNSName, uriHostName); names.add(dnsName); hasDNSName = true; } } } catch (Exception e) { logger.warn("Cannot initialize DNS Name to Certificate from ApplicationUri {}", applicationUri); } // Add other DNS Names List<GeneralName> ipAddressNames = new ArrayList<GeneralName>(); if (hostNames != null) for (String hostName : hostNames) { boolean isIpAddress = hostName.matches("^[0-9.]+$"); if (!hostName.equals(uriHostName) && !hostName.toLowerCase().equals("localhost")) { GeneralName dnsName = new GeneralName( hostName.matches("^[0-9.]+$") ? GeneralName.iPAddress : GeneralName.dNSName, hostName); if (isIpAddress) ipAddressNames.add(dnsName); else { names.add(dnsName); hasDNSName = true; } } } // Add IP Addresses, if no host names are defined if (!hasDNSName) for (GeneralName n : ipAddressNames) names.add(n); final GeneralNames subjectAltNames = new GeneralNames(names.toArray(new GeneralName[0])); certBldr.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); // ***** generate certificate ***********/ try { ContentSigner signer = new JcaContentSignerBuilder(CertificateUtils.getCertificateSignatureAlgorithm()) .setProvider("BC").build(signerKey); return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certBldr.build(signer)); } catch (OperatorCreationException e) { throw new GeneralSecurityException(e); } }
From source file:org.opcfoundation.ua.utils.BouncyCastleUtils.java
License:Open Source License
/** * Generates a new certificate using the Bouncy Castle implementation. * <p>//from w w w . j av a 2s. c o m * The method is used from * {@link CertificateUtils#createApplicationInstanceCertificate(String, String, String, int, String...)} * and * {@link CertificateUtils#renewApplicationInstanceCertificate(String, String, String, int, org.opcfoundation.ua.transport.security.KeyPair, String...)} * * @param domainName * the X500 domain name for the certificate * @param publicKey * the public key of the cert * @param privateKey * the private key of the cert * @param issuerKeys * the certificate and private key of the issuer * @param from * validity start time * @param to * validity end time * @param serialNumber * a unique serial number for the certificate * @param applicationUri * the OPC UA ApplicationUri of the application - added to * SubjectAlternativeName * @param hostNames * the additional host names to ass to SubjectAlternativeName * @return the generated certificate * @throws GeneralSecurityException * if the generation fails * @throws IOException * if the generation fails due to an IO exception */ public static X509Certificate generateCertificate(String domainName, PublicKey publicKey, PrivateKey privateKey, KeyPair issuerKeys, Date from, Date to, BigInteger serial, String applicationUri, String... hostNames) throws IOException, GeneralSecurityException { JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); X509v3CertificateBuilder certBldr; AuthorityKeyIdentifier authorityKeyIdentifier; PrivateKey signerKey; if (issuerKeys == null) { X500Name dn = new X500Name(domainName); certBldr = new JcaX509v3CertificateBuilder(dn, serial, from, to, dn, publicKey); authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(publicKey); signerKey = privateKey; } else { X509Certificate caCert = issuerKeys.getCertificate().getCertificate(); certBldr = new JcaX509v3CertificateBuilder(caCert, serial, from, to, new X500Principal(domainName), publicKey); authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(caCert); signerKey = issuerKeys.getPrivateKey().getPrivateKey(); } certBldr.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier) .addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(publicKey)) .addExtension(Extension.basicConstraints, false, new BasicConstraints(false)).addExtension( Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation | KeyUsage.dataEncipherment | KeyUsage.keyCertSign)); certBldr.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage( new KeyPurposeId[] { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth })); // Vector<KeyPurposeId> extendedKeyUsages = new Vector<KeyPurposeId>(); // extendedKeyUsages.add(KeyPurposeId.id_kp_serverAuth); // extendedKeyUsages.add(KeyPurposeId.id_kp_clientAuth); // certBldr.addExtension(Extension.extendedKeyUsage, false, // new ExtendedKeyUsage(extendedKeyUsages)); // BC 1.49: // certBldr.addExtension(X509Extension.extendedKeyUsage, false, // new ExtendedKeyUsage(new KeyPurposeId[] { // KeyPurposeId.id_kp_serverAuth, // KeyPurposeId.id_kp_clientAuth })); // create the extension value // URI Name List<GeneralName> names = new ArrayList<GeneralName>(); names.add(new GeneralName(GeneralName.uniformResourceIdentifier, applicationUri)); // Add DNS name from ApplicationUri boolean hasDNSName = false; String uriHostName = null; try { String[] appUriParts = applicationUri.split("[:/]"); if (appUriParts.length > 1) { uriHostName = appUriParts[1]; if (!uriHostName.toLowerCase().equals("localhost")) { GeneralName dnsName = new GeneralName(GeneralName.dNSName, uriHostName); names.add(dnsName); hasDNSName = true; } } } catch (Exception e) { logger.warn("Cannot initialize DNS Name to Certificate from ApplicationUri {}", applicationUri); } // Add other DNS Names List<GeneralName> ipAddressNames = new ArrayList<GeneralName>(); if (hostNames != null) for (String hostName : hostNames) { boolean isIpAddress = hostName.matches("^[0-9.]+$"); if (!hostName.equals(uriHostName) && !hostName.toLowerCase().equals("localhost")) { GeneralName dnsName = new GeneralName( hostName.matches("^[0-9.]+$") ? GeneralName.iPAddress : GeneralName.dNSName, hostName); if (isIpAddress) ipAddressNames.add(dnsName); else { names.add(dnsName); hasDNSName = true; } } } // Add IP Addresses, if no host names are defined if (!hasDNSName) for (GeneralName n : ipAddressNames) names.add(n); final GeneralNames subjectAltNames = new GeneralNames(names.toArray(new GeneralName[0])); certBldr.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); //***** generate certificate ***********/ try { ContentSigner signer = new JcaContentSignerBuilder(CertificateUtils.getCertificateSignatureAlgorithm()) .setProvider("BC").build(signerKey); return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certBldr.build(signer)); } catch (OperatorCreationException e) { throw new GeneralSecurityException(e); } }
From source file:org.opcfoundation.ua.utils.CertificateUtils.java
License:Open Source License
/** * //from w w w .j a v a 2 s . c o m * @param commonName - Common Name (CN) for generated certificate * @param organisation - Organisation (O) for generated certificate * @param applicationUri - Alternative name (one of x509 extensiontype) for generated certificate. Must not be null * @param validityTime - the time that the certificate is valid (in days) * @return * @throws IOException * @throws InvalidKeySpecException * @throws NoSuchAlgorithmException * @throws CertificateEncodingException * @throws InvalidKeyException * @throws IllegalStateException * @throws NoSuchProviderException * @throws SignatureException * @throws CertificateParsingException */ public static org.opcfoundation.ua.transport.security.KeyPair createApplicationInstanceCertificate( String commonName, String organisation, String applicationUri, int validityTime) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException, CertificateEncodingException, InvalidKeyException, IllegalStateException, NoSuchProviderException, SignatureException, CertificateParsingException { if (applicationUri == null) throw new NullPointerException("applicationUri must not be null"); //Add provider for generator Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); //Initializes generator SecureRandom srForCert = new SecureRandom(); RSAKeyPairGenerator genForCert = new RSAKeyPairGenerator(); //Used for generating prime Random r = new Random(System.currentTimeMillis()); int random = -1; while (random < 3) { random = r.nextInt(32); } //calculate(generate) possible value for public modulus //used method is "monte carlo -algorithm", so we calculate it as long as it generates value. BigInteger value = null; while (value == null) { value = BigInteger.probablePrime(random, new SecureRandom()); } //Generate (Java) keypair genForCert.init(new RSAKeyGenerationParameters(value, srForCert, KEY_SIZE, 80)); AsymmetricCipherKeyPair keypairForCert = genForCert.generateKeyPair(); //Extract the keys from parameters logger.debug("Generated keypair, extracting components and creating public structure for certificate"); RSAKeyParameters clientPublicKey = (RSAKeyParameters) keypairForCert.getPublic(); RSAPrivateCrtKeyParameters clientPrivateKey = (RSAPrivateCrtKeyParameters) keypairForCert.getPrivate(); // used to get proper encoding for the certificate RSAPublicKeyStructure clientPkStruct = new RSAPublicKeyStructure(clientPublicKey.getModulus(), clientPublicKey.getExponent()); logger.debug("New public key is '" + makeHexString(clientPkStruct.getEncoded()) + ", exponent=" + clientPublicKey.getExponent() + ", modulus=" + clientPublicKey.getModulus()); // JCE format needed for the certificate - because getEncoded() is necessary... PublicKey certPubKey = KeyFactory.getInstance("RSA") .generatePublic(new RSAPublicKeySpec(clientPublicKey.getModulus(), clientPublicKey.getExponent())); // and this one for the KeyStore PrivateKey certPrivKey = KeyFactory.getInstance("RSA").generatePrivate( new RSAPrivateCrtKeySpec(clientPublicKey.getModulus(), clientPublicKey.getExponent(), clientPrivateKey.getExponent(), clientPrivateKey.getP(), clientPrivateKey.getQ(), clientPrivateKey.getDP(), clientPrivateKey.getDQ(), clientPrivateKey.getQInv())); //The data for the certificate.. Calendar expiryTime = Calendar.getInstance(); expiryTime.add(Calendar.DAY_OF_YEAR, validityTime); X509Name certificateX509Name = new X509Name( "CN=" + commonName + ", O=" + organisation + ", C=" + System.getProperty("user.country")); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); BigInteger serial = BigInteger.valueOf(System.currentTimeMillis()); certGen.setSerialNumber(serial); //Issuer and subject must be the same (because this is self signed) certGen.setIssuerDN(certificateX509Name); certGen.setSubjectDN(certificateX509Name); //expiry & start time for this certificate certGen.setNotBefore(new Date(System.currentTimeMillis() - 1000 * 60 * 60)); //take 60 minutes (1000 ms * 60 s * 60) away from system clock (in case there is some lag in system clocks) certGen.setNotAfter(expiryTime.getTime()); certGen.setPublicKey(certPubKey); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); //******* X.509 V3 Extensions ***************** SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(certPubKey.getEncoded())).readObject()); SubjectKeyIdentifier ski = new SubjectKeyIdentifier(apki); /*certGen.addExtension(X509Extensions.SubjectKeyIdentifier, true, new DEROctetString(ski//new SubjectKeyIdentifier Structure(apki/*certPubKey))); */ certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, ski); certGen.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, /*new DEROctetString(new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation | KeyUsage.dataEncipherment | KeyUsage.keyCertSign ))*/new KeyUsage( KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation | KeyUsage.dataEncipherment | KeyUsage.keyCertSign)); BasicConstraints b = new BasicConstraints(false); Vector<KeyPurposeId> extendedKeyUsages = new Vector<KeyPurposeId>(); extendedKeyUsages.add(KeyPurposeId.id_kp_serverAuth); extendedKeyUsages.add(KeyPurposeId.id_kp_clientAuth); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, /*new DEROctetString(new ExtendedKeyUsage(extendedKeyUsages))*/new ExtendedKeyUsage( extendedKeyUsages)); // create the extension value ASN1EncodableVector names = new ASN1EncodableVector(); names.add(new GeneralName(GeneralName.uniformResourceIdentifier, applicationUri)); // GeneralName dnsName = new GeneralName(GeneralName.dNSName, applicationUri); // names.add(dnsName); final GeneralNames subjectAltNames = new GeneralNames(new DERSequence(names)); certGen.addExtension(X509Extensions.SubjectAlternativeName, true, subjectAltNames); // AuthorityKeyIdentifier final GeneralNames certificateIssuer = new GeneralNames(new GeneralName(certificateX509Name)); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki, certificateIssuer, serial); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, aki); //***** generate certificate ***********/ X509Certificate cert = certGen.generate(certPrivKey, "BC"); //Encapsulate Certificate and private key to CertificateKeyPair Cert certificate = new Cert(cert); org.opcfoundation.ua.transport.security.PrivKey UAkey = new org.opcfoundation.ua.transport.security.PrivKey( (RSAPrivateKey) certPrivKey); return new org.opcfoundation.ua.transport.security.KeyPair(certificate, UAkey); }
From source file:org.openmaji.implementation.security.utility.cert.CertUtil.java
License:Open Source License
private static AuthorityKeyIdentifier createAuthorityKeyId(PublicKey pubKey, X509Name name, BigInteger sNumber) {/* w ww . j av a2 s. co m*/ try { ByteArrayInputStream bIn = new ByteArrayInputStream(pubKey.getEncoded()); SubjectPublicKeyInfo info = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(bIn).readObject()); // (ASN1Sequence)new DERInputStream(bIn).readObject() GeneralName genName = new GeneralName(name); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(genName); return new AuthorityKeyIdentifier(info, new GeneralNames(new DERSequence(v)), sNumber); } catch (Exception e) { throw new RuntimeException("error creating AuthorityKeyId"); } }
From source file:org.openmaji.implementation.server.security.auth.CoreAdminHelper.java
License:Open Source License
private static AuthorityKeyIdentifier createAuthorityKeyId(PublicKey pubKey, X509Principal name, BigInteger sNumber) {/*from ww w.ja v a2s . c o m*/ try { ByteArrayInputStream bIn = new ByteArrayInputStream(pubKey.getEncoded()); SubjectPublicKeyInfo info = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(bIn).readObject()); GeneralName genName = new GeneralName(name); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(genName); return new AuthorityKeyIdentifier(info, new GeneralNames(new DERSequence(v)), sNumber); } catch (Exception e) { throw new RuntimeException("error creating AuthorityKeyId"); } }
From source file:org.pidome.server.services.provider.CertGen.java
License:Apache License
private void gen() throws CertGenException { try {/*from ww w .j a v a 2s.c o m*/ File store = new File(SystemConfig.getProperty("system", "server.keystore")); store.getParentFile().mkdirs(); if (store.exists()) { store.delete(); } X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setSubjectDN(new X500Principal("CN=" + curHost)); certGen.setIssuerDN(new X500Principal("CN=PiDome Server at " + curHost)); certGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30)); certGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10))); certGen.setPublicKey(KPair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); GeneralName altName = new GeneralName(GeneralName.iPAddress, Network.getIpAddressProperty().get().getHostAddress()); GeneralNames subjectAltName = new GeneralNames(altName); certGen.addExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName); X509Certificate cert = certGen.generate(KPair.getPrivate(), "BC"); /// Always, but always create a new keystore. a new keystore pass has is always created. privateKS = KeyStore.getInstance("JKS"); privateKS.load(null, null); String storePass = MessageDigest.getInstance("MD5").toString(); privateKS.setKeyEntry("PiDome.Default", KPair.getPrivate(), storePass.toCharArray(), new java.security.cert.Certificate[] { cert }); store.createNewFile(); privateKS.store(new FileOutputStream(store), storePass.toCharArray()); System.setProperty("javax.net.ssl.keyStore", SystemConfig.getProperty("system", "server.keystore")); System.setProperty("javax.net.ssl.keyStorePassword", storePass); available = true; LOG.info("Certificate(s) generated."); } catch (CertificateEncodingException ex) { throw new CertGenException("Could not encode certificate, can not continue: " + ex.getMessage()); } catch (IllegalStateException ex) { throw new CertGenException("Illegal state, can not continue: " + ex.getMessage()); } catch (NoSuchProviderException ex) { throw new CertGenException("No known provider, can not continue: " + ex.getMessage()); } catch (NoSuchAlgorithmException ex) { throw new CertGenException("No such algorithm, can not continue: " + ex.getMessage()); } catch (SignatureException ex) { throw new CertGenException("Signature problem, can not continue: " + ex.getMessage()); } catch (InvalidKeyException ex) { throw new CertGenException("Invalid key used, can not continue: " + ex.getMessage()); } catch (KeyStoreException ex) { throw new CertGenException("KeyStore problem, can not continue: " + ex.getMessage()); } catch (IOException ex) { throw new CertGenException("KeyStore can not be opened, can not continue: " + ex.getMessage()); } catch (CertificateException ex) { throw new CertGenException("KeyStore certificate problem, can not continue: " + ex.getMessage()); } catch (ConfigPropertiesException ex) { throw new CertGenException( "KeyStore location configuration problem, can not continue: " + ex.getMessage()); } }