List of usage examples for org.bouncycastle.asn1.x500 X500Name X500Name
public X500Name(String dirName)
From source file:org.kse.gui.dnchooser.DistinguishedNameChooser.java
License:Open Source License
public void reset() { currentName = new X500Name(defaultName); removeAll(); init(); revalidate(); repaint(50L); }
From source file:org.neo4j.bolt.security.ssl.Certificates.java
License:Open Source License
public void createSelfSignedCertificate(File certificatePath, File privateKeyPath, String hostName) throws GeneralSecurityException, IOException, OperatorCreationException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance(DEFAULT_ENCRYPTION); keyGen.initialize(2048, random);/*from w w w.ja va 2 s . co m*/ KeyPair keypair = keyGen.generateKeyPair(); // Prepare the information required for generating an X.509 certificate. X500Name owner = new X500Name("CN=" + hostName); X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(owner, new BigInteger(64, random), NOT_BEFORE, NOT_AFTER, owner, keypair.getPublic()); PrivateKey privateKey = keypair.getPrivate(); ContentSigner signer = new JcaContentSignerBuilder("SHA512WithRSAEncryption").build(privateKey); X509CertificateHolder certHolder = builder.build(signer); X509Certificate cert = new JcaX509CertificateConverter().setProvider(PROVIDER).getCertificate(certHolder); //check so that cert is valid cert.verify(keypair.getPublic()); //write to disk writePem("CERTIFICATE", cert.getEncoded(), certificatePath); writePem("PRIVATE KEY", privateKey.getEncoded(), privateKeyPath); }
From source file:org.neo4j.driver.util.CertificateToolTest.java
License:Apache License
/** * Create a random certificate// w w w. ja v a 2 s . com * * @return * @throws GeneralSecurityException, IOException, OperatorCreationException */ public static X509Certificate generateSelfSignedCertificate() throws GeneralSecurityException, IOException, OperatorCreationException { // Create the public/private rsa key pair KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC"); keyPairGenerator.initialize(1024, new SecureRandom()); KeyPair keyPair = keyPairGenerator.generateKeyPair(); // Create x509 certificate Date startDate = new Date(System.currentTimeMillis()); Date endDate = new Date(System.currentTimeMillis() + 365L * 24L * 60L * 60L * 1000L); BigInteger serialNum = BigInteger.valueOf(System.currentTimeMillis()); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); X509v1CertificateBuilder certBuilder = new X509v1CertificateBuilder(new X500Name("CN=NEO4J_JAVA_DRIVER"), serialNum, startDate, endDate, new X500Name("CN=Test"), publicKeyInfo); // Get the certificate back AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); AsymmetricKeyParameter privateKey = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded()); ContentSigner signer = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKey); X509CertificateHolder certHolder = certBuilder.build(signer); return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder); }
From source file:org.neociclo.odetteftp.util.EnvelopingUtil.java
License:Apache License
/** * /*from ww w .jav a2 s . c om*/ * @param cryptData * InputStream of encapsulated encrypted data * @param cert * user secure certificate used to match the recipient identifier * @param key * user private key used to decrypt the encapsulated data * @return InputStream the original data stream (decrypted) * @throws CMSException * @throws IOException * @throws NoSuchProviderException */ public static InputStream openEnvelopedDataParser(InputStream cryptData, X509Certificate cert, PrivateKey key) throws CMSException, IOException, NoSuchProviderException { installBouncyCastleProviderIfNecessary(); // set up the parser CMSEnvelopedDataParser ep = new CMSEnvelopedDataParser(cryptData); // TODO validate the receiving enveloped-data against supported // algorithms // look for our recipient identifier RecipientId recId = new org.bouncycastle.cms.KeyTransRecipientId( new X500Name(cert.getIssuerX500Principal().getName()), cert.getSerialNumber()); RecipientInformationStore recipients = ep.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); if (recipient != null) { // return the decrypting parser InputStream InputStream parserStream = recipient.getContentStream(key, BC_PROVIDER).getContentStream(); return parserStream; } // TODO raise a kind of invalid certificate exception instead of null // or recipient not found return null; }
From source file:org.neociclo.odetteftp.util.EnvelopingUtil.java
License:Apache License
public static InputStream openSignedDataParser(InputStream sigData, final X509Certificate checkCert, final SignatureVerifyResult checkResult) throws CMSException { installBouncyCastleProviderIfNecessary(); // set up the parser final CMSSignedDataParser sp = new CMSSignedDataParser(sigData); // TODO what to do? the validity of the certificate isn't verified here ///*from w w w . jav a 2s . c o m*/ // Perform signature verification. // // Create a runnable block which is executed after the returned // input stream is completely read (end of stream is reached). This is // strictly important, because we are in a streaming mode the order of // the operations is important. // final Runnable signatureChecker = new Runnable() { public void run() { try { SignerInformationStore signers = sp.getSignerInfos(); // lookup signer by matching with the given certificate SignerId sigId = new SignerId(new X500Name(checkCert.getIssuerX500Principal().getName()), checkCert.getSerialNumber()); SignerInformation signer = signers.get(sigId); // perform signature verification if (signer != null) { // // verify that the signature is correct and that it was generated // when the certificate was current // if (signer.verify(checkCert, BC_PROVIDER)) { // signature verified if (checkResult != null) { checkResult.setSuccess(); } } else { // signature failed!!! if (checkResult != null) { checkResult.setFailure(); } } } else { // signer not found if (checkResult != null) { checkResult.setError(new Exception("Provided check certificate doesn't match.")); } } } catch (Exception e) { if (checkResult != null) { checkResult.setError(e); } } } }; // // Return content stream from the encapsulated data. // // A simple input stream is returned, where readable bytes represents // the original content data (without signatures) from the encapsulated // signed envelope. But a wrapping InputStream is created to execute the // signature verification after the buffer is completely read. // final InputStream contentStream = sp.getSignedContent().getContentStream(); InputStream endOfStreamSignatureCheckInputStream = new InputStream() { /** * Used to avoid running the signature checker above multiple times. */ private boolean alreadyReachedEof = false; @Override public int read() throws IOException { int b = contentStream.read(); if (b == -1 && !alreadyReachedEof) { alreadyReachedEof = true; signatureChecker.run(); } return b; } }; return endOfStreamSignatureCheckInputStream; }
From source file:org.neociclo.odetteftp.util.EnvelopingUtil.java
License:Apache License
/** * Return null if certificate's recipientId could not be found within the * encoded envelope - typically when using a bad certificate to decrypt the * authentication challenge encrypted using other public certificate. * /*from w ww .j a va 2 s .co m*/ * @param encoded * @param cert * @param key * @return * @throws NoSuchProviderException * @throws CMSException * @throws IOException */ public static byte[] parseEnvelopedData(byte[] encoded, X509Certificate cert, PrivateKey key) throws NoSuchProviderException, CMSException, IOException { installBouncyCastleProviderIfNecessary(); byte[] data = null; CMSEnvelopedData enveloped = new CMSEnvelopedData(encoded); // TODO validate the receiving enveloped-data against supported // algorithms // look for our recipient identifier RecipientId recId = new org.bouncycastle.cms.KeyTransRecipientId( new X500Name(cert.getIssuerX500Principal().getName()), cert.getSerialNumber()); RecipientInformationStore recipients = enveloped.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); if (recipient != null) { // decrypt the data data = recipient.getContent(key, BC_PROVIDER); } return data; }
From source file:org.neociclo.odetteftp.util.EnvelopingUtil.java
License:Apache License
public static void parseEnvelopedDataContentStream(InputStream envelopedStream, OutputStream outStream, X509Certificate cert, PrivateKey key) throws NoSuchProviderException, CMSException, IOException { installBouncyCastleProviderIfNecessary(); // use the CMS parser to decrypt the EnvelopedData CMSEnvelopedDataParser parser = new CMSEnvelopedDataParser(envelopedStream); // TODO validate the receiving enveloped-data against supported // algorithms // look for our recipient identifier RecipientId recId = new org.bouncycastle.cms.KeyTransRecipientId( new X500Name(cert.getIssuerX500Principal().getName()), cert.getSerialNumber()); RecipientInformationStore recipients = parser.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); if (recipient != null) { // decrypt the data InputStream unenveloped = recipient.getContentStream(key, BC_PROVIDER).getContentStream(); IoUtil.copyStream(unenveloped, outStream); }//from w w w . j a va2 s . c om }
From source file:org.opcfoundation.ua.transport.security.BcCertificateProvider.java
License:Open Source License
/** * Generates a new certificate using the Bouncy Castle implementation. * <p>/*from w w w. ja va 2s . c om*/ * 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.transport.security.BcCertificateProvider.java
License:Open Source License
/** * Build a X509 V3 certificate to use as an issuer (CA) certificate. The * certificate does not define OPC UA specific fields, so it cannot be used * for an application instance certificate. * //from w w w . ja v a2 s . com * @param publicKey * the public key to use for the certificate * @param privateKey * the private key corresponding to the publicKey * @param issuerKeys * the certificate and private key of the certificate issuer: if * null a self-signed certificate is created. * @param commonName * the CommonName to use for the subject of the certificate. * @param serialNr * @param startDate * @param expiryDate * @throws OperatorCreationException */ @Override public X509Certificate generateIssuerCert(PublicKey publicKey, PrivateKey privateKey, KeyPair issuerKeys, String commonName, BigInteger serialNr, Date startDate, Date expiryDate) throws GeneralSecurityException, IOException { JcaX509v3CertificateBuilder certBldr; JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); AuthorityKeyIdentifier authorityKeyIdentifier; if (issuerKeys == null) { X500Name dn = new X500Name(commonName); certBldr = new JcaX509v3CertificateBuilder(dn, serialNr, startDate, expiryDate, dn, publicKey); authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(publicKey); } else { X509Certificate caCert = issuerKeys.getCertificate().getCertificate(); certBldr = new JcaX509v3CertificateBuilder(caCert, serialNr, startDate, expiryDate, new X500Principal(commonName), publicKey); authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(caCert); } certBldr.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier) .addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(publicKey)) .addExtension(Extension.basicConstraints, true, new BasicConstraints(0)) .addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); ContentSigner signer; try { signer = new JcaContentSignerBuilder(CertificateUtils.getCertificateSignatureAlgorithm()) .setProvider("BC").build(privateKey); } catch (OperatorCreationException e) { throw new GeneralSecurityException("Failed to sign the certificate", e); } return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certBldr.build(signer)); }
From source file:org.opcfoundation.ua.utils.BouncyCastleUtils.java
License:Open Source License
/** * Build a X509 V3 certificate to use as an issuer (CA) certificate. The * certificate does not define OPC UA specific fields, so it cannot be used * for an application instance certificate. * /*from w w w . j a v a2 s .c o m*/ * @param publicKey * the public key to use for the certificate * @param privateKey * the private key corresponding to the publicKey * @param issuerKeys * the certificate and private key of the certificate issuer: if * null a self-signed certificate is created. * @param commonName * the CommonName to use for the subject of the certificate. * @param serialNr * @param startDate * @param expiryDate * @throws OperatorCreationException */ public static X509Certificate generateIssuerCert(PublicKey publicKey, PrivateKey privateKey, KeyPair issuerKeys, String commonName, BigInteger serialNr, Date startDate, Date expiryDate) throws GeneralSecurityException, IOException { JcaX509v3CertificateBuilder certBldr; JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); AuthorityKeyIdentifier authorityKeyIdentifier; if (issuerKeys == null) { X500Name dn = new X500Name(commonName); certBldr = new JcaX509v3CertificateBuilder(dn, serialNr, startDate, expiryDate, dn, publicKey); authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(publicKey); } else { X509Certificate caCert = issuerKeys.getCertificate().getCertificate(); certBldr = new JcaX509v3CertificateBuilder(caCert, serialNr, startDate, expiryDate, new X500Principal(commonName), publicKey); authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(caCert); } certBldr.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier) .addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(publicKey)) .addExtension(Extension.basicConstraints, true, new BasicConstraints(0)) .addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); ContentSigner signer; try { signer = new JcaContentSignerBuilder(CertificateUtils.getCertificateSignatureAlgorithm()) .setProvider("BC").build(privateKey); } catch (OperatorCreationException e) { throw new GeneralSecurityException("Failed to sign the certificate", e); } return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certBldr.build(signer)); }