List of usage examples for org.bouncycastle.jce PKCS10CertificationRequest PKCS10CertificationRequest
public PKCS10CertificationRequest(String signatureAlgorithm, X500Principal subject, PublicKey key, ASN1Set attributes, PrivateKey signingKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException
From source file:gridReq.java
License:Open Source License
/** * Generates a encrypted private key and certificate request. *//* w ww . j av a2 s. c om*/ static public void genCertificateRequest(String dname, String emailAddressOfCA, String password, String privKeyLoc, String certLoc, String certReqLoc) throws Exception { String sigAlgName = "MD5WithRSA"; String keyAlgName = "RSA"; //CertUtil.init(); // Generate a new key pair. KeyPairGenerator keygen = KeyPairGenerator.getInstance(keyAlgName); KeyPair keyPair = keygen.genKeyPair(); PrivateKey privKey = keyPair.getPrivate(); PublicKey pubKey = keyPair.getPublic(); // Generate the certificate request. X509Name name = new X509Name(dname); DERConstructedSet derSet = new DERConstructedSet(); PKCS10CertificationRequest request = new PKCS10CertificationRequest(sigAlgName, name, pubKey, derSet, privKey); // Save the certificate request to a .pem file. byte[] data = request.getEncoded(); PrintStream ps = new PrintStream(new FileOutputStream(certReqLoc)); // build / delimited name. String certSubject = ""; StringTokenizer tokens = new StringTokenizer(dname, ","); while (tokens.hasMoreTokens()) { certSubject = certSubject + "/" + tokens.nextToken(); } ps.print("\n\n" + "Please mail the following certificate request to " + emailAddressOfCA + "\n" + "\n" + "==================================================================\n" + "\n" + "Certificate Subject:\n" + "\n" + certSubject + "\n" + "\n" + "The above string is known as your user certificate subject, and it \n" + "uniquely identifies this user.\n" + "\n" + "To install this user certificate, please save this e-mail message\n" + "into the following file.\n" + "\n" + "\n" + certLoc + "\n" + "\n" + "\n" + " You need not edit this message in any way. Simply \n" + " save this e-mail message to the file.\n" + "\n" + "\n" + "If you have any questions about the certificate contact\n" + "the Certificate Authority at " + emailAddressOfCA + "\n" + "\n"); ps.print(toPEM(data)); ps.close(); // Save private key to a .pem file. OpenSSLKey key = new BouncyCastleOpenSSLKey(privKey); if (password.length() != 0) { key.encrypt(password); } key.writeTo(new File(privKeyLoc).getAbsolutePath()); // set read only permissions //Util.setFilePermissions(privKeyLoc, 600); // Create an empty cert file. File f = new File(certLoc); f.createNewFile(); }
From source file:chapter6.PKCS10CertRequestExample.java
public static PKCS10CertificationRequest generateRequest(KeyPair pair) throws Exception { return new PKCS10CertificationRequest("SHA256withRSA", new X500Principal("CN=Requested Test Certificate"), pair.getPublic(), null, pair.getPrivate()); }
From source file:chapter6.PKCS10ExtensionExample.java
public static PKCS10CertificationRequest generateRequest(KeyPair pair) throws Exception { // Create a SubjectAlternativeName extension value GeneralNames subjectAltName = new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test")); // Create the extensions object and add it as an attribute Vector oids = new Vector(); Vector values = new Vector(); oids.add(X509Extensions.SubjectAlternativeName); values.add(new X509Extension(false, new DEROctetString(subjectAltName))); X509Extensions extensions = new X509Extensions(oids, values); Attribute attribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, new DERSet(extensions)); return new PKCS10CertificationRequest("SHA256withRSA", new X500Principal("CN=Requested Test Certificate"), pair.getPublic(), new DERSet(attribute), pair.getPrivate()); }
From source file:com.igeekinc.indelible.indeliblefs.security.EntityAuthenticationClient.java
License:Open Source License
/** * Contacts the Entity Authentication Server to create an authentication for the specified Entity ID * @param entityID//from ww w . j a v a 2 s . c o m * @param entityAuthenticationServerID * @param entityKeys * @return * @throws CertificateEncodingException * @throws InvalidKeyException * @throws IllegalStateException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws SignatureException * @throws UnrecoverableKeyException * @throws KeyStoreException * @throws IOException * @throws CertificateParsingException */ public EntityAuthentication authenticateEntity(EntityID entityID, EntityID entityAuthenticationServerID, KeyPair entityKeys) throws CertificateEncodingException, InvalidKeyException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, UnrecoverableKeyException, KeyStoreException, IOException, CertificateParsingException { EntityAuthentication returnAuthentication = null; synchronized (cachedAuthentications) { HashMap<EntityID, EntityAuthentication> authentications = cachedAuthentications.get(entityID); if (authentications != null) { EntityAuthentication checkAuthentication = authentications.get(entityAuthenticationServerID); if (checkAuthentication != null) { if (checkAuthentication.getAuthorizationExpirationTime().before(new Date())) { returnAuthentication = checkAuthentication; } else { // Authentication is expired, remove from the table authentications.remove(entityAuthenticationServerID); } } } } if (returnAuthentication == null) { X500Principal entityName = new X500Principal(kEntityIDCNPrefix + entityID.toString()); PKCS10CertificationRequest certReq = new PKCS10CertificationRequest( EntityAuthenticationServer.kCertificateSignatureAlg, entityName, entityKeys.getPublic(), null, entityKeys.getPrivate()); byte[] encodedCertReq = certReq.getEncoded(); EntityAuthenticationServer[] authenticateServers = new EntityAuthenticationServer[entityAuthenticationServers .size()]; authenticateServers = entityAuthenticationServers.toArray(authenticateServers); for (int curServerNum = 0; curServerNum < authenticateServers.length; curServerNum++) { if (authenticateServers[curServerNum].getEntityID().equals(entityAuthenticationServerID)) { returnAuthentication = authenticateServers[curServerNum].authenticateServer(entityID, encodedCertReq); break; } ; } if (returnAuthentication != null) { synchronized (cachedAuthentications) { HashMap<EntityID, EntityAuthentication> authentications = cachedAuthentications.get(entityID); if (authentications == null) { authentications = new HashMap<EntityID, EntityAuthentication>(); cachedAuthentications.put(entityID, authentications); } EntityAuthentication checkAuthentication = authentications.get(entityAuthenticationServerID); if (checkAuthentication != null && checkAuthentication.getAuthorizationExpirationTime().before(new Date())) { // Hmmm - someone beat us to it. Use that authentication returnAuthentication = checkAuthentication; } else { authentications.put(entityAuthenticationServerID, returnAuthentication); } } } } return returnAuthentication; }
From source file:com.igeekinc.indelible.indeliblefs.security.EntityAuthenticationServerNewRMITest.java
License:Open Source License
private void doTestAuthenticateServer(SocketAddress tcpConnectAddress) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException, CertificateEncodingException, UnrecoverableKeyException, KeyStoreException, RemoteException, CertificateParsingException, IllegalStateException, AuthenticationFailureException, ServerNotRegisteredException {//from w w w . j a v a2 s . c o m EntityAuthenticationServerFirehoseClient client = new EntityAuthenticationServerFirehoseClient( tcpConnectAddress); try { X500Principal entityName = new X500Principal( EntityAuthenticationClient.kEntityIDCNPrefix + id.toString()); PKCS10CertificationRequest certReq = new PKCS10CertificationRequest( EntityAuthenticationServer.kCertificateSignatureAlg, entityName, keyPair.getPublic(), null, keyPair.getPrivate()); byte[] encodedCertReq = certReq.getEncoded(); EntityAuthentication authentication = client.authenticateServer(id, encodedCertReq); assertNotNull(authentication); } finally { client.close(); } }
From source file:com.jlocksmith.util.CertificateUtil.java
License:Open Source License
/** * Generate PKCS10 CSR//from w w w .j av a 2 s.c o m * * @param cert X590 Certificate * @param privateKey Private Key * @param path File Path * * @return String * @throws Exception */ public static void generatePKCS10CSR(X509Certificate cert, PrivateKey privateKey, String path) throws Exception { X509Name subject = new X509Name(cert.getSubjectDN().toString()); PKCS10CertificationRequest csr = new PKCS10CertificationRequest(cert.getSigAlgName(), subject, cert.getPublicKey(), null, privateKey); // Verify CSR csr.verify(); // Get Base 64 encoding of CSR ByteArrayOutputStream baos = new ByteArrayOutputStream(); DEROutputStream dos = new DEROutputStream(baos); dos.writeObject(csr.getDERObject()); String sTmp = new String(Base64.encode(baos.toByteArray())); // CSR Header String csrText = BEGIN_CERT_REQUEST + "\n"; // Wrap lines for (int iCnt = 0; iCnt < sTmp.length(); iCnt += CERT_REQ_LINE_LENGTH) { int iLineLength; if ((iCnt + CERT_REQ_LINE_LENGTH) > sTmp.length()) { iLineLength = sTmp.length() - iCnt; } else { iLineLength = CERT_REQ_LINE_LENGTH; } csrText += sTmp.substring(iCnt, iCnt + iLineLength) + "\n"; } // CSR Footer csrText += END_CERT_REQUEST + "\n"; // Write it out to file FileWriter fw = null; try { fw = new FileWriter(path); fw.write(csrText); } catch (Exception err) { throw err; } finally { if (fw != null) { try { fw.close(); } catch (IOException ex) { } } } }
From source file:com.peterphi.std.crypto.keygen.CaHelper.java
License:Open Source License
public static PKCS10CertificationRequest generateCertificateRequest(X509Certificate cert, PrivateKey signingKey) throws Exception { ASN1EncodableVector attributes = new ASN1EncodableVector(); Set<String> nonCriticalExtensionOIDs = cert.getNonCriticalExtensionOIDs(); for (String nceoid : nonCriticalExtensionOIDs) { byte[] derBytes = cert.getExtensionValue(nceoid); ByteArrayInputStream bis = new ByteArrayInputStream(derBytes); ASN1InputStream dis = new ASN1InputStream(bis); try {//from ww w . j a va2 s . co m DERObject derObject = dis.readObject(); DERSet value = new DERSet(derObject); Attribute attr = new Attribute(new DERObjectIdentifier(nceoid), value); attributes.add(attr); } finally { IOUtils.closeQuietly(dis); } } PKCS10CertificationRequest certificationRequest = new PKCS10CertificationRequest(getSignatureAlgorithm(), cert.getSubjectX500Principal(), cert.getPublicKey(), new DERSet(attributes), signingKey); return certificationRequest; }
From source file:com.zotoh.crypto.Crypto.java
License:Open Source License
/** * @param keyLength//from w w w.j a v a2 s. c o m * @param dnStr * @param fmt * @return * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws NoSuchProviderException * @throws SignatureException * @throws IOException */ public Tuple createCSR(int keyLength, String dnStr, CertFormat fmt) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException, IOException { tstPosIntArg("key-length", keyLength); tstEStrArg("subject-dn", dnStr); tstObjArg("cert-format", fmt); tlog().debug("Crypto: createCSR: dnStr= {}, key-len= {}", dnStr, keyLength); KeyPair kp = createKeyPair("RSA", keyLength); PrivateKey k = kp.getPrivate(); byte[] bits = new PKCS10CertificationRequest(DEF_ALGO, new X500Principal(dnStr), kp.getPublic(), null, k) .getEncoded(); if (CertFormat.PEM == fmt) { bits = fmtPEM("-----BEGIN CERTIFICATE REQUEST-----\n", "\n-----END CERTIFICATE REQUEST-----\n", bits); } return new Tuple(bits, getPKey(k, fmt)); }
From source file:de.mendelson.util.security.csr.CSRUtil.java
/** * Generates a PKCS10 CertificationRequest. The passed private key must not be trusted *//*from www.j a v a 2 s .c o m*/ public PKCS10CertificationRequest generateCSR(PrivateKey key, X509Certificate cert) throws Exception { X509Name subject = new X509Name(cert.getSubjectDN().toString()); PKCS10CertificationRequest csr = new PKCS10CertificationRequest(cert.getSigAlgName(), subject, cert.getPublicKey(), null, key); boolean verified = csr.verify(); if (!verified) { throw new Exception(this.rb.getResourceString("verification.failed")); } return (csr); }
From source file:io.aos.crypto.spl06.PKCS10ExtensionExample.java
License:Apache License
public static PKCS10CertificationRequest generateRequest(KeyPair pair) throws Exception { // create a SubjectAlternativeName extension value GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test")); // create the extensions object and add it as an attribute Vector oids = new Vector(); Vector values = new Vector(); oids.add(X509Extensions.SubjectAlternativeName); values.add(new X509Extension(false, new DEROctetString(subjectAltNames))); X509Extensions extensions = new X509Extensions(oids, values); Attribute attribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, new DERSet(extensions)); return new PKCS10CertificationRequest("SHA256withRSA", new X500Principal("CN=Requested Test Certificate"), pair.getPublic(), new DERSet(attribute), pair.getPrivate()); }