List of usage examples for java.security Signature initVerify
public final void initVerify(Certificate certificate) throws InvalidKeyException
From source file:com.cloudbees.jenkins.plugins.enterpriseplugins.CloudBeesUpdateSite.java
/** * Verifies the signature in the update center data file. *///from ww w .ja va 2 s .c om private FormValidation verifySignature(JSONObject o) throws IOException { try { FormValidation warning = null; JSONObject signature = o.getJSONObject("signature"); if (signature.isNullObject()) { return FormValidation.error("No signature block found in update center '" + getId() + "'"); } o.remove("signature"); List<X509Certificate> certs = new ArrayList<X509Certificate>(); {// load and verify certificates CertificateFactory cf = CertificateFactory.getInstance("X509"); for (Object cert : signature.getJSONArray("certificates")) { X509Certificate c = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(Base64.decode(cert.toString().toCharArray()))); try { c.checkValidity(); } catch (CertificateExpiredException e) { // even if the certificate isn't valid yet, // we'll proceed it anyway warning = FormValidation.warning(e, String.format( "Certificate %s has expired in update center '%s'", cert.toString(), getId())); } catch (CertificateNotYetValidException e) { warning = FormValidation.warning(e, String.format( "Certificate %s is not yet valid in update center '%s'", cert.toString(), getId())); } certs.add(c); } // all default root CAs in JVM are trusted, plus certs bundled in Jenkins Set<TrustAnchor> anchors = new HashSet<TrustAnchor>(); // CertificateUtil.getDefaultRootCAs(); ServletContext context = Hudson.getInstance().servletContext; anchors.add(new TrustAnchor(loadLicenseCaCertificate(), null)); for (String cert : (Set<String>) context.getResourcePaths("/WEB-INF/update-center-rootCAs")) { if (cert.endsWith(".txt")) { continue; // skip text files that are meant to be documentation } InputStream stream = context.getResourceAsStream(cert); if (stream != null) { try { anchors.add(new TrustAnchor((X509Certificate) cf.generateCertificate(stream), null)); } finally { IOUtils.closeQuietly(stream); } } } CertificateUtil.validatePath(certs, anchors); } // this is for computing a digest to check sanity MessageDigest sha1 = MessageDigest.getInstance("SHA1"); DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(), sha1); // this is for computing a signature Signature sig = Signature.getInstance("SHA1withRSA"); sig.initVerify(certs.get(0)); SignatureOutputStream sos = new SignatureOutputStream(sig); // until JENKINS-11110 fix, UC used to serve invalid digest (and therefore unverifiable signature) // that only covers the earlier portion of the file. This was caused by the lack of close() call // in the canonical writing, which apparently leave some bytes somewhere that's not flushed to // the digest output stream. This affects Jenkins [1.424,1,431]. // Jenkins 1.432 shipped with the "fix" (1eb0c64abb3794edce29cbb1de50c93fa03a8229) that made it // compute the correct digest, but it breaks all the existing UC json metadata out there. We then // quickly discovered ourselves in the catch-22 situation. If we generate UC with the correct signature, // it'll cut off [1.424,1.431] from the UC. But if we don't, we'll cut off [1.432,*). // // In 1.433, we revisited 1eb0c64abb3794edce29cbb1de50c93fa03a8229 so that the original "digest"/"signature" // pair continues to be generated in a buggy form, while "correct_digest"/"correct_signature" are generated // correctly. // // Jenkins should ignore "digest"/"signature" pair. Accepting it creates a vulnerability that allows // the attacker to inject a fragment at the end of the json. o.writeCanonical(new OutputStreamWriter(new TeeOutputStream(dos, sos), "UTF-8")).close(); // did the digest match? this is not a part of the signature validation, but if we have a bug in the c14n // (which is more likely than someone tampering with update center), we can tell String computedDigest = new String(Base64.encode(sha1.digest())); String providedDigest = signature.optString("correct_digest"); if (providedDigest == null) { return FormValidation.error("No correct_digest parameter in update center '" + getId() + "'. This metadata appears to be old."); } if (!computedDigest.equalsIgnoreCase(providedDigest)) { return FormValidation.error("Digest mismatch: " + computedDigest + " vs " + providedDigest + " in update center '" + getId() + "'"); } String providedSignature = signature.getString("correct_signature"); if (!sig.verify(Base64.decode(providedSignature.toCharArray()))) { return FormValidation.error( "Signature in the update center doesn't match with the certificate in update center '" + getId() + "'"); } if (warning != null) { return warning; } return FormValidation.ok(); } catch (GeneralSecurityException e) { return FormValidation.error(e, "Signature verification failed in the update center '" + getId() + "'"); } }
From source file:net.sf.keystore_explorer.crypto.csr.spkac.Spkac.java
/** * Verify SPKAC.//from ww w . ja v a2 s .co m * * @return True if verified successfully, false otherwise * @throws SpkacException * If verification fails */ public boolean verify() throws SpkacException { try { byte[] publicKeyAndChallenge = createPublicKeyAndChallengeForSigning(); Signature sig = Signature.getInstance(getSignatureAlgorithm().jce()); sig.initVerify(getPublicKey()); sig.update(publicKeyAndChallenge); return sig.verify(signature); } catch (GeneralSecurityException ex) { throw new SpkacException(res.getString("NoVerifySpkacSignature.exception.message"), ex); } }
From source file:test.be.fedict.eid.applet.RSATest.java
@Test public void testPSS() throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); SecureRandom random = new SecureRandom(); keyPairGenerator.initialize(new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4), random); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); Signature signature = Signature.getInstance("SHA256withRSA/PSS", "BC"); byte[] data = "hello world".getBytes(); signature.initSign(privateKey);//from w w w .j av a2 s.c o m signature.update(data); byte[] signatureValue = signature.sign(); LOG.debug("signature size: " + signatureValue.length); LOG.debug("signature value: " + new String(Hex.encodeHex(signatureValue))); signature.initVerify(publicKey); signature.update(data); boolean result = signature.verify(signatureValue); assertTrue(result); signature.initSign(privateKey); signature.update(data); byte[] signatureValue2 = signature.sign(); LOG.debug("signature size: " + signatureValue2.length); LOG.debug("signature value: " + new String(Hex.encodeHex(signatureValue2))); assertFalse(Arrays.equals(signatureValue, signatureValue2)); MessageDigest messageDigest = MessageDigest.getInstance("SHA-256", "BC"); byte[] digest = messageDigest.digest(data); signature = Signature.getInstance("RAWRSASSA-PSS", "BC"); signature.setParameter(new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), 32, 1)); signature.initVerify(publicKey); signature.update(digest); result = signature.verify(signatureValue); assertTrue(result); }
From source file:edu.lternet.pasta.gatekeeper.GatekeeperFilter.java
private Boolean isValidSignature(String tokenString, byte[] signature) { Boolean isValid = false;//from w w w .j av a 2 s.c om File lterCert = ConfigurationListener.getLterCertificate(); try { FileInputStream certFis = new FileInputStream(lterCert); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) cf.generateCertificate(certFis); PublicKey pubKey = cert.getPublicKey(); Signature sig = Signature.getInstance("MD5withRSA"); sig.initVerify(pubKey); sig.update(tokenString.getBytes()); isValid = sig.verify(signature); } catch (FileNotFoundException e) { logger.error("Gatekeeper.validateSignature :" + e.getMessage()); e.printStackTrace(); } catch (CertificateException e) { logger.error("Gatekeeper.validateSignature :" + e.getMessage()); e.printStackTrace(); } catch (NoSuchAlgorithmException e) { logger.error("Gatekeeper.validateSignature :" + e.getMessage()); e.printStackTrace(); } catch (InvalidKeyException e) { logger.error("Gatekeeper.validateSignature :" + e.getMessage()); e.printStackTrace(); } catch (SignatureException e) { logger.error("Gatekeeper.validateSignature :" + e.getMessage()); e.printStackTrace(); } return isValid; }
From source file:test.unit.be.fedict.eid.applet.service.signer.CMSTest.java
@Test public void testPkcs1Signature() throws Exception { // setup/*from w ww. ja v a 2 s .c o m*/ KeyPair keyPair = PkiTestUtils.generateKeyPair(); byte[] toBeSigned = "hello world".getBytes(); // operate Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(keyPair.getPrivate()); signature.update(toBeSigned); byte[] signatureValue = signature.sign(); // verify signature.initVerify(keyPair.getPublic()); signature.update(toBeSigned); boolean signatureResult = signature.verify(signatureValue); assertTrue(signatureResult); }
From source file:com.cws.esolutions.security.processors.impl.FileSecurityProcessorImpl.java
/** * @see com.cws.esolutions.security.processors.interfaces.IFileSecurityProcessor#verifyFile(com.cws.esolutions.security.processors.dto.FileSecurityRequest) *///w ww .j a va 2 s.co m public synchronized FileSecurityResponse verifyFile(final FileSecurityRequest request) throws FileSecurityException { final String methodName = IFileSecurityProcessor.CNAME + "#verifyFile(final FileSecurityRequest request) throws FileSecurityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("FileSecurityRequest: {}", request); } FileSecurityResponse response = new FileSecurityResponse(); final RequestHostInfo reqInfo = request.getHostInfo(); final UserAccount userAccount = request.getUserAccount(); final KeyManager keyManager = KeyManagementFactory.getKeyManager(keyConfig.getKeyManager()); if (DEBUG) { DEBUGGER.debug("RequestHostInfo: {}", reqInfo); DEBUGGER.debug("UserAccount", userAccount); DEBUGGER.debug("KeyManager: {}", keyManager); } try { KeyPair keyPair = keyManager.returnKeys(userAccount.getGuid()); if (keyPair != null) { // read in the file signature byte[] sigToVerify = IOUtils.toByteArray(new FileInputStream(request.getSignedFile())); if (DEBUG) { DEBUGGER.debug("sigToVerify: {}", sigToVerify); } Signature signature = Signature.getInstance(fileSecurityConfig.getSignatureAlgorithm()); signature.initVerify(keyPair.getPublic()); signature.update(IOUtils.toByteArray(new FileInputStream(request.getUnsignedFile()))); if (DEBUG) { DEBUGGER.debug("Signature: {}", signature); } response.setRequestStatus(SecurityRequestStatus.SUCCESS); response.setIsSignatureValid(signature.verify(sigToVerify)); } else { response.setRequestStatus(SecurityRequestStatus.FAILURE); } } catch (NoSuchAlgorithmException nsax) { ERROR_RECORDER.error(nsax.getMessage(), nsax); throw new FileSecurityException(nsax.getMessage(), nsax); } catch (FileNotFoundException fnfx) { ERROR_RECORDER.error(fnfx.getMessage(), fnfx); throw new FileSecurityException(fnfx.getMessage(), fnfx); } catch (InvalidKeyException ikx) { ERROR_RECORDER.error(ikx.getMessage(), ikx); throw new FileSecurityException(ikx.getMessage(), ikx); } catch (SignatureException sx) { ERROR_RECORDER.error(sx.getMessage(), sx); throw new FileSecurityException(sx.getMessage(), sx); } catch (IOException iox) { ERROR_RECORDER.error(iox.getMessage(), iox); throw new FileSecurityException(iox.getMessage(), iox); } catch (KeyManagementException kmx) { ERROR_RECORDER.error(kmx.getMessage(), kmx); throw new FileSecurityException(kmx.getMessage(), kmx); } finally { // audit try { AuditEntry auditEntry = new AuditEntry(); auditEntry.setHostInfo(reqInfo); auditEntry.setAuditType(AuditType.VERIFYFILE); auditEntry.setUserAccount(userAccount); auditEntry.setAuthorized(Boolean.TRUE); auditEntry.setApplicationId(request.getApplicationId()); auditEntry.setApplicationName(request.getAppName()); if (DEBUG) { DEBUGGER.debug("AuditEntry: {}", auditEntry); } AuditRequest auditRequest = new AuditRequest(); auditRequest.setAuditEntry(auditEntry); if (DEBUG) { DEBUGGER.debug("AuditRequest: {}", auditRequest); } auditor.auditRequest(auditRequest); } catch (AuditServiceException asx) { ERROR_RECORDER.error(asx.getMessage(), asx); } } return response; }
From source file:com.vmware.identity.samlservice.SamlServiceTest.java
@Test public void testVerifySignature() throws NoSuchAlgorithmException, InvalidKeyException, SignatureException { // pick a sample message String message = "This is a sample message to be encoded"; // sign using our algorithm SignatureAlgorithm algo = SignatureAlgorithm.getSignatureAlgorithmForURI(TestConstants.SIGNATURE_ALGORITHM); Signature sig = Signature.getInstance(algo.getAlgorithmName()); sig.initSign(privateKey);//from w w w.ja v a2 s. co m byte[] messageBytes = message.getBytes(); sig.update(messageBytes); byte[] sigBytes = sig.sign(); String signature = Shared.encodeBytes(sigBytes); // verify signature here sig.initVerify(x509Certificate.getPublicKey()); sig.update(messageBytes); boolean verifies = sig.verify(sigBytes); log.debug("signature verifies in test: " + verifies); // just call verifySignature method and expect to not throw service.verifySignature(message, signature); }
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"); }// ww w .j av a2 s . c om 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:eu.europa.ejusticeportal.dss.applet.DssApplet.java
/** * This methods checks if the data coming from the server can be trusted. * The hash provided by the server is checked using the public key. * @param data the data coming from the server. * @param serverHash the hash of the data coming from the server. * @param algo the algorithm used for the server hash. * @return <code>true</code> if the serverHash can be verified with the public key. */// www. j a v a 2 s.c o m private boolean canTrustServerHash(final String data, final String serverHash, final String algo) { Certificate certificate; InputStream pemInputStream; try { pemInputStream = getClass().getClassLoader().getResourceAsStream("certificate.pem"); if (pemInputStream == null) { LOG.log(Level.SEVERE, "Missing certificate.pem file. Impossible to check if the data coming from the server can be trusted."); return false; } } catch (Exception e) { LOG.log(Level.SEVERE, "Missing certificate.pem file. Impossible to check if the data coming from the server can be trusted."); return false; } try { certificate = CertificateFactory.getInstance("X.509").generateCertificate(pemInputStream); PublicKey publicKey = certificate.getPublicKey(); Signature sigVerify = Signature.getInstance(new String(Base64.decodeBase64(algo)), "BC"); sigVerify.initVerify(publicKey); sigVerify.update(data.getBytes("UTF-8")); boolean signatureMatch = sigVerify.verify(Base64.decodeBase64(serverHash)); if (signatureMatch) { LOG.log(Level.INFO, "The data coming from the server can be trusted."); return true; } else { LOG.log(Level.SEVERE, "!!! Tampered data received !!!"); LOG.log(Level.INFO, serverHash); LOG.log(Level.INFO, data); return false; } } catch (CertificateException e) { LOG.error(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { LOG.error(e.getMessage(), e); } catch (NoSuchProviderException e) { LOG.error(e.getMessage(), e); } catch (InvalidKeyException e) { LOG.error(e.getMessage(), e); } catch (SignatureException e) { LOG.error(e.getMessage(), e); } catch (UnsupportedEncodingException e) { LOG.error(e.getMessage(), e); } LOG.log(Level.SEVERE, "Impossible to check if the data coming from the server can be trusted."); return false; }
From source file:org.waveprotocol.wave.crypto.WaveSignatureVerifier.java
/** * Verifies the signature on some signed payload. * @param signedPayload the payload on which we're verifiying the signature. * @param signatureInfo the signature provided with the payload. * @param authority name of the authority that we expect the target * certificate to be issued to.//from w w w .ja va2 s . c o m * * @throws SignatureException if the signature can't be verified, either * because it simply didn't check out, or because of other reasons, like us * not supporting the signature algorithm specified. * @throws UnknownSignerException if we can't find the cert chain in the local * cert-path store. */ public void verify(byte[] signedPayload, ProtocolSignature signatureInfo, String authority) throws SignatureException, UnknownSignerException { SignerInfo signer = pathStore.getSignerInfo(signatureInfo.getSignerId().toByteArray()); if (signer == null) { throw new UnknownSignerException("could not find information about signer " + Base64.encodeBase64(signatureInfo.getSignerId().toByteArray())); } verifySignerInfo(signer); Signature verifier; try { verifier = Signature.getInstance(AlgorithmUtil.getJceName(signatureInfo.getSignatureAlgorithm())); } catch (NoSuchAlgorithmException e) { throw new SignatureException( "can't verify signatures of type " + signatureInfo.getSignatureAlgorithm().toString(), e); } X509Certificate cert = signer.getCertificates().get(0); try { verifier.initVerify(cert); } catch (InvalidKeyException e) { throw new SignatureException("certificate of signer was not issued for " + "message signing"); } try { verifier.update(signedPayload); } catch (java.security.SignatureException e) { // this is thrown if the verifier object is not properly initialized. // this shouldn't happen as we _just_ initialized it on the previous line. throw new IllegalStateException(e); } try { if (!verifier.verify(signatureInfo.getSignatureBytes().toByteArray())) { throw new SignatureException("signature did not verify"); } } catch (java.security.SignatureException e) { throw new SignatureException(e); } verifyMatchingAuthority(authority, cert); }