List of usage examples for java.security.cert X509Certificate getPublicKey
public abstract PublicKey getPublicKey();
From source file:de.konqi.fitapi.auth.PublicKeysManager.java
/** * Forces a refresh of the public certificates downloaded from {@link #getPublicCertsEncodedUrl}. * * <p>//from w w w . j a va 2 s.c om * This method is automatically called from {@link #getPublicKeys()} if the public keys have not * yet been initialized or if the expiration time is very close, so normally this doesn't need to * be called. Only call this method to explicitly force the public keys to be updated. * </p> */ public PublicKeysManager refresh() throws GeneralSecurityException, IOException { lock.lock(); try { publicKeys = new ArrayList<PublicKey>(); // HTTP request to public endpoint CertificateFactory factory = SecurityUtils.getX509CertificateFactory(); HttpResponse certsResponse = transport.createRequestFactory() .buildGetRequest(new GenericUrl(publicCertsEncodedUrl)).execute(); expirationTimeMilliseconds = clock.currentTimeMillis() + getCacheTimeInSec(certsResponse.getHeaders()) * 1000; // parse each public key in the JSON response JsonParser parser = jsonFactory.createJsonParser(certsResponse.getContent()); JsonToken currentToken = parser.getCurrentToken(); // token is null at start, so get next token if (currentToken == null) { currentToken = parser.nextToken(); } Preconditions.checkArgument(currentToken == JsonToken.START_OBJECT); try { while (parser.nextToken() != JsonToken.END_OBJECT) { parser.nextToken(); String certValue = parser.getText(); X509Certificate x509Cert = (X509Certificate) factory .generateCertificate(new ByteArrayInputStream(StringUtils.getBytesUtf8(certValue))); publicKeys.add(x509Cert.getPublicKey()); } publicKeys = Collections.unmodifiableList(publicKeys); } finally { parser.close(); } return this; } finally { lock.unlock(); } }
From source file:be.fedict.eid.applet.service.signer.facets.KeyInfoSignatureFacet.java
public void postSign(Element signatureElement, List<X509Certificate> signingCertificateChain) { LOG.debug("postSign"); String signatureNamespacePrefix = signatureElement.getPrefix(); /*/* w w w . ja va 2 s.c om*/ * Make sure we insert right after the ds:SignatureValue element, just * before the first ds:Object element. */ Node nextSibling; NodeList objectNodeList = signatureElement.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Object"); if (0 == objectNodeList.getLength()) { nextSibling = null; } else { nextSibling = objectNodeList.item(0); } /* * Construct the ds:KeyInfo element using JSR 105. */ KeyInfoFactory keyInfoFactory = KeyInfoFactory.getInstance("DOM", new XMLDSigRI()); List<Object> x509DataObjects = new LinkedList<Object>(); X509Certificate signingCertificate = signingCertificateChain.get(0); List<Object> keyInfoContent = new LinkedList<Object>(); if (this.includeKeyValue) { KeyValue keyValue; try { keyValue = keyInfoFactory.newKeyValue(signingCertificate.getPublicKey()); } catch (KeyException e) { throw new RuntimeException("key exception: " + e.getMessage(), e); } keyInfoContent.add(keyValue); } if (this.includeIssuerSerial) { x509DataObjects.add(keyInfoFactory.newX509IssuerSerial( signingCertificate.getIssuerX500Principal().toString(), signingCertificate.getSerialNumber())); } if (this.includeEntireCertificateChain) { for (X509Certificate certificate : signingCertificateChain) { x509DataObjects.add(certificate); } } else { x509DataObjects.add(signingCertificate); } if (false == x509DataObjects.isEmpty()) { X509Data x509Data = keyInfoFactory.newX509Data(x509DataObjects); keyInfoContent.add(x509Data); } KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoContent); DOMKeyInfo domKeyInfo = (DOMKeyInfo) keyInfo; Key key = new Key() { private static final long serialVersionUID = 1L; public String getAlgorithm() { return null; } public byte[] getEncoded() { return null; } public String getFormat() { return null; } }; XMLSignContext xmlSignContext = new DOMSignContext(key, signatureElement); DOMCryptoContext domCryptoContext = (DOMCryptoContext) xmlSignContext; try { domKeyInfo.marshal(signatureElement, nextSibling, signatureNamespacePrefix, domCryptoContext); } catch (MarshalException e) { throw new RuntimeException("marshall error: " + e.getMessage(), e); } }
From source file:be.fedict.trust.TrustValidator.java
/** * Validate the specified encoded {@link X509V2AttributeCertificate}'s. The * supplied certificate path will also be validated and used to validate the * attribute certificates./*from ww w .j ava 2 s.c o m*/ * * @param encodedAttributeCertificates * the encoded X509V2 attribute certificate. * * @param certificatePath * the certificate path. * @param validationDate * the validation date. * @throws CertPathValidatorException */ public void isTrusted(List<byte[]> encodedAttributeCertificates, List<X509Certificate> certificatePath, Date validationDate) throws CertPathValidatorException { try { /* * Validate the supplied certificate path */ isTrusted(certificatePath, validationDate); /* * Validate the attribute certificates */ for (byte[] encodedAttributeCertificate : encodedAttributeCertificates) { X509V2AttributeCertificate attributeCertificate = new X509V2AttributeCertificate( encodedAttributeCertificate); // check validity attributeCertificate.checkValidity(); if (certificatePath.size() < 2) { this.result = new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "Certificate path should at least contain 2 certificates"); throw new CertPathValidatorException(this.result.getMessage()); } // validate the signature on the attribute certificate against // the attribute certificate's holder X509Certificate issuerCertificate = certificatePath.get(1); attributeCertificate.verify(issuerCertificate.getPublicKey(), "BC"); } } catch (CertificateExpiredException e) { this.result = new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_VALIDITY_INTERVAL, "CertificateExpiredException: " + e.getMessage()); } catch (InvalidKeyException e) { this.result = new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_SIGNATURE, "InvalidKeyException: " + e.getMessage()); } catch (CertificateException e) { this.result = new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_SIGNATURE, "CertificateException: " + e.getMessage()); } catch (NoSuchAlgorithmException e) { this.result = new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_SIGNATURE, "NoSuchAlgorithmException: " + e.getMessage()); } catch (NoSuchProviderException e) { this.result = new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_SIGNATURE, "NoSuchProviderException: " + e.getMessage()); } catch (SignatureException e) { this.result = new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_SIGNATURE, "SignatureException: " + e.getMessage()); } catch (IOException e) { this.result = new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_SIGNATURE, "IOException: " + e.getMessage()); } }
From source file:be.fedict.commons.eid.consumer.BeIDIntegrity.java
private boolean __verifyNonRepSignature(final byte[] expectedDigestValue, final byte[] signatureValue, final X509Certificate certificate) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, IOException { final PublicKey publicKey = certificate.getPublicKey(); final Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, publicKey); final byte[] actualSignatureDigestInfoValue = cipher.doFinal(signatureValue); final ASN1InputStream asnInputStream = new ASN1InputStream(actualSignatureDigestInfoValue); final DigestInfo actualSignatureDigestInfo = new DigestInfo((ASN1Sequence) asnInputStream.readObject()); asnInputStream.close();/*from w w w . j a va 2s. co m*/ final byte[] actualDigestValue = actualSignatureDigestInfo.getDigest(); return Arrays.equals(expectedDigestValue, actualDigestValue); }
From source file:ddf.security.samlp.SimpleSign.java
private java.security.Signature getSignature(X509Certificate certificate) throws SignatureException { java.security.Signature signature; try {//from w ww . j a va2s .c o m if ("DSA".equalsIgnoreCase(certificate.getPublicKey().getAlgorithm())) { signature = java.security.Signature.getInstance(DSA_ALGO_JCE, "BC"); } else { signature = java.security.Signature.getInstance(RSA_ALGO_JCE); } } catch (NoSuchAlgorithmException | NoSuchProviderException e) { throw new SignatureException(e); } return signature; }
From source file:com.aivarsda.certpinninglib.HttpsPinner.java
/** * Will match the _trustedPins against the certificate chain, to validate * the specific certificate by checking if it has one of the trusted pins. * //from w w w . ja v a 2s . co m * @param certificate Certificate to validate with the pin. * @return True - certificate has one of the trusted pins. False - otherwise. * @throws CertificateException */ private boolean hasTrustedPin(X509Certificate certificate) throws CertificateException { try { boolean hasTrustedPin = false; final MessageDigest digest = MessageDigest.getInstance("SHA1"); final byte[] encodedPublicKey = certificate.getPublicKey().getEncoded(); final byte[] pin = digest.digest(encodedPublicKey); String strPin = Hex.bytesToHexString(pin); for (byte[] validPin : this._trustedPins) { if (Arrays.equals(validPin, pin)) { hasTrustedPin = true; break; } } // Remove logging if not needed Logger.logCertificate(certificate, true, strPin, hasTrustedPin); return hasTrustedPin; } catch (NoSuchAlgorithmException nsae) { throw new CertificateException(nsae); } }
From source file:com.tremolosecurity.unison.google.u2f.U2FServerUnison.java
@Override public SecurityKeyData processRegistrationResponse(RegistrationResponse registrationResponse, long currentTimeInMillis) throws U2FException { log.debug(">> processRegistrationResponse"); String sessionId = registrationResponse.getSessionId(); String clientDataBase64 = registrationResponse.getClientData(); String rawRegistrationDataBase64 = registrationResponse.getRegistrationData(); log.debug(">> rawRegistrationDataBase64: " + rawRegistrationDataBase64); EnrollSessionData sessionData = dataStore.getEnrollSessionData(sessionId); if (sessionData == null) { throw new U2FException("Unknown session_id"); }/*from w w w .ja v a 2s. c om*/ String appId = sessionData.getAppId(); String clientData = new String(Base64.decodeBase64(clientDataBase64)); byte[] rawRegistrationData = Base64.decodeBase64(rawRegistrationDataBase64); if (log.isDebugEnabled()) { log.debug("-- Input --"); log.debug(" sessionId: " + sessionId); log.debug(" challenge: " + Hex.encodeHexString(sessionData.getChallenge())); log.debug(" accountName: " + sessionData.getAccountName()); log.debug(" clientData: " + clientData); log.debug(" rawRegistrationData: " + Hex.encodeHexString(rawRegistrationData)); } RegisterResponse registerResponse = RawMessageCodec.decodeRegisterResponse(rawRegistrationData); byte[] userPublicKey = registerResponse.getUserPublicKey(); byte[] keyHandle = registerResponse.getKeyHandle(); X509Certificate attestationCertificate = registerResponse.getAttestationCertificate(); byte[] signature = registerResponse.getSignature(); List<Transports> transports = null; try { transports = U2fAttestation.Parse(attestationCertificate).getTransports(); } catch (CertificateParsingException e) { log.warn("Could not parse transports extension " + e.getMessage()); } if (log.isDebugEnabled()) { log.debug("-- Parsed rawRegistrationResponse --"); log.debug(" userPublicKey: " + Hex.encodeHexString(userPublicKey)); log.debug(" keyHandle: " + Hex.encodeHexString(keyHandle)); log.debug(" attestationCertificate: " + attestationCertificate.toString()); log.debug(" transports: " + transports); try { log.debug(" attestationCertificate bytes: " + Hex.encodeHexString(attestationCertificate.getEncoded())); } catch (CertificateEncodingException e) { throw new U2FException("Cannot encode certificate", e); } log.debug(" signature: " + Hex.encodeHexString(signature)); } byte[] appIdSha256 = crypto.computeSha256(appId.getBytes()); byte[] clientDataSha256 = crypto.computeSha256(clientData.getBytes()); byte[] signedBytes = RawMessageCodec.encodeRegistrationSignedBytes(appIdSha256, clientDataSha256, keyHandle, userPublicKey); Set<X509Certificate> trustedCertificates = dataStore.getTrustedCertificates(); boolean found = false; for (X509Certificate trusted : trustedCertificates) { try { attestationCertificate.verify(trusted.getPublicKey()); found = true; } catch (InvalidKeyException | CertificateException | NoSuchAlgorithmException | NoSuchProviderException | SignatureException e) { } } if (!found) { if (!this.requireAttestation) { log.warn("attestion cert is not trusted"); } else { throw new U2FException("Attestation certificate is not trusted"); } } verifyBrowserData(new JsonParser().parse(clientData), "navigator.id.finishEnrollment", sessionData); if (log.isDebugEnabled()) { log.debug("Verifying signature of bytes " + Hex.encodeHexString(signedBytes)); } if (!crypto.verifySignature(attestationCertificate, signedBytes, signature)) { throw new U2FException("Signature is invalid"); } // The first time we create the SecurityKeyData, we set the counter value to 0. // We don't actually know what the counter value of the real device is - but it will // be something bigger (or equal) to 0, so subsequent signatures will check out ok. SecurityKeyData securityKeyData = new SecurityKeyData(currentTimeInMillis, transports, keyHandle, userPublicKey, attestationCertificate, /* initial counter value */ 0); dataStore.addSecurityKeyData(sessionData.getAccountName(), securityKeyData); if (log.isDebugEnabled()) { log.debug("<< processRegistrationResponse"); } return securityKeyData; }
From source file:be.e_contract.eid.applet.service.impl.handler.SignatureDataMessageHandler.java
@Override public Object handleMessage(SignatureDataMessage message, Map<String, String> httpHeaders, HttpServletRequest request, HttpSession session) throws ServletException { byte[] signatureValue = message.signatureValue; List<X509Certificate> certificateChain = message.certificateChain; if (certificateChain.isEmpty()) { throw new ServletException("certificate chain is empty"); }// www . j a v a 2 s. co m X509Certificate signingCertificate = certificateChain.get(0); if (null == signingCertificate) { throw new ServletException("non-repudiation certificate missing"); } LOG.debug("non-repudiation signing certificate: " + signingCertificate.getSubjectX500Principal()); PublicKey signingPublicKey = signingCertificate.getPublicKey(); BeIDContextQualifier contextQualifier = new BeIDContextQualifier(request); /* * Verify the signature. */ String digestAlgo = this.signatureState.getDigestAlgo(); byte[] expectedDigestValue = this.signatureState.getDigestValue(); if (digestAlgo.endsWith("-PSS")) { LOG.debug("verifying RSA/PSS signature"); try { Signature signature = Signature.getInstance("RAWRSASSA-PSS", BouncyCastleProvider.PROVIDER_NAME); if ("SHA-256-PSS".equals(digestAlgo)) { LOG.debug("RSA/PSS SHA256"); signature.setParameter( new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), 32, 1)); } signature.initVerify(signingPublicKey); signature.update(expectedDigestValue); boolean result = signature.verify(signatureValue); if (false == result) { SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.SIGNATURE, signingCertificate, signatureValue); this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent); throw new SecurityException("signature incorrect"); } } catch (Exception e) { LOG.debug("signature verification error: " + e.getMessage(), e); SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.SIGNATURE, signingCertificate, signatureValue); this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent); throw new ServletException("signature verification error: " + e.getMessage(), e); } } else { try { Signature signature = Signature.getInstance("RawRSA", BouncyCastleProvider.PROVIDER_NAME); signature.initVerify(signingPublicKey); ByteArrayOutputStream digestInfo = new ByteArrayOutputStream(); if ("SHA-1".equals(digestAlgo) || "SHA1".equals(digestAlgo)) { digestInfo.write(SHA1_DIGEST_INFO_PREFIX); } else if ("SHA-224".equals(digestAlgo)) { digestInfo.write(SHA224_DIGEST_INFO_PREFIX); } else if ("SHA-256".equals(digestAlgo)) { digestInfo.write(SHA256_DIGEST_INFO_PREFIX); } else if ("SHA-384".equals(digestAlgo)) { digestInfo.write(SHA384_DIGEST_INFO_PREFIX); } else if ("SHA-512".equals(digestAlgo)) { digestInfo.write(SHA512_DIGEST_INFO_PREFIX); } else if ("RIPEMD160".equals(digestAlgo)) { digestInfo.write(RIPEMD160_DIGEST_INFO_PREFIX); } else if ("RIPEMD128".equals(digestAlgo)) { digestInfo.write(RIPEMD128_DIGEST_INFO_PREFIX); } else if ("RIPEMD256".equals(digestAlgo)) { digestInfo.write(RIPEMD256_DIGEST_INFO_PREFIX); } digestInfo.write(expectedDigestValue); signature.update(digestInfo.toByteArray()); boolean result = signature.verify(signatureValue); if (false == result) { SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.SIGNATURE, signingCertificate, signatureValue); this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent); throw new SecurityException("signature incorrect"); } } catch (Exception e) { LOG.debug("signature verification error: " + e.getMessage()); SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.SIGNATURE, signingCertificate, signatureValue); this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent); throw new ServletException("signature verification error: " + e.getMessage(), e); } } SignatureEvent signatureEvent = new SignatureEvent(signatureValue, certificateChain); try { this.signatureEvent.select(contextQualifier).fire(signatureEvent); } catch (ExpiredCertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED); } catch (RevokedCertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED); } catch (TrustCertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED); } catch (CertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE); } if (null != signatureEvent.getError()) { SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.TRUST, signingCertificate); this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent); return new FinishedMessage(signatureEvent.getError()); } return new FinishedMessage(); }
From source file:cl.nic.dte.util.XMLUtil.java
/** * Firma digitalmente usando la forma "enveloped signature" según el * estándar de la W3C (<a//from w w w. ja v a 2 s . c o m * href="http://www.w3.org/TR/xmldsig-core/">http://www.w3.org/TR/xmldsig-core/</a>). * <p> * * Este método además incorpora la información del * certificado a la sección <KeyInfo> opcional del * estándar, según lo exige SII. * <p> * * @param doc * El documento a firmar * @param uri * La referencia dentro del documento que debe ser firmada * @param pKey * La llave privada para firmar * @param cert * El certificado digital correspondiente a la llave privada * @throws NoSuchAlgorithmException * Si el algoritmo de firma de la llave no está soportado * (Actualmente soportado RSA+SHA1, DSA+SHA1 y HMAC+SHA1). * @throws InvalidAlgorithmParameterException * Si los algoritmos de canonización (parte del * estándar XML Signature) no son soportados (actaulmente * se usa el por defecto) * @throws KeyException * Si hay problemas al incluir la llave pública en el * <KeyValue>. * @throws MarshalException * @throws XMLSignatureException * * @see javax.xml.crypto.dsig.XMLSignature#sign(javax.xml.crypto.dsig.XMLSignContext) */ public static void signEmbededApache(Document doc, String uri, PrivateKey pKey, X509Certificate cert) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException { try { org.apache.xml.security.signature.XMLSignature sig = new org.apache.xml.security.signature.XMLSignature( doc, uri, org.apache.xml.security.signature.XMLSignature.ALGO_ID_SIGNATURE_RSA); doc.getDocumentElement().appendChild(sig.getElement()); //ObjectContainer obj = new ObjectContainer(doc); //obj.setId(uri); //sig.appendObject(obj); Transforms transforms = new Transforms(doc); transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE); sig.addDocument(uri, transforms); sig.addKeyInfo(cert.getPublicKey()); sig.addKeyInfo(cert); // sig.setXPathNamespaceContext("xmlns", "http://www.w3.org/2000/09/xmldsig#"); sig.sign(pKey); } catch (XMLSecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:be.e_contract.eid.applet.service.impl.handler.IdentityDataMessageHandler.java
private void verifySignature(BeIDContextQualifier contextQualifier, String signAlgo, byte[] signatureData, X509Certificate certificate, HttpServletRequest request, byte[]... data) throws ServletException { Signature signature;/*from w ww.j av a 2 s . c om*/ try { signature = Signature.getInstance(signAlgo); } catch (NoSuchAlgorithmException e) { throw new ServletException("algo error: " + e.getMessage(), e); } PublicKey publicKey = certificate.getPublicKey(); try { signature.initVerify(publicKey); } catch (InvalidKeyException e) { throw new ServletException("key error: " + e.getMessage(), e); } try { for (byte[] dataItem : data) { signature.update(dataItem); } boolean result = signature.verify(signatureData); if (false == result) { SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.DATA_INTEGRITY, certificate, signatureData); this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent); throw new ServletException("signature incorrect"); } } catch (SignatureException e) { SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.DATA_INTEGRITY, certificate, signatureData); this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent); throw new ServletException("signature error: " + e.getMessage(), e); } }