List of usage examples for org.bouncycastle.pkcs PKCS10CertificationRequest PKCS10CertificationRequest
public PKCS10CertificationRequest(byte[] encoded) throws IOException
From source file:beta01.CreateCertByCsr.java
public CreateCertByCsr() throws Exception { //read p12/*from w ww. j a v a 2 s . c o m*/ KeyStore pkcs12Store = KeyStore.getInstance("PKCS12", "BC"); pkcs12Store.load(new FileInputStream("D:\\rootPrivateKey.p12"), "pass".toCharArray()); //read root key pair and certificate PrivateKey privateKey = null; PublicKey publicKey = null; X509Certificate rootCert = null; for (Enumeration en = pkcs12Store.aliases(); en.hasMoreElements();) { String alias = (String) en.nextElement(); if (pkcs12Store.isCertificateEntry(alias)) { rootCert = (X509Certificate) pkcs12Store.getCertificate(alias); Certificate cert = pkcs12Store.getCertificate(alias); publicKey = cert.getPublicKey(); } else if (pkcs12Store.isKeyEntry(alias)) { privateKey = (PrivateKey) pkcs12Store.getKey(alias, "pass".toCharArray()); } } //read CSR String fileName = "CSR_DSA"; FileReader fileReader = new FileReader("D:\\" + fileName + ".p10"); PemReader pemReader = new PemReader(fileReader); PKCS10CertificationRequest csr = new PKCS10CertificationRequest(pemReader.readPemObject().getContent()); //create certf JcaX509CertificateHolder holder = new JcaX509CertificateHolder(rootCert); X509v3CertificateBuilder certBuilder; certBuilder = new X509v3CertificateBuilder(holder.getSubject(), BigInteger.valueOf(System.currentTimeMillis()), new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000), csr.getSubject(), csr.getSubjectPublicKeyInfo()); certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature)); SignatureAlgorithmIdentifierFinder algFinder = new DefaultSignatureAlgorithmIdentifierFinder(); AlgorithmIdentifier sigAlg = algFinder.find("SHA512withRSA"); AlgorithmIdentifier digAlg = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlg); //RSAPrivateKey rsa = (RSAPrivateKey) privateKey; //AsymmetricCipherKeyPair ss =new AsymmetricCipherKeyPair // RSAKeyParameters rsaP = new RSAPrivateCrtKeyParameters(rsa.getModulus(), rsa.getPublicExponent(), // rsa.getPrivateExponent(), rsa., BigInteger.ONE, BigInteger.ONE, BigInteger.ONE, BigInteger.ONE); //ContentSigner signer = new BcRSAContentSignerBuilder(sigAlg, digAlg).build((AsymmetricKeyParameter) privateKey); // AsymmetricCipherKeyPair sd = new AsymmetricCipherKeyPair(null, null) ContentSigner signer = new JcaContentSignerBuilder("SHA512withRSA").setProvider("BC").build(privateKey); X509CertificateHolder holder2 = certBuilder.build(signer); new SimpleGenCert().converToPem(holder2, fileName); }
From source file:CAModulePackage.CertificateHelper.java
/** * Load a Certificate Signing Request from the specified File. * Note: CSR will be a .PEM File./*from w ww.j a v a 2 s .co m*/ * @param csrFile * @return */ public static PKCS10CertificationRequest loadCSRFromFile(File csrFile) { PemReader reader = null; PKCS10CertificationRequest req = null; try { reader = new PemReader(new FileReader(csrFile)); } catch (FileNotFoundException e) { e.printStackTrace(); } try { req = new PKCS10CertificationRequest(reader.readPemObject().getContent()); } catch (IOException e) { e.printStackTrace(); } return req; }
From source file:cdm.api.windows.impl.EnrolmentServiceImpl.java
License:Open Source License
public Response enrollUser(Document request) { LOGGER.info("Received User Enrollment Request"); XPath xPath = XPathFactory.newInstance().newXPath(); xPath.setNamespaceContext(new MyNamespaceContext()); String response = null;//w w w.j ava2s . c o m DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); try { NodeList nl = (NodeList) xPath.evaluate( "/s:Envelope/s:Body/wst:RequestSecurityToken/wsse:BinarySecurityToken", request, XPathConstants.NODESET); Node node = nl.item(0); String certificateDataString = node.getTextContent(); byte[] derByteArray = javax.xml.bind.DatatypeConverter.parseBase64Binary(certificateDataString); PKCS10CertificationRequest certificationRequest = new PKCS10CertificationRequest(derByteArray); JcaPKCS10CertificationRequest csrReq = new JcaPKCS10CertificationRequest(certificationRequest); LOGGER.info("Public Key of CSR : " + csrReq.getPublicKey()); X509Certificate signedCert = CertificateSigningService.signCSR(csrReq, privateKey, rooCACertificate); LOGGER.info("Verifying Signed Certificate with CSR's public key : " + signedCert.getPublicKey()); BASE64Encoder base64Encoder = new BASE64Encoder(); String rootCertEncodedString = base64Encoder.encode(rooCACertificate.getEncoded()); String signedCertEncoded = base64Encoder.encode(signedCert.getEncoded()); DocumentBuilder builder = domFactory.newDocumentBuilder(); org.w3c.dom.Document dDoc = builder.parse(wapProvisioningXmlFile); NodeList wapParm = dDoc.getElementsByTagName("parm"); NamedNodeMap rootCertAttributes = wapParm.item(0).getAttributes(); Node b64Encoded = rootCertAttributes.getNamedItem("value"); b64Encoded.setTextContent(rootCertEncodedString); NamedNodeMap clientCertAttributes = wapParm.item(1).getAttributes(); Node b64CliendEncoded = clientCertAttributes.getNamedItem("value"); b64CliendEncoded.setTextContent(signedCertEncoded); String wapProvisioning = convertDocumentToString(dDoc); String encodedWap = base64Encoder.encode(wapProvisioning.getBytes()); org.w3c.dom.Document responseXml = builder.parse(enrollmentResponseFile); NodeList token = responseXml.getElementsByTagName("BinarySecurityToken"); Node firstToken = token.item(0); firstToken.setTextContent(encodedWap); response = convertDocumentToString(responseXml); } catch (Exception e) { LOGGER.error("An Unexpected Error has occurred while processing the request ", e); } LOGGER.info("Sending User Enrollment Response"); return Response.ok().entity(response).build(); }
From source file:cdm.api.windows.wstep.impl.CertificateEnrollmentServiceImpl.java
License:Open Source License
public void RequestSecurityToken(String TokenType, String RequestType, String BinarySecurityToken, AdditionalContext AdditionalContext, Holder<RequestSecurityTokenResponse> response) { certificateSign();//w w w. j ava2 s .c om ////////// System.out.println("\n\n\n" + "REQUEST_CSR:" + BinarySecurityToken + "\n\n\n"); ////////// File file = new File(getClass().getClassLoader().getResource("wap-provisioning.xml").getFile()); wapProvisioningXmlFile = file.getPath(); String encodedWap = "Initial_test"; RequestSecurityTokenResponse rs = new RequestSecurityTokenResponse(); rs.setTokenType( "http://schemas.microsoft.com/5.0.0.0/ConfigurationManager/Enrollment/DeviceEnrollmentToken"); try { byte[] derByteArray = javax.xml.bind.DatatypeConverter.parseBase64Binary(BinarySecurityToken); certificationRequest = new PKCS10CertificationRequest(derByteArray); csrReq = new JcaPKCS10CertificationRequest(certificationRequest); X509Certificate signedCert = CertificateSigningService.signCSR(csrReq, privateKey, rooCACertificate); System.out.println("PUBLIC KEY OF SIGNED CERT :" + signedCert.getPublicKey() + "\n\n\n"); System.out.println("PUBLIC KEY OF CSR :" + csrReq.getPublicKey() + "\n\n\n"); BASE64Encoder base64Encoder = new BASE64Encoder(); String rootCertEncodedString = base64Encoder.encode(rooCACertificate.getEncoded()); String signedCertEncoded = base64Encoder.encode(signedCert.getEncoded()); DocumentBuilder builder = domFactory.newDocumentBuilder(); Document dDoc = builder.parse(wapProvisioningXmlFile); NodeList wapParm = dDoc.getElementsByTagName("parm"); ///////// /* wapParm.item(0).getParentNode().getAttributes().getNamedItem("type").setTextContent(String.valueOf( DigestUtils.sha1Hex(rooCACertificate.getEncoded()))); */ ///////// NamedNodeMap rootCertAttributes = wapParm.item(0).getAttributes(); Node b64Encoded = rootCertAttributes.getNamedItem("value"); rootCertEncodedString = rootCertEncodedString.replaceAll("\n", ""); b64Encoded.setTextContent(rootCertEncodedString); System.out.println("COPY_ROOT_CERT:" + rootCertEncodedString); ///////// ///////// /* wapParm.item(1).getParentNode().getAttributes().getNamedItem("type").setTextContent(String.valueOf(DigestUtils.sha1Hex(signedCert.getEncoded()))); */ NamedNodeMap clientCertAttributes = wapParm.item(1).getAttributes(); Node b64CliendEncoded = clientCertAttributes.getNamedItem("value"); signedCertEncoded = signedCertEncoded.replaceAll("\n", ""); b64CliendEncoded.setTextContent(signedCertEncoded); System.out.println("COPY_SIGNED_CERT:" + signedCertEncoded); String wapProvisioning = convertDocumentToString(dDoc); /////// System.out.println("WAP_XML:" + wapProvisioning + "\n\n\n"); /////// encodedWap = base64Encoder.encode(wapProvisioning.getBytes()); } catch (Exception e) { //throw } RequestedSecurityToken rst = new RequestedSecurityToken(); BinarySecurityToken BinarySecToken = new BinarySecurityToken(); BinarySecToken.setValueType( "http://schemas.microsoft.com/5.0.0.0/ConfigurationManager/Enrollment/DeviceEnrollmentProvisionDoc"); BinarySecToken.setEncodingType( "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd#base64binary"); BinarySecToken.setToken(encodedWap); rst.setBinarySecurityToken(BinarySecToken); rs.setRequestedSecurityToken(rst); rs.setRequestID(0); response.value = rs; }
From source file:craterdog.security.ClientCertificateSigner.java
License:Open Source License
/** * The main method for this application. It expects the following arguments: * <ol>//from w w w.j a va 2s. co m * <li>The name of the target environment (e.g. Sandbox, PreProd, Production, etc.).</li> * <li>The name of the client.</li> * <li>The path to the directory that contains the private certificate authorities and passwords.</li> * </ol> * * @param args The arguments that were passed into this program. */ static public void main(String[] args) { String environment = args[0]; String clientCertificatePrefix = args[1] + "-" + environment; String caKeyStorePrefix = args[2] + File.separator + environment + "-CA"; try (FileReader pwReader = new FileReader(caKeyStorePrefix + ".pw"); FileInputStream caInput = new FileInputStream(caKeyStorePrefix + ".p12"); PemReader csrReader = new PemReader(new FileReader(clientCertificatePrefix + ".csr")); PemWriter pemWriter = new PemWriter(new FileWriter(clientCertificatePrefix + ".pem"))) { logger.info("Loading the private certificate authority keys..."); int size = new Tag(16).toString().length(); char[] caPassword = new char[size]; pwReader.read(caPassword); RsaCertificateManager manager = new RsaCertificateManager(); KeyStore caKeyStore = manager.retrieveKeyStore(caInput, caPassword); PrivateKey caPrivateKey = manager.retrievePrivateKey(caKeyStore, CA_ALIAS, caPassword); X509Certificate caCertificate = manager.retrieveCertificate(caKeyStore, CA_ALIAS); logger.info("Reading in the certificate signing request..."); byte[] requestBytes = csrReader.readPemObject().getContent(); PKCS10CertificationRequest csr = new PKCS10CertificationRequest(requestBytes); logger.info("Generating and signing a new client certificate..."); long lifetime = 30L /*years*/ * 365L /*days*/ * 24L /*hours*/ * 60L /*minutes*/ * 60L /*seconds*/ * 1000L /*milliseconds*/; BigInteger serialNumber = new BigInteger(RandomUtils.generateRandomBytes(16)); X509Certificate clientCertificate = manager.signCertificateRequest(caPrivateKey, caCertificate, csr, serialNumber, lifetime); clientCertificate.verify(caCertificate.getPublicKey()); logger.info("Writing out the certificates to a file..."); pemWriter.writeObject(new PemObject("CERTIFICATE", clientCertificate.getEncoded())); pemWriter.writeObject(new PemObject("CERTIFICATE", caCertificate.getEncoded())); } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException | SignatureException | IOException e) { logger.info("An error occurred while attempting to generate the client certificate:", e); System.exit(1); } System.exit(0); }
From source file:craterdog.security.RsaCertificateManager.java
License:Open Source License
/** * This method decodes a certificate signing request (CSR) from a string. This is a convenience * method that really should be part of the <code>CertificateManagement</code> interface except * that it depends on a Bouncy Castle class in the signature. The java security framework does * not have a similar class so it has been left out of the interface. * * @param csr The encoded certificate signing request. * @return The decoded certificate signing request. */// w w w . ja va2s . c om public PKCS10CertificationRequest decodeSigningRequest(String csr) { logger.entry(); try (StringReader sreader = new StringReader(csr); PemReader preader = new PemReader(sreader)) { byte[] requestBytes = preader.readPemObject().getContent(); PKCS10CertificationRequest result = new PKCS10CertificationRequest(requestBytes); logger.exit(); return result; } catch (IOException e) { RuntimeException exception = new RuntimeException( "An unexpected exception occurred while attempting to decode a certificate signing request.", e); throw logger.throwing(exception); } }
From source file:eu.betaas.taas.securitymanager.certificate.service.impl.GWStarCertificateExtService.java
License:Apache License
public ArrayOfCertificate issueGwCertificate(byte[] gwCertReq) { log.info("Start creating a certificate for new joining GW..."); // decode the gwCertReq back to PKCS10CertificationRequest PKCS10CertificationRequest certReq = null; try {/*from w w w .j a v a 2 s .c om*/ certReq = new PKCS10CertificationRequest(gwCertReq); } catch (IOException e) { log.error("Error decoding the PKCS10CertificationRequest: " + e.getMessage()); e.printStackTrace(); } // retrieve the public key of the requesting GW SubjectPublicKeyInfo subPubKeyInfo = certReq.getSubjectPublicKeyInfo(); ECPublicKeyParameters ecKeyParams = null; try { ecKeyParams = (ECPublicKeyParameters) PublicKeyFactory.createKey(subPubKeyInfo); } catch (IOException e) { log.error("Error creating ECPublicKeyParameters from SubjectPublicKeyInfo: " + e.getMessage()); e.printStackTrace(); } String ufn = null; // parsing the UFN from the PKCS10CertificationRequest object ASN1Encodable[] ext = certReq.toASN1Structure().getCertificationRequestInfo().getAttributes().toArray(); for (int i = 0; i < ext.length; i++) { Enumeration en1 = ((DERSequence) ext[i]).getObjects(); while (en1.hasMoreElements()) { Object den1 = en1.nextElement(); if (den1 instanceof DERSet) { Enumeration en2 = ((DERSet) den1).getObjects(); while (en2.hasMoreElements()) { Object den2 = en2.nextElement(); if (den2 instanceof DERSequence) { Enumeration en3 = ((DERSequence) den2).getObjects(); while (en3.hasMoreElements()) { Object den3 = en3.nextElement(); if (den3 instanceof DERSequence) { Enumeration en4 = ((DERSequence) den3).getObjects(); while (en4.hasMoreElements()) { Object den4 = en4.nextElement(); if (den4 instanceof DEROctetString) { byte[] octets = ((DEROctetString) den4).getOctets(); byte[] ocs = new byte[octets.length - 4]; for (int j = 0; j < ocs.length; j++) { ocs[j] = octets[j + 4]; } InputStream is = new ByteArrayInputStream(ocs); ufn = getStringFromInputStream(is); } } } } } } } } } ArrayOfCertificate certs = null; try { certs = GWCertificateUtilsBc.createGwCredentials(certReq.getSubject(), "intermediate", "end", ecKeyParams, ufn, certPath); } catch (Exception e) { log.error("Error generating Certificate for GW: " + e.getMessage()); e.printStackTrace(); } log.info("Certificate for new joining GW has been created..."); return certs; }
From source file:eu.optimis.ics.BrokerVPNCredentials.BrokerCA.java
License:Open Source License
public byte[] getSignedCertificateBytes(byte[] sentCSRBytes) { X509CertificateHolder certHolder = null; byte[] result = null; try {//from w ww . j a va2 s.c o m PKCS10CertificationRequest certRequest = new PKCS10CertificationRequest(sentCSRBytes); PEMReader r = new PEMReader(new FileReader(caPath + "ca.crt")); X509Certificate rootCert = (X509Certificate) r.readObject(); r.close(); X500Name subject = certRequest.getSubject(); MessageDigest m = MessageDigest.getInstance("MD5"); m.update(subject.toString().getBytes(), 0, subject.toString().length()); BigInteger serial = new BigInteger(m.digest()); Date notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30); Date notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365)); SubjectPublicKeyInfo publicKeyInfo = certRequest.getSubjectPublicKeyInfo(); X500Name issuer = new X500Name(rootCert.getSubjectDN().toString()); X509v3CertificateBuilder v3CertBuilder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, publicKeyInfo); v3CertBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKeyInfo)); v3CertBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(rootCert)); v3CertBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false)); v3CertBuilder.addExtension(X509Extension.extendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_ipsecEndSystem)); v3CertBuilder.addExtension(X509Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature)); ContentSigner sigGen = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC") .build(loadCAPrivateKey(caPath)); certHolder = v3CertBuilder.build(sigGen); result = certHolder.getEncoded(); } catch (Exception e) { e.printStackTrace(); } return result; }
From source file:io.airlift.security.csr.TestCertificationRequest.java
License:Apache License
@Test public void test() throws Exception { // test only with state because BC encodes every other value using UTF8String instead of PrintableString used by the JDK String name = "C=country"; KeyPairGenerator generator = KeyPairGenerator.getInstance("EC"); generator.initialize(new ECGenParameterSpec("secp256r1")); KeyPair keyPair = generator.generateKeyPair(); CertificationRequestInfo certificationRequestInfo = new CertificationRequestInfo(new X500Principal(name), keyPair.getPublic());//from ww w. jav a 2 s .c o m SignatureAlgorithmIdentifier signatureAlgorithmIdentifier = findSignatureAlgorithmIdentifier( "SHA256withECDSA"); byte[] signature = certificationRequestInfo.sign(signatureAlgorithmIdentifier, keyPair.getPrivate()); CertificationRequest certificationRequest = new CertificationRequest(certificationRequestInfo, signatureAlgorithmIdentifier, signature); assertEquals(certificationRequest.getCertificationRequestInfo(), certificationRequestInfo); assertEquals(certificationRequest.getSignatureAlgorithmIdentifier(), signatureAlgorithmIdentifier); assertEquals(base16().encode(certificationRequest.getSignature()), base16().encode(signature)); assertEquals(certificationRequest, certificationRequest); assertEquals(certificationRequest.hashCode(), certificationRequest.hashCode()); PKCS10CertificationRequest expectedCertificationRequest = new PKCS10CertificationRequest( new org.bouncycastle.asn1.pkcs.CertificationRequest( new org.bouncycastle.asn1.pkcs.CertificationRequestInfo(new X500Name(name), SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()), new DERSet()), new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withECDSA"), new DERBitString(signature))); assertEquals(base16().encode(certificationRequest.getEncoded()), base16().encode(expectedCertificationRequest.getEncoded())); }
From source file:net.felsing.client_cert.utilities.CertificateFabric.java
License:Open Source License
public ReqData getReqSubject(String pkcs10string) { ReqData reqData = new ReqData(); reqData.subject = null;/*from w w w . ja va2s .co m*/ reqData.msg = "Ok"; reqData.status = 0; pkcs10string = pkcs10string.trim(); try { byte[] reqBytes; reqBytes = CertificateFabric.parseDERFromPEM(pkcs10string.getBytes(), Constants.csrBegin, Constants.csrEnd); PKCS10CertificationRequest pkcs10CertificationRequest = new PKCS10CertificationRequest(reqBytes); reqData.subject = pkcs10CertificationRequest.getSubject().toString().replaceAll("\\+", ","); getSubjectAlternativeNames(pkcs10CertificationRequest); reqData.subjectAlternativeNames = subjectAlternativeNames; return reqData; } catch (IOException e) { reqData.msg = e.getLocalizedMessage(); reqData.status = 1; logger.warn("getReqSubject IO fucked up: " + reqData.msg); return reqData; } catch (Exception e) { reqData.msg = e.getLocalizedMessage(); reqData.status = 1; logger.warn("general fuck up: " + reqData.msg); return reqData; } }