List of usage examples for java.security.cert X509Certificate getEncoded
public abstract byte[] getEncoded() throws CertificateEncodingException;
From source file:info.guardianproject.onionkit.trust.StrongTrustManager.java
public String getFingerprint(X509Certificate cert, String type) throws NoSuchAlgorithmException, CertificateEncodingException { MessageDigest md = MessageDigest.getInstance(type); byte[] publicKey = md.digest(cert.getEncoded()); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < publicKey.length; i++) { String appendString = Integer.toHexString(0xFF & publicKey[i]); if (appendString.length() == 1) hexString.append("0"); hexString.append(appendString);//from ww w . j a v a 2 s .c om hexString.append(' '); } return hexString.toString(); }
From source file:org.ejbca.ui.web.RequestHelper.java
/** * 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.// ww w .ja v a 2 s . c o m * * @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.codice.ddf.security.idp.server.IdpEndpointTest.java
@Test public void testProcessLoginPki() throws CertificateEncodingException, WSSecurityException { String samlRequest = authNRequestGet; HttpServletRequest request = mock(HttpServletRequest.class); X509Certificate x509Certificate = mock(X509Certificate.class); when(request.isSecure()).thenReturn(true); when(request.getRequestURL()).thenReturn(requestURL); when(request.getAttribute(ContextPolicy.ACTIVE_REALM)).thenReturn("*"); //dummy cert//from ww w . ja v a2 s.c o m when((X509Certificate[]) request.getAttribute(requestCertificateAttributeName)) .thenReturn(new X509Certificate[] { x509Certificate }); when(x509Certificate.getEncoded()).thenReturn(new byte[48]); Response response = idpEndpoint.processLogin(samlRequest, relayState, Idp.PKI, signatureAlgorithm, signature, SamlProtocol.REDIRECT_BINDING, request); assertThat(response.getEntity().toString(), containsString(ssoSAMLResponse)); assertThat(response.getEntity().toString(), containsString("RelayState=")); }
From source file:org.codice.ddf.security.idp.server.IdpEndpointTest.java
@Test public void testProcessLoginPkiPost() throws CertificateEncodingException { idpEndpoint.setStrictSignature(false); String samlRequest = authNRequestPkiPost; HttpServletRequest request = mock(HttpServletRequest.class); X509Certificate x509Certificate = mock(X509Certificate.class); when(request.isSecure()).thenReturn(true); when(request.getRequestURL()).thenReturn(requestURL); when(request.getAttribute(ContextPolicy.ACTIVE_REALM)).thenReturn("*"); //dummy cert/*w w w. j a v a 2s . com*/ when((X509Certificate[]) request.getAttribute(requestCertificateAttributeName)) .thenReturn(new X509Certificate[] { x509Certificate }); when(x509Certificate.getEncoded()).thenReturn(new byte[48]); Response response = idpEndpoint.processLogin(samlRequest, relayState, Idp.PKI, null, null, SamlProtocol.POST_BINDING, request); assertThat(response.getEntity().toString(), containsString("Form Submit")); assertThat(response.getEntity().toString(), containsString("SAMLResponse")); assertThat(response.getEntity().toString(), containsString("RelayState")); }
From source file:se.leap.bitmaskclient.ProviderAPI.java
private boolean loadCertificate(String cert_string) { try {/*ww w.ja va2 s . com*/ // API returns concatenated cert & key. Split them for OpenVPN options String certificateString = null, keyString = null; String[] certAndKey = cert_string.split("(?<=-\n)"); for (int i = 0; i < certAndKey.length - 1; i++) { if (certAndKey[i].contains("KEY")) { keyString = certAndKey[i++] + certAndKey[i]; } else if (certAndKey[i].contains("CERTIFICATE")) { certificateString = certAndKey[i++] + certAndKey[i]; } } RSAPrivateKey key = ConfigHelper.parseRsaKeyFromString(keyString); keyString = Base64.encodeToString(key.getEncoded(), Base64.DEFAULT); preferences.edit() .putString(Constants.PRIVATE_KEY, "-----BEGIN RSA PRIVATE KEY-----\n" + keyString + "-----END RSA PRIVATE KEY-----") .commit(); X509Certificate certificate = ConfigHelper.parseX509CertificateFromString(certificateString); certificateString = Base64.encodeToString(certificate.getEncoded(), Base64.DEFAULT); preferences.edit() .putString(Constants.CERTIFICATE, "-----BEGIN CERTIFICATE-----\n" + certificateString + "-----END CERTIFICATE-----") .commit(); return true; } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } }
From source file:org.apache.ws.security.message.token.SecurityTokenReference.java
/** * Sets the KeyIdentifier Element as a Thumbprint. * /*from w ww . j a v a 2 s .co m*/ * Takes a X509 certificate, computes its thumbprint using SHA-1, converts into base 64 and * inserts it into a <code>wsse:KeyIdentifier</code> element, which is placed in the * <code>wsse:SecurityTokenReference</code> element. * * @param cert * is the X509 certificate to get the thumbprint */ public void setKeyIdentifierThumb(X509Certificate cert) throws WSSecurityException { Document doc = this.element.getOwnerDocument(); MessageDigest sha = null; try { sha = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e1) { throw new WSSecurityException(WSSecurityException.FAILURE, "noSHA1availabe", null, e1); } sha.reset(); try { sha.update(cert.getEncoded()); } catch (CertificateEncodingException e1) { throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "encodeError", null, e1); } byte[] data = sha.digest(); org.w3c.dom.Text text = doc.createTextNode(Base64.encode(data)); createKeyIdentifier(doc, THUMB_URI, text, true); }
From source file:com.netscape.cms.publish.publishers.FileBasedPublisher.java
/** * Publishes a object to the ldap directory. * * @param conn a Ldap connection//w w w .j a va2 s . co m * (null if LDAP publishing is not enabled) * @param dn dn of the ldap entry to publish cert * (null if LDAP publishing is not enabled) * @param object object to publish * (java.security.cert.X509Certificate or, * java.security.cert.X509CRL) */ public void publish(LDAPConnection conn, String dn, Object object) throws ELdapException { CMS.debug("FileBasedPublisher: publish"); try { if (object instanceof X509Certificate) { X509Certificate cert = (X509Certificate) object; BigInteger sno = cert.getSerialNumber(); String name = mDir + File.separator + "cert-" + sno.toString(); if (mDerAttr) { FileOutputStream fos = null; try { String fileName = name + ".der"; fos = new FileOutputStream(fileName); fos.write(cert.getEncoded()); } finally { if (fos != null) fos.close(); } } if (mB64Attr) { String fileName = name + ".b64"; PrintStream ps = null; Base64OutputStream b64 = null; FileOutputStream fos = null; try { fos = new FileOutputStream(fileName); ByteArrayOutputStream output = new ByteArrayOutputStream(); b64 = new Base64OutputStream(new PrintStream(new FilterOutputStream(output))); b64.write(cert.getEncoded()); b64.flush(); ps = new PrintStream(fos); ps.print(output.toString("8859_1")); } finally { if (ps != null) { ps.close(); } if (b64 != null) { b64.close(); } if (fos != null) fos.close(); } } } else if (object instanceof X509CRL) { X509CRL crl = (X509CRL) object; String[] namePrefix = getCrlNamePrefix(crl, mTimeStamp.equals("GMT")); String baseName = mDir + File.separator + namePrefix[0]; String tempFile = baseName + ".temp"; ZipOutputStream zos = null; byte[] encodedArray = null; File destFile = null; String destName = null; File renameFile = null; if (mDerAttr) { FileOutputStream fos = null; try { fos = new FileOutputStream(tempFile); encodedArray = crl.getEncoded(); fos.write(encodedArray); } finally { if (fos != null) fos.close(); } if (mZipCRL) { try { zos = new ZipOutputStream(new FileOutputStream(baseName + ".zip")); zos.setLevel(mZipLevel); zos.putNextEntry(new ZipEntry(baseName + ".der")); zos.write(encodedArray, 0, encodedArray.length); zos.closeEntry(); } finally { if (zos != null) zos.close(); } } destName = baseName + ".der"; destFile = new File(destName); if (destFile.exists()) { destFile.delete(); } renameFile = new File(tempFile); renameFile.renameTo(destFile); if (mLatestCRL) { String linkExt = "."; if (mLinkExt != null && mLinkExt.length() > 0) { linkExt += mLinkExt; } else { linkExt += "der"; } String linkName = mDir + File.separator + namePrefix[1] + linkExt; createLink(linkName, destName); if (mZipCRL) { linkName = mDir + File.separator + namePrefix[1] + ".zip"; createLink(linkName, baseName + ".zip"); } } } // output base64 file if (mB64Attr == true) { if (encodedArray == null) encodedArray = crl.getEncoded(); FileOutputStream fos = null; try { fos = new FileOutputStream(tempFile); fos.write(Utils.base64encode(encodedArray, true).getBytes()); } finally { if (fos != null) fos.close(); } destName = baseName + ".b64"; destFile = new File(destName); if (destFile.exists()) { destFile.delete(); } renameFile = new File(tempFile); renameFile.renameTo(destFile); } purgeExpiredFiles(); purgeExcessFiles(); } } catch (IOException e) { mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_FILE_PUBLISHER_ERROR", e.toString())); } catch (CertificateEncodingException e) { mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_FILE_PUBLISHER_ERROR", e.toString())); } catch (CRLException e) { mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_FILE_PUBLISHER_ERROR", e.toString())); } }
From source file:org.codice.ddf.security.idp.server.IdpEndpointTest.java
@Test public void testPassiveLoginPki() throws SecurityServiceException, WSSecurityException, CertificateEncodingException { String samlRequest = authNRequestPassivePkiGet; HttpServletRequest request = mock(HttpServletRequest.class); X509Certificate x509Certificate = mock(X509Certificate.class); idpEndpoint.setStrictSignature(false); when(request.isSecure()).thenReturn(true); when(request.getRequestURL()).thenReturn(requestURL); when(request.getAttribute(ContextPolicy.ACTIVE_REALM)).thenReturn("*"); //dummy cert// w w w . j ava 2 s. c o m when((X509Certificate[]) request.getAttribute(requestCertificateAttributeName)) .thenReturn(new X509Certificate[] { x509Certificate }); when(x509Certificate.getEncoded()).thenReturn(new byte[48]); Response response = idpEndpoint.showGetLogin(samlRequest, relayState, signatureAlgorithm, signature, request); assertThat(response.getEntity().toString(), containsString(ssoSAMLResponse)); assertThat(response.getEntity().toString(), containsString("RelayState=")); }
From source file:org.codice.ddf.security.idp.server.IdpEndpointTest.java
@Test public void testPassiveLoginPkiPost() throws SecurityServiceException, WSSecurityException, CertificateEncodingException { String samlRequest = authNRequestPassivePkiPost; HttpServletRequest request = mock(HttpServletRequest.class); X509Certificate x509Certificate = mock(X509Certificate.class); idpEndpoint.setStrictSignature(false); when(request.isSecure()).thenReturn(true); when(request.getRequestURL()).thenReturn(requestURL); when(request.getAttribute(ContextPolicy.ACTIVE_REALM)).thenReturn("*"); //dummy cert//from w ww. j a v a2 s . co m when((X509Certificate[]) request.getAttribute(requestCertificateAttributeName)) .thenReturn(new X509Certificate[] { x509Certificate }); when(x509Certificate.getEncoded()).thenReturn(new byte[48]); Response response = idpEndpoint.showPostLogin(samlRequest, relayState, request); assertThat(response.getEntity().toString(), containsString("Form Submit")); assertThat(response.getEntity().toString(), containsString("SAMLResponse")); assertThat(response.getEntity().toString(), containsString("RelayState")); }
From source file:org.ejbca.extra.ra.ScepRAServlet.java
private void service(String operation, String message, String remoteAddr, HttpServletResponse response) throws IOException { try {/* w w w .j av a2s . co m*/ if ((operation == null) || (message == null)) { log.error("Got request missing operation and/or message parameters."); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameters 'operation' and 'message' must be supplied!"); return; } log.debug("Got request '" + operation + "'"); log.debug("Message: " + message); log.debug("Operation is : " + operation); String alias = scepraks.getAlias(); log.debug("SCEP RA Keystore alias : " + alias); KeyStore raks = scepraks.getKeyStore(); Certificate[] chain = raks.getCertificateChain(alias); X509Certificate cacert = null; if (chain.length > 1) { // This should absolutely be more than one! cacert = (X509Certificate) chain[1]; } else { log.error( "Certificate chain in RA keystore is only 1 certificate long! This is en error, because there should also be CA certificates."); } X509Certificate racert = (X509Certificate) raks.getCertificate(alias); String kspwd = ExtraConfiguration.instance() .getString(ExtraConfiguration.SCEPKEYSTOREPWD + keyStoreNumber); PrivateKey rapriv = (PrivateKey) raks.getKey(alias, kspwd.toCharArray()); if (operation.equals("PKIOperation")) { byte[] scepmsg = Base64.decode(message.getBytes()); // Read the message end get the cert, this also checks authorization boolean includeCACert = true; if (StringUtils.equals("0", getInitParameter("includeCACert"))) { includeCACert = false; } byte[] reply = null; ScepRequestMessage reqmsg = new ScepRequestMessage(scepmsg, includeCACert); String transId = reqmsg.getTransactionId(); log.debug("Received a message of type: " + reqmsg.getMessageType()); if (reqmsg.getMessageType() == ScepRequestMessage.SCEP_TYPE_GETCERTINITIAL) { log.info("Received a GetCertInitial message from host: " + remoteAddr); Message msg = null; try { msg = msgHome.findByMessageId(transId); } catch (Exception e) { // TODO: internal resources log.info("Error looking for message with transId " + transId + " :", e); } if (msg != null) { if (msg.getStatus().equals(Message.STATUS_PROCESSED)) { log.debug("Request is processed with status: " + msg.getStatus()); SubMessages submessagesresp = msg.getSubMessages(null, null, null); Iterator<ISubMessage> iter = submessagesresp.getSubMessages().iterator(); PKCS10Response resp = (PKCS10Response) iter.next(); // create proper ScepResponseMessage IResponseMessage ret = reqmsg.createResponseMessage( org.ejbca.core.protocol.scep.ScepResponseMessage.class, reqmsg, racert, rapriv, cryptProvider); ret.setCACert(cacert); X509Certificate respCert = resp.getCertificate(); if (resp.isSuccessful() && (respCert != null)) { ret.setCertificate(respCert); } else { ret.setStatus(ResponseStatus.FAILURE); ret.setFailInfo(FailInfo.BAD_REQUEST); String failText = resp.getFailInfo(); ret.setFailText(failText); } ret.create(); reply = ret.getResponseMessage(); } else { log.debug("Request is not yet processed, status: " + msg.getStatus()); reply = createPendingResponseMessage(reqmsg, racert, rapriv, cryptProvider) .getResponseMessage(); log.debug("Responding with pending response, still pending."); } } else { // User doesn't exist } } else { if (reqmsg.getMessageType() == ScepRequestMessage.SCEP_TYPE_PKCSREQ) { log.debug("Received a PKCSReq message from host: " + remoteAddr); // Decrypt the Scep message and extract the pkcs10 request if (reqmsg.requireKeyInfo()) { // scep encrypts message with the RAs certificate reqmsg.setKeyInfo(racert, rapriv, cryptProvider); } // Verify the request if (reqmsg.verify() == false) { String msg = "POPO verification failed."; log.error(msg); throw new SignRequestSignatureException(msg); } String username = reqmsg.getUsername(); if (username == null) { String msg = "No username in request, request DN: " + reqmsg.getRequestDN(); log.error(msg); throw new SignRequestException(msg); } log.info("Received a SCEP/PKCS10 request for user: " + username + ", from host: " + remoteAddr); String authPwd = ExtraConfiguration.instance().getString(ExtraConfiguration.SCEPAUTHPWD); if (StringUtils.isNotEmpty(authPwd) && !StringUtils.equals(authPwd, "none")) { log.debug("Requiring authPwd in order to precess SCEP requests"); String pwd = reqmsg.getPassword(); if (!StringUtils.equals(authPwd, pwd)) { log.error("Wrong auth password received in SCEP request: " + pwd); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Auth pwd missmatch"); return; } log.debug("Request passed authPwd test."); } else { log.debug("Not requiring authPwd in order to precess SCEP requests"); } // Try to find the CA name from the issuerDN, if we can't find it (i.e. not defined in web.xml) we use the default String issuerDN = CertTools.stringToBCDNString(reqmsg.getIssuerDN()); String caName = ExtraConfiguration.instance().getString(issuerDN); if (StringUtils.isEmpty(caName)) { caName = ExtraConfiguration.instance().getString(ExtraConfiguration.SCEPDEFAULTCA); log.info("Did not find a CA name from issuerDN: " + issuerDN + ", using the default CA '" + caName + "'"); } else { log.debug("Found a CA name '" + caName + "' from issuerDN: " + issuerDN); } // Get altNames if we can find them String altNames = reqmsg.getRequestAltNames(); byte[] encoded = reqmsg.getCertificationRequest().getEncoded(); String pkcs10 = new String(Base64.encode(encoded, false)); // Create a pkcs10 request String certificateProfile = ExtraConfiguration.instance() .getString(ExtraConfiguration.SCEPCERTPROFILEKEY); String entityProfile = ExtraConfiguration.instance() .getString(ExtraConfiguration.SCEPENTITYPROFILEKEY); boolean createOrEditUser = ExtraConfiguration.instance() .getBoolean(ExtraConfiguration.SCEPEDITUSER); PKCS10Request req = new PKCS10Request(100, username, reqmsg.getRequestDN(), altNames, null, null, entityProfile, certificateProfile, caName, pkcs10); req.setCreateOrEditUser(createOrEditUser); SubMessages submessages = new SubMessages(); submessages.addSubMessage(req); msgHome.create(transId, submessages); reply = createPendingResponseMessage(reqmsg, racert, rapriv, cryptProvider) .getResponseMessage(); } } if (reply == null) { // This is probably a getCert message? log.debug("Sending HttpServletResponse.SC_NOT_IMPLEMENTED (501) response"); response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, "Can not handle request"); return; } // Send back SCEP response, PKCS#7 which contains the end entity's certificate, or pending, or failure sendBinaryBytes(reply, response, "application/x-pki-message", null); } else if (operation.equals("GetCACert")) { // The response has the content type tagged as application/x-x509-ca-cert. // The body of the response is a DER encoded binary X.509 certificate. // For example: "Content-Type:application/x-x509-ca-cert\n\n"<BER-encoded X509> // IF we are not an RA, which in case we should return the same thing as GetCACertChain log.info("Got SCEP cert request for CA '" + message + "'"); if (chain != null) { if (chain.length > 1) { // We are an RA, so return the same as GetCACertChain, but with other content type getCACertChain(message, remoteAddr, response, alias, raks, false); } else { // The CA certificate is no 0 X509Certificate cert = (X509Certificate) chain[0]; if (chain.length > 1) { cert = (X509Certificate) chain[1]; } log.debug("Found cert with DN '" + cert.getSubjectDN().toString() + "'"); log.info("Sent certificate for CA '" + message + "' to SCEP client with ip " + remoteAddr); sendBinaryBytes(cert.getEncoded(), response, "application/x-x509-ca-cert", null); } } else { log.error("No CA certificates found"); response.sendError(HttpServletResponse.SC_NOT_FOUND, "No CA certificates found."); } } else if (operation.equals("GetCACertChain")) { // The response for GetCACertChain is a certificates-only PKCS#7 // SignedDatato carry the certificates to the end entity, with a // Content-Type of application/x-x509-ca-ra-cert-chain. log.info("Got SCEP cert chain request for CA '" + message + "'"); getCACertChain(message, remoteAddr, response, alias, raks, true); } else if (operation.equals("GetCACaps")) { // The response for GetCACaps is a <lf> separated list of capabilities /* "GetNextCACert" CA Supports the GetNextCACert message. "POSTPKIOperation" PKIOPeration messages may be sent via HTTP POST. "SHA-1" CA Supports the SHA-1 hashing algorithm in signatures and fingerprints. If present, the client SHOULD use SHA-1. If absent, the client MUST use MD5 to maintain backward compatability. "Renewal" Clients may use current certificate and key to authenticate an enrollment request for a new certificate. */ log.info("Got SCEP CACaps request for CA '" + message + "'"); response.setContentType("text/plain"); response.getOutputStream().print("POSTPKIOperation\nSHA-1"); } } catch (java.lang.ArrayIndexOutOfBoundsException ae) { log.error("Empty or invalid request received.", ae); // TODO: Send back proper Failure Response response.sendError(HttpServletResponse.SC_BAD_REQUEST, ae.getMessage()); } catch (Exception e) { log.error("Error in ScepRAServlet:", e); // TODO: Send back proper Failure Response response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } }