List of usage examples for org.bouncycastle.jce PKCS10CertificationRequest getEncoded
public byte[] getEncoded()
From source file:org.ejbca.core.protocol.PKCS10RequestMessage.java
License:Open Source License
/** * Constructs a new PKCS#10 message handler object. * * @param p10 the PKCS#10 request// www .j av a 2 s . com */ public PKCS10RequestMessage(PKCS10CertificationRequest p10) { if (log.isTraceEnabled()) { log.trace(">PKCS10RequestMessage(ExtendedPKCS10CertificationRequest)"); } p10msg = p10.getEncoded(); pkcs10 = p10; if (log.isTraceEnabled()) { log.trace("<PKCS10RequestMessage(ExtendedPKCS10CertificationRequest)"); } }
From source file:org.globus.cog.security.cert.request.GridCertRenewalRequest.java
License:Open Source License
/** * The renewal request method is based on the Grid Canada's renew.sh script. * //from w w w . ja v a 2s .co m * @param newPrivateKeyPassword * @param chalenge * @param newPrivKeyLoc * @param userCertRenewFile * @return */ public static void genRenewRequest(GlobusGSSCredentialImpl cred, String newPrivateKeyPassword, String chalenge, String newPrivKeyLoc, String userCertRenewFile) throws GeneralSecurityException, IOException { File fTempDigest = null; try { // Extract the private key, encrypt it in new passphrase and save it as new user key // $OPENSSL rsa -des3 -in $TMPPROXY -out $RENEWALKEY OpenSSLKey key = new BouncyCastleOpenSSLKey(cred.getPrivateKey()); if (newPrivateKeyPassword.length() != 0) { key.encrypt(newPrivateKeyPassword); } key.writeTo(new File(newPrivKeyLoc).getAbsolutePath()); // set read only permissions Util.setFilePermissions(newPrivKeyLoc, 600); // copy proxy cert signed by user // $OPENSSL x509 -in $TMPPROXY >> $RENEWALREQ PrintStream ps = null; X509Certificate cert = null; byte[] data = null; X509Certificate[] certs = cred.getCertificateChain(); cert = certs[0]; data = cert.getEncoded(); ps = new PrintStream(new FileOutputStream(userCertRenewFile)); ////// part 1 ///// ps.print(toCertPEM(data)); // generate a digest which can not be copied // $OPENSSL x509 -in $TMPPROXY > $TMPPROXY.d // echo X$1 >> $TMPPROXY.d // $OPENSSL dgst < $TMPPROXY.d >> $RENEWALREQ fTempDigest = File.createTempFile("digest-", ".pem"); PrintStream psDigest = new PrintStream(new FileOutputStream(fTempDigest)); psDigest.print(toCertPEM(data)); psDigest.println("X" + chalenge); psDigest.close(); FileInputStream inDigest = null; inDigest = new FileInputStream(fTempDigest); int digestSize = inDigest.available(); byte[] digestData = new byte[digestSize]; inDigest.read(digestData, 0, digestSize); MessageDigest md = MessageDigest.getInstance("MD5"); int le = md.getDigestLength(); byte[] digest = md.digest(digestData); /////// part 2 /////// ps.println(Hex.toString(digest).toLowerCase()); // generate a cert req signed by the new key. // $OPENSSL x509 -in $TMPPROXY -x509toreq -signkey $RENEWALKEY >> $RENEWALREQ // Generate a certificate request. X509Name name = new X509Name(cert.getIssuerDN().getName()); DERConstructedSet derSet = new DERConstructedSet(); PKCS10CertificationRequest request = null; request = new PKCS10CertificationRequest("MD5WithRSA", name, cert.getPublicKey(), derSet, key.getPrivateKey()); /////// part 3 ///// ps.println("Certificate Request:"); ps.println(" Data:"); ps.print(cert.toString()); ps.print(toCertReqPEM(request.getEncoded())); ps.close(); } finally { if (fTempDigest != null) { fTempDigest.delete(); } } }
From source file:org.globus.cog.security.cert.request.GridCertRequest.java
License:Open Source License
/** * Generates a encrypted private key and certificate request. *///from w ww .ja va2 s . c o m 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:org.globus.gsi.bc.BouncyCastleCertProcessingFactory.java
License:Apache License
/** * Creates a certificate request from the specified subject name, signing algorithm, and a key pair. * * @param subjectDN/*from w w w .j a va2s .c o m*/ * the subject name of the certificate request. * @param sigAlgName * the signing algorithm name. * @param keyPair * the key pair of the certificate request * @return the certificate request. * @exception GeneralSecurityException * if security error occurs. */ public byte[] createCertificateRequest(X509Name subjectDN, String sigAlgName, KeyPair keyPair) throws GeneralSecurityException { DERSet attrs = null; PKCS10CertificationRequest certReq = null; certReq = new PKCS10CertificationRequest(sigAlgName, subjectDN, keyPair.getPublic(), attrs, keyPair.getPrivate()); return certReq.getEncoded(); }
From source file:org.globus.tools.GridCertRequest.java
License:Open Source License
/** * Generates a encrypted private key and certificate request. */// w w w.j a v a 2 s. c om static public void genCertificateRequest(String dname, String emailAddressOfCA, String password, File keyFile, File certFile, File certReqFile) throws Exception { String sigAlgName = "MD5WithRSA"; String keyAlgName = "RSA"; CertUtil.init(); X509Name name = new X509Name(dname); String certSubject = X509NameHelper.toString(name); System.out.println("Generating a 1024 bit RSA private key"); // Generate a new key pair. KeyPairGenerator keygen = KeyPairGenerator.getInstance(keyAlgName); keygen.initialize(1024); KeyPair keyPair = keygen.genKeyPair(); PrivateKey privKey = keyPair.getPrivate(); PublicKey pubKey = keyPair.getPublic(); // Generate the certificate request. DERSet derSet = new DERSet(); PKCS10CertificationRequest request = new PKCS10CertificationRequest(sigAlgName, name, pubKey, derSet, privKey); // Save the certificate request to a .pem file. byte[] data = request.getEncoded(); byte[] encodedData = Base64.encode(data); PrintStream ps = null; try { ps = new PrintStream(new FileOutputStream(certReqFile)); boolean caEmail = false; if ((emailAddressOfCA != null) && (emailAddressOfCA.length() > 0)) { caEmail = true; ps.print("\n\n" + "Please mail the following certificate request to " + emailAddressOfCA); } else { ps.print("\n\n" + "Please send the following certificate request to the Certificate Authority (CA). Refer to CA instructions for details on to send the request."); } ps.print("\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" + certReqFile.getAbsolutePath() + "\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"); if (caEmail) { ps.print("at " + emailAddressOfCA); } ps.print("\n\n"); PEMUtils.writeBase64(ps, "-----BEGIN CERTIFICATE REQUEST-----", encodedData, "-----END CERTIFICATE REQUEST-----"); } finally { if (ps != null) { ps.close(); } } // Save private key to a .pem file. OpenSSLKey key = new BouncyCastleOpenSSLKey(privKey); if (password != null) { key.encrypt(password); } // this will set the permissions correctly already key.writeTo(keyFile.getAbsolutePath()); // Create an empty cert file. certFile.createNewFile(); System.out.println("A private key and a certificate request has been generated with the subject:"); System.out.println(); System.out.println(certSubject); System.out.println(); System.out.println("The private key is stored in " + keyFile.getAbsolutePath()); System.out.println("The request is stored in " + certReqFile.getAbsolutePath()); }
From source file:org.opendaylight.aaa.cert.impl.ODLKeyTool.java
License:Open Source License
public String generateCertificateReq(final String keyStoreName, final String keyStorePwd, final String keyAlias, final String signAlg, final boolean withTag) { try {//from ww w . j a v a 2 s. c o m final KeyStore ctlKeyStore = KeyStore.getInstance("JKS"); final FileInputStream fInputStream = new FileInputStream(workingDir + keyStoreName); ctlKeyStore.load(fInputStream, keyStorePwd.toCharArray()); if (ctlKeyStore.containsAlias(keyAlias)) { final X509Certificate odlCert = (X509Certificate) ctlKeyStore.getCertificate(keyAlias); final PublicKey pubKey = odlCert.getPublicKey(); final PrivateKey privKey = (PrivateKey) ctlKeyStore.getKey(keyAlias, keyStorePwd.toCharArray()); final String subject = odlCert.getSubjectDN().getName(); final X509Name xname = new X509Name(subject); final String signatureAlgorithm = signAlg; final PKCS10CertificationRequest csr = new PKCS10CertificationRequest(signatureAlgorithm, xname, pubKey, null, privKey); final String certReq = DatatypeConverter.printBase64Binary(csr.getEncoded()); if (withTag) { final StringBuilder sb = new StringBuilder(); sb.append(KeyStoreConstant.BEGIN_CERTIFICATE_REQUEST); sb.append("\n"); sb.append(certReq); sb.append("\n"); sb.append(KeyStoreConstant.END_CERTIFICATE_REQUEST); return sb.toString(); } return certReq; } LOG.info("{} KeyStore does not contain alias {}", keyStoreName, keyAlias); return null; } catch (NoSuchAlgorithmException | CertificateException | IOException | KeyStoreException | UnrecoverableKeyException | InvalidKeyException | NoSuchProviderException | SignatureException e) { LOG.error("Failed to generate certificate request {}", e.getMessage()); return null; } }
From source file:org.opendaylight.aaa.cert.impl.ODLMdsalKeyTool.java
License:Open Source License
public String generateCertificateReq(final KeyStore odlKeyStore, final String keyStorePwd, final String keyAlias, final String signAlg, final boolean withTag) { try {//from www.ja v a 2 s . com if (odlKeyStore.containsAlias(keyAlias)) { final X509Certificate odlCert = (X509Certificate) odlKeyStore.getCertificate(keyAlias); final PublicKey pubKey = odlCert.getPublicKey(); final PrivateKey privKey = (PrivateKey) odlKeyStore.getKey(keyAlias, keyStorePwd.toCharArray()); final String subject = odlCert.getSubjectDN().getName(); final X509Name xname = new X509Name(subject); final String signatureAlgorithm = signAlg; final PKCS10CertificationRequest csr = new PKCS10CertificationRequest(signatureAlgorithm, xname, pubKey, null, privKey); final String certReq = DatatypeConverter.printBase64Binary(csr.getEncoded()); if (withTag) { final StringBuilder sb = new StringBuilder(); sb.append(KeyStoreConstant.BEGIN_CERTIFICATE_REQUEST); sb.append("\n"); sb.append(certReq); sb.append("\n"); sb.append(KeyStoreConstant.END_CERTIFICATE_REQUEST); return sb.toString(); } return certReq; } LOG.info("KeyStore does not contain alias {}", keyAlias); return null; } catch (final NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | InvalidKeyException | NoSuchProviderException | SignatureException e) { LOG.error("Failed to generate certificate request", e); return null; } }
From source file:org.teragrid.portal.filebrowser.applet.util.proxy.MyProxyLogon.java
License:Open Source License
/** * Retrieves credentials from the MyProxy server. *///w w w .ja va 2 s. co m public void getCredentials() throws IOException, GeneralSecurityException { int numCertificates; KeyPairGenerator keyGenerator; PKCS10CertificationRequest pkcs10; CertificateFactory certFactory; if (this.state != State.LOGGEDON) { this.logon(); } keyGenerator = KeyPairGenerator.getInstance(keyAlg); keyGenerator.initialize(keySize); this.keypair = keyGenerator.genKeyPair(); pkcs10 = new PKCS10CertificationRequest(pkcs10SigAlgName, new X509Name(DN), this.keypair.getPublic(), null, this.keypair.getPrivate(), pkcs10Provider); this.socketOut.write(pkcs10.getEncoded()); this.socketOut.flush(); numCertificates = this.socketIn.read(); if (numCertificates == -1) { System.err.println("connection aborted"); System.exit(1); } else if (numCertificates == 0 || numCertificates < 0) { System.err.print("bad number of certificates sent by server: "); System.err.println(Integer.toString(numCertificates)); System.exit(1); } certFactory = CertificateFactory.getInstance("X.509"); this.certificateChain = certFactory.generateCertificates(this.socketIn); this.state = State.DONE; }
From source file:org.vpac.grix.model.certificate.CertificationRequest.java
License:Open Source License
/** * creates a encoded representation of the certification request. * // w ww .java2s .c o m * @return the certification request. */ public String getEncodedRequest() { String request_string = null; ByteArrayOutputStream out = new ByteArrayOutputStream(); // stolen from jglobus.jar: // nothing in it DERSet derset = new DERSet(); PublicKey pubkey = this.keypair.getPublicKey(); PrivateKey privkey = this.keypair.getPrivateKey().getPrivateKey(); PKCS10CertificationRequest request = null; try { // using the already implemented .getEncoded() function of // PKCS10CertificationRequest request = new PKCS10CertificationRequest(this.signatureAlgorithm, this.dn, pubkey, derset, privkey); PEMUtils.writeBase64(out, "-----BEGIN CERTIFICATE REQUEST-----", Base64.encode(request.getEncoded()), "-----END CERTIFICATE REQUEST-----"); request_string = out.toString(); out.close(); } catch (Exception e) { // TODO throw new SecurityProviderException("Could not write // certification request to file."); // e.printStackTrace(); myLogger.error(e); } return request_string; }
From source file:org.wso2.emm.agent.utils.CommonUtils.java
License:Open Source License
/** * Generates keys, CSR and certificates for the devices. * @param context - Application context. * @param listener - DeviceCertCreationListener which provide device . *///from w w w. j av a 2 s .co m public static void generateDeviceCertificate(final Context context, final DeviceCertCreationListener listener) throws AndroidAgentException { if (context.getFileStreamPath(Constants.DEVICE_CERTIFCATE_NAME).exists()) { try { listener.onDeviceCertCreated( new BufferedInputStream(context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME))); } catch (FileNotFoundException e) { Log.e(TAG, e.getMessage()); } } else { try { ServerConfig utils = new ServerConfig(); final KeyPair deviceKeyPair = KeyPairGenerator.getInstance(Constants.DEVICE_KEY_TYPE) .generateKeyPair(); X500Principal subject = new X500Principal(Constants.DEVICE_CSR_INFO); PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Constants.DEVICE_KEY_ALGO, subject, deviceKeyPair.getPublic(), null, deviceKeyPair.getPrivate()); EndPointInfo endPointInfo = new EndPointInfo(); endPointInfo.setHttpMethod(org.wso2.emm.agent.proxy.utils.Constants.HTTP_METHODS.POST); endPointInfo.setEndPoint(utils.getAPIServerURL(context) + Constants.SCEP_ENDPOINT); endPointInfo.setRequestParams(Base64.encodeToString(csr.getEncoded(), Base64.DEFAULT)); new APIController().invokeAPI(endPointInfo, new APIResultCallBack() { @Override public void onReceiveAPIResult(Map<String, String> result, int requestCode) { try { CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); InputStream in = new ByteArrayInputStream( Base64.decode(result.get("response"), Base64.DEFAULT)); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(null); keyStore.setKeyEntry(Constants.DEVICE_CERTIFCATE_ALIAS, (Key) deviceKeyPair.getPrivate(), Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray(), new java.security.cert.Certificate[] { cert }); keyStore.store(byteArrayOutputStream, Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray()); FileOutputStream outputStream = context.openFileOutput(Constants.DEVICE_CERTIFCATE_NAME, Context.MODE_PRIVATE); outputStream.write(byteArrayOutputStream.toByteArray()); byteArrayOutputStream.close(); outputStream.close(); try { listener.onDeviceCertCreated(new BufferedInputStream( context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME))); } catch (FileNotFoundException e) { Log.e(TAG, e.getMessage()); } } catch (CertificateException e) { Log.e(TAG, e.getMessage()); } catch (KeyStoreException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }, Constants.SCEP_REQUEST_CODE, context, true); } catch (NoSuchAlgorithmException e) { throw new AndroidAgentException("No algorithm for key generation", e); } catch (SignatureException e) { throw new AndroidAgentException("Invalid Signature", e); } catch (NoSuchProviderException e) { throw new AndroidAgentException("Invalid provider", e); } catch (InvalidKeyException e) { throw new AndroidAgentException("Invalid key", e); } } }