List of usage examples for org.bouncycastle.jce.netscape NetscapeCertRequest getPublicKey
public PublicKey getPublicKey()
From source file:org.cesecore.certificates.certificate.request.RequestMessageUtils.java
License:Open Source License
public static RequestMessage getSimpleRequestMessageFromType(final String username, final String password, final String req, final int reqType) throws SignRequestSignatureException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, IOException, SignatureException, InvalidKeySpecException, ParseException, ConstructionException, NoSuchFieldException { RequestMessage ret = null;/* w w w . j a v a 2s . c o m*/ if (reqType == CertificateConstants.CERT_REQ_TYPE_PKCS10) { final RequestMessage pkcs10req = RequestMessageUtils.genPKCS10RequestMessage(req.getBytes()); final PublicKey pubKey = pkcs10req.getRequestPublicKey(); SimpleRequestMessage simplereq = new SimpleRequestMessage(pubKey, username, password); final Extensions ext = pkcs10req.getRequestExtensions(); simplereq.setRequestExtensions(ext); ret = simplereq; } else if (reqType == CertificateConstants.CERT_REQ_TYPE_SPKAC) { byte[] reqBytes = req.getBytes(); if (reqBytes != null) { if (log.isDebugEnabled()) { log.debug("Received NS request: " + new String(reqBytes)); } byte[] buffer = Base64.decode(reqBytes); if (buffer == null) { return null; } ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(buffer)); ASN1Sequence spkacSeq = (ASN1Sequence) in.readObject(); in.close(); NetscapeCertRequest nscr = new NetscapeCertRequest(spkacSeq); // Verify POPO, we don't care about the challenge, it's not important. nscr.setChallenge("challenge"); if (nscr.verify("challenge") == false) { if (log.isDebugEnabled()) { log.debug("SPKAC POPO verification Failed"); } throw new SignRequestSignatureException( "Invalid signature in NetscapeCertRequest, popo-verification failed."); } if (log.isDebugEnabled()) { log.debug("POPO verification successful"); } PublicKey pubKey = nscr.getPublicKey(); ret = new SimpleRequestMessage(pubKey, username, password); } } else if (reqType == CertificateConstants.CERT_REQ_TYPE_CRMF) { byte[] request = Base64.decode(req.getBytes()); ASN1InputStream in = new ASN1InputStream(request); try { ASN1Sequence crmfSeq = (ASN1Sequence) in.readObject(); ASN1Sequence reqSeq = (ASN1Sequence) ((ASN1Sequence) crmfSeq.getObjectAt(0)).getObjectAt(0); CertRequest certReq = CertRequest.getInstance(reqSeq); SubjectPublicKeyInfo pKeyInfo = certReq.getCertTemplate().getPublicKey(); KeyFactory keyFact = KeyFactory.getInstance("RSA", "BC"); KeySpec keySpec = new X509EncodedKeySpec(pKeyInfo.getEncoded()); PublicKey pubKey = keyFact.generatePublic(keySpec); // just check it's ok SimpleRequestMessage simplereq = new SimpleRequestMessage(pubKey, username, password); Extensions ext = certReq.getCertTemplate().getExtensions(); simplereq.setRequestExtensions(ext); ret = simplereq; } finally { in.close(); } // a simple crmf is not a complete PKI message, as desired by the CrmfRequestMessage class //PKIMessage msg = PKIMessage.getInstance(new ASN1InputStream(new ByteArrayInputStream(request)).readObject()); //CrmfRequestMessage reqmsg = new CrmfRequestMessage(msg, null, true, null); //imsg = reqmsg; } else if (reqType == CertificateConstants.CERT_REQ_TYPE_PUBLICKEY) { byte[] request; // Request can be Base64 encoded or in PEM format try { request = FileTools.getBytesFromPEM(req.getBytes(), CertTools.BEGIN_PUBLIC_KEY, CertTools.END_PUBLIC_KEY); } catch (IOException ex) { try { request = Base64.decode(req.getBytes()); if (request == null) { throw new IOException("Base64 decode of buffer returns null"); } } catch (DecoderException de) { throw new IOException("Base64 decode fails, message not base64 encoded: " + de.getMessage()); } } final PublicKey pubKey = KeyTools.getPublicKeyFromBytes(request); ret = new SimpleRequestMessage(pubKey, username, password); } else if (reqType == CertificateConstants.CERT_REQ_TYPE_CVC) { CVCObject parsedObject = CertificateParser.parseCVCObject(Base64.decode(req.getBytes())); // We will handle both the case if the request is an authenticated request, i.e. with an outer signature // and when the request is missing the (optional) outer signature. CVCertificate cvccert = null; if (parsedObject instanceof CVCAuthenticatedRequest) { CVCAuthenticatedRequest cvcreq = (CVCAuthenticatedRequest) parsedObject; cvccert = cvcreq.getRequest(); } else { cvccert = (CVCertificate) parsedObject; } CVCRequestMessage reqmsg = new CVCRequestMessage(cvccert.getDEREncoded()); reqmsg.setUsername(username); reqmsg.setPassword(password); // Popo is really actually verified by the CA (in SignSessionBean) as well if (reqmsg.verify() == false) { if (log.isDebugEnabled()) { log.debug("CVC POPO verification Failed"); } throw new SignRequestSignatureException( "Invalid inner signature in CVCRequest, popo-verification failed."); } else { if (log.isDebugEnabled()) { log.debug("POPO verification successful"); } } ret = reqmsg; } return ret; }
From source file:org.ejbca.core.ejb.ra.CertificateRequestSessionBean.java
License:Open Source License
@Override public byte[] processCertReq(Admin admin, UserDataVO userdata, String req, int reqType, String hardTokenSN, int responseType) throws CADoesntExistsException, AuthorizationDeniedException, NotFoundException, InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException, SignatureException, IOException, ObjectNotFoundException, CertificateException, UserDoesntFullfillEndEntityProfile, ApprovalException, EjbcaException { byte[] retval = null; // Check tokentype if (userdata.getTokenType() != SecConst.TOKEN_SOFT_BROWSERGEN) { throw new WrongTokenTypeException( "Error: Wrong Token Type of user, must be 'USERGENERATED' for PKCS10/SPKAC/CRMF/CVC requests"); }/*from ww w . j a va 2 s.c om*/ // This is the secret sauce, do the end entity handling automagically here before we get the cert addOrEditUser(admin, userdata, false, true); // Process request try { String password = userdata.getPassword(); String username = userdata.getUsername(); IRequestMessage imsg = null; if (reqType == SecConst.CERT_REQ_TYPE_PKCS10) { IRequestMessage pkcs10req = RequestMessageUtils.genPKCS10RequestMessage(req.getBytes()); PublicKey pubKey = pkcs10req.getRequestPublicKey(); imsg = new SimpleRequestMessage(pubKey, username, password); } else if (reqType == SecConst.CERT_REQ_TYPE_SPKAC) { // parts copied from request helper. byte[] reqBytes = req.getBytes(); if (reqBytes != null) { log.debug("Received NS request: " + new String(reqBytes)); byte[] buffer = Base64.decode(reqBytes); if (buffer == null) { return null; } ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(buffer)); ASN1Sequence spkacSeq = (ASN1Sequence) in.readObject(); in.close(); NetscapeCertRequest nscr = new NetscapeCertRequest(spkacSeq); // Verify POPO, we don't care about the challenge, it's not important. nscr.setChallenge("challenge"); if (nscr.verify("challenge") == false) { log.debug("POPO verification Failed"); throw new SignRequestSignatureException( "Invalid signature in NetscapeCertRequest, popo-verification failed."); } log.debug("POPO verification successful"); PublicKey pubKey = nscr.getPublicKey(); imsg = new SimpleRequestMessage(pubKey, username, password); } } else if (reqType == SecConst.CERT_REQ_TYPE_CRMF) { byte[] request = Base64.decode(req.getBytes()); ASN1InputStream in = new ASN1InputStream(request); ASN1Sequence crmfSeq = (ASN1Sequence) in.readObject(); ASN1Sequence reqSeq = (ASN1Sequence) ((ASN1Sequence) crmfSeq.getObjectAt(0)).getObjectAt(0); CertRequest certReq = new CertRequest(reqSeq); SubjectPublicKeyInfo pKeyInfo = certReq.getCertTemplate().getPublicKey(); KeyFactory keyFact = KeyFactory.getInstance("RSA", "BC"); KeySpec keySpec = new X509EncodedKeySpec(pKeyInfo.getEncoded()); PublicKey pubKey = keyFact.generatePublic(keySpec); // just check it's ok imsg = new SimpleRequestMessage(pubKey, username, password); // a simple crmf is not a complete PKI message, as desired by the CrmfRequestMessage class //PKIMessage msg = PKIMessage.getInstance(new ASN1InputStream(new ByteArrayInputStream(request)).readObject()); //CrmfRequestMessage reqmsg = new CrmfRequestMessage(msg, null, true, null); //imsg = reqmsg; } else if (reqType == SecConst.CERT_REQ_TYPE_PUBLICKEY) { byte[] request; // Request can be Base64 encoded or in PEM format try { request = FileTools.getBytesFromPEM(req.getBytes(), CertTools.BEGIN_PUBLIC_KEY, CertTools.END_PUBLIC_KEY); } catch (IOException ex) { try { request = Base64.decode(req.getBytes()); if (request == null) { throw new IOException("Base64 decode of buffer returns null"); } } catch (ArrayIndexOutOfBoundsException ae) { throw new IOException( "Base64 decode fails, message not base64 encoded: " + ae.getMessage()); } } final ASN1InputStream in = new ASN1InputStream(request); final SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(in.readObject()); final AlgorithmIdentifier keyAlg = keyInfo.getAlgorithmId(); final X509EncodedKeySpec xKeySpec = new X509EncodedKeySpec(new DERBitString(keyInfo).getBytes()); final KeyFactory keyFact = KeyFactory.getInstance(keyAlg.getObjectId().getId(), "BC"); final PublicKey pubKey = keyFact.generatePublic(xKeySpec); imsg = new SimpleRequestMessage(pubKey, username, password); } if (imsg != null) { retval = getCertResponseFromPublicKey(admin, imsg, hardTokenSN, responseType, userdata); } } catch (NotFoundException e) { sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically throw e; } catch (InvalidKeyException e) { sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically throw e; } catch (NoSuchAlgorithmException e) { sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically throw e; } catch (InvalidKeySpecException e) { sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically throw e; } catch (NoSuchProviderException e) { sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically throw e; } catch (SignatureException e) { sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically throw e; } catch (IOException e) { sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically throw e; } catch (CertificateException e) { sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically throw e; } catch (EjbcaException e) { sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically throw e; } return retval; }
From source file:org.ejbca.extra.caservice.processor.CertificateRequestRequestProcessor.java
License:Open Source License
/** * Extracts the certificate signing request type and requests a new certificate using the provided credentials. *//*from w w w . j a v a2 s. c o m*/ private CertificateRequestResponse processCertificateRequestRequest(Admin admin, CertificateRequestRequest submessage) { if (log.isDebugEnabled()) { log.debug("Processing CertificateRequestRequest"); } try { byte[] result = null; if (submessage.createOrEditUser()) { if (log.isDebugEnabled()) { log.debug("createOrEditUser == true, will use one-shot request processing."); } final UserDataVO userdatavo = getUserDataVO(admin, submessage); final String requestData = new String(submessage.getRequestData()); final int requestTypeInt = submessage.getRequestType(); final int responseTypeInt = submessage.getResponseType(); final String hardTokenSN = null; result = certificateRequestSession.processCertReq(admin, userdatavo, requestData, requestTypeInt, hardTokenSN, responseTypeInt); } else { switch (submessage.getRequestType()) { case CertificateRequestRequest.REQUEST_TYPE_PKCS10: Certificate cert = null; PKCS10RequestMessage req = RequestMessageUtils .genPKCS10RequestMessage(submessage.getRequestData()); req.setUsername(submessage.getUsername()); req.setPassword(submessage.getPassword()); IResponseMessage resp = signSession.createCertificate(admin, req, X509ResponseMessage.class, null); cert = CertTools.getCertfromByteArray(resp.getResponseMessage()); if (submessage.getResponseType() == CertificateRequestRequest.RESPONSE_TYPE_CERTIFICATE) { result = cert.getEncoded(); } else { result = signSession.createPKCS7(admin, cert, true); } break; case CertificateRequestRequest.REQUEST_TYPE_SPKAC: ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(submessage.getRequestData())); ASN1Sequence spkac = (ASN1Sequence) in.readObject(); in.close(); NetscapeCertRequest nscr = new NetscapeCertRequest(spkac); cert = signSession.createCertificate(admin, submessage.getUsername(), submessage.getPassword(), nscr.getPublicKey()); if (submessage.getResponseType() == CertificateRequestRequest.RESPONSE_TYPE_CERTIFICATE) { result = cert.getEncoded(); } else if (submessage.getResponseType() == CertificateRequestRequest.RESPONSE_TYPE_PKCS7) { result = signSession.createPKCS7(admin, cert, true); } else if (submessage .getResponseType() == CertificateRequestRequest.RESPONSE_TYPE_PKCS7WITHCHAIN) { // Read certificate chain ArrayList<Certificate> certList = new ArrayList<Certificate>(); certList.add(cert); certList.addAll( caSession.getCA(Admin.getInternalAdmin(), CertTools.getIssuerDN(cert).hashCode()) .getCertificateChain()); // Create large certificate-only PKCS7 CertificateFactory cf = CertificateFactory.getInstance("X.509"); CertPath certPath = cf .generateCertPath(new ByteArrayInputStream(CertTools.getPEMFromCerts(certList))); result = certPath.getEncoded("PKCS7"); } else { return new CertificateRequestResponse(submessage.getRequestId(), false, MSG_UNSUPPORTED_RESPONSE_TYPE, null, null); } break; case CertificateRequestRequest.REQUEST_TYPE_CRMF: // Extract request in a format that EJBCA can process CertReqMessages certReqMessages = CertReqMessages .getInstance(new ASN1InputStream(submessage.getRequestData()).readObject()); PKIMessage msg = new PKIMessage(new PKIHeader(new DERInteger(2), new GeneralName(new X509Name("CN=unused")), new GeneralName(new X509Name("CN=unused"))), new PKIBody(certReqMessages, 2)); // [2] CertReqMessages --Certification Request CrmfRequestMessage crmfReq = new CrmfRequestMessage(msg, null, true, null); crmfReq.setUsername(submessage.getUsername()); crmfReq.setPassword(submessage.getPassword()); // Request and extract certificate from response IResponseMessage response = signSession.createCertificate(admin, crmfReq, org.ejbca.core.protocol.cmp.CmpResponseMessage.class, null); ASN1InputStream ais = new ASN1InputStream( new ByteArrayInputStream(response.getResponseMessage())); CertRepMessage certRepMessage = PKIMessage.getInstance(ais.readObject()).getBody().getCp(); InputStream inStream = new ByteArrayInputStream(certRepMessage.getResponse(0) .getCertifiedKeyPair().getCertOrEncCert().getCertificate().getEncoded()); cert = CertificateFactory.getInstance("X.509").generateCertificate(inStream); inStream.close(); // Convert to the right response type if (submessage.getResponseType() == CertificateRequestRequest.RESPONSE_TYPE_CERTIFICATE) { result = cert.getEncoded(); } else if (submessage.getResponseType() == CertificateRequestRequest.RESPONSE_TYPE_PKCS7) { result = signSession.createPKCS7(admin, cert, false); } else if (submessage .getResponseType() == CertificateRequestRequest.RESPONSE_TYPE_PKCS7WITHCHAIN) { // Read certificate chain ArrayList<Certificate> certList = new ArrayList<Certificate>(); certList.add(cert); certList.addAll( caSession.getCA(Admin.getInternalAdmin(), CertTools.getIssuerDN(cert).hashCode()) .getCertificateChain()); // Create large certificate-only PKCS7 CertificateFactory cf = CertificateFactory.getInstance("X.509"); CertPath certPath = cf .generateCertPath(new ByteArrayInputStream(CertTools.getPEMFromCerts(certList))); result = certPath.getEncoded("PKCS7"); } else { return new CertificateRequestResponse(submessage.getRequestId(), false, MSG_UNSUPPORTED_RESPONSE_TYPE, null, null); } break; default: return new CertificateRequestResponse(submessage.getRequestId(), false, MSG_UNSUPPORTED_REQUEST_TYPE, null, null); } } // Return the response when we have response data (byte[]) return new CertificateRequestResponse(submessage.getRequestId(), true, null, submessage.getResponseType(), result); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("External RA request generated an error: " + e.getMessage()); } return new CertificateRequestResponse(submessage.getRequestId(), false, "Error " + e.getMessage(), null, null); } }
From source file:org.ejbca.ui.web.RequestHelper.java
License:Open Source License
/** * Handles Firefox certificate request (KEYGEN), these are constructed as: <code> * SignedPublicKeyAndChallenge ::= SEQUENCE { publicKeyAndChallenge PublicKeyAndChallenge, * signatureAlgorithm AlgorithmIdentifier, signature BIT STRING }</code> PublicKey's * encoded-format has to be RSA X.509.//from w w w.j a v a2s . com * * @param signsession EJB session to signature bean. * @param reqBytes buffer holding te request from NS. * @param username username in EJBCA for authoriation. * @param password users password for authorization. * * @return byte[] containing DER-encoded certificate. * * @throws CesecoreException * @throws AuthorizationDeniedException * @throws EjbcaException * @throws CADoesntExistsException * @throws ObjectNotFoundException * @throws CertificateEncodingException * @throws NoSuchProviderException * @throws SignatureException * @throws NoSuchAlgorithmException * @throws InvalidKeyException */ public byte[] nsCertRequest(SignSessionLocal signsession, byte[] reqBytes, String username, String password) throws ObjectNotFoundException, CADoesntExistsException, EjbcaException, AuthorizationDeniedException, CesecoreException, CertificateEncodingException, InvalidKeyException, NoSuchAlgorithmException, SignatureException, NoSuchProviderException { byte[] buffer = Base64.decode(reqBytes); if (buffer == null) { return null; } ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(buffer)); ASN1Sequence spkac; try { spkac = (ASN1Sequence) in.readObject(); in.close(); } catch (IOException e) { throw new IllegalStateException("Unexpected IOException was caught.", e); } NetscapeCertRequest nscr = new NetscapeCertRequest(spkac); // Verify POPO, we don't care about the challenge, it's not important. nscr.setChallenge("challenge"); if (nscr.verify("challenge") == false) { throw new SignRequestSignatureException( "Invalid signature in NetscapeCertRequest, popo-verification failed."); } if (log.isDebugEnabled()) { log.debug("POPO verification successful"); } X509Certificate cert = (X509Certificate) signsession.createCertificate(administrator, username, password, nscr.getPublicKey()); if (log.isDebugEnabled()) { log.debug("Created certificate for " + username); } if (debug != null) { debug.print("<h4>Generated certificate:</h4>"); debug.printInsertLineBreaks(cert.toString().getBytes()); } return cert.getEncoded(); /* ECA-2065: the <keygen> specification doesn't say anything about the * returned certificate. Originally EJBCA used a PKCS7 container but * this has proved to be incompatible with Safari and Chrome. ECA-2065 * changes returned data to just a DER-encoded certificate which has * been verified to work in Firefox, Chrome and Safari. The mime-type * remains application/x-x509-user-certificate. Below is the deleted * code: // Don't include certificate chain in the PKCS7 to Firefox byte[] pkcs7 = signsession.createPKCS7(administrator, cert, false); log.debug("Created certificate (PKCS7) for " + username); if (debug != null) { debug.print("<h4>Generated certificate:</h4>"); debug.printInsertLineBreaks(cert.toString().getBytes()); } return pkcs7; */ }
From source file:org.xwiki.crypto.x509.internal.X509KeyService.java
License:Open Source License
/** * @param spkacSerialization a <a href="http://en.wikipedia.org/wiki/Spkac">SPKAC</a> Certificate Signing Request * @param daysOfValidity number of days before the certificate should become invalid. * @param webID the URL of the user's page. Used for FOAFSSL compatibility. * @param userName the String serialization of the user's page name. * @return 2 certificates, one a client cert and the other an authority cert which signed the client cert. * @throws GeneralSecurityException on errors * @see org.xwiki.crypto.CryptoService#certsFromSpkac(String, int) *//*from w w w .jav a2 s.co m*/ public XWikiX509Certificate[] certsFromSpkac(final String spkacSerialization, final int daysOfValidity, final String webID, final String userName) throws GeneralSecurityException { this.checkWebID(webID); if (spkacSerialization == null) { throw new InvalidParameterException("SPKAC parameter is null"); } NetscapeCertRequest certRequest = null; try { certRequest = new NetscapeCertRequest(Convert.fromBase64String(spkacSerialization)); } catch (Exception e) { throw new GeneralSecurityException("Failed to parse certificate request", e); } X509Certificate[] certs = this.keymaker.makeClientAndAuthorityCertificates(certRequest.getPublicKey(), daysOfValidity, true, webID, userName); return new XWikiX509Certificate[] { new XWikiX509Certificate(certs[0]), new XWikiX509Certificate(certs[1]) }; }