List of usage examples for java.security Signature getInstance
public static Signature getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:com.cloudbees.jenkins.plugins.enterpriseplugins.CloudBeesUpdateSite.java
/** * Verifies the signature in the update center data file. */// w w w. j av a2 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:test.unit.be.fedict.eid.applet.service.SignatureDataMessageHandlerTest.java
public void testHandleMessageWithAudit() throws Exception { // setup//from w w w.ja v a2 s .c o m KeyPair keyPair = MiscTestUtils.generateKeyPair(); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusYears(1); X509Certificate certificate = MiscTestUtils.generateCertificate(keyPair.getPublic(), "CN=Test,SERIALNUMBER=1234", notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null, null); ServletConfig mockServletConfig = EasyMock.createMock(ServletConfig.class); Map<String, String> httpHeaders = new HashMap<String, String>(); HttpSession mockHttpSession = EasyMock.createMock(HttpSession.class); HttpServletRequest mockServletRequest = EasyMock.createMock(HttpServletRequest.class); EasyMock.expect(mockServletConfig.getInitParameter("AuditService")).andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter("AuditServiceClass")) .andStubReturn(AuditTestService.class.getName()); EasyMock.expect(mockServletConfig.getInitParameter("SignatureService")).andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter("SignatureServiceClass")) .andStubReturn(SignatureTestService.class.getName()); MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); byte[] document = "hello world".getBytes(); byte[] digestValue = messageDigest.digest(document); EasyMock.expect(mockHttpSession.getAttribute(SignatureDataMessageHandler.DIGEST_VALUE_SESSION_ATTRIBUTE)) .andStubReturn(digestValue); EasyMock.expect(mockHttpSession.getAttribute(SignatureDataMessageHandler.DIGEST_ALGO_SESSION_ATTRIBUTE)) .andStubReturn("SHA-1"); SignatureDataMessage message = new SignatureDataMessage(); message.certificateChain = new LinkedList<X509Certificate>(); message.certificateChain.add(certificate); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(keyPair.getPrivate()); signature.update(document); byte[] signatureValue = signature.sign(); message.signatureValue = signatureValue; // prepare EasyMock.replay(mockServletConfig, mockHttpSession, mockServletRequest); // operate AppletServiceServlet.injectInitParams(mockServletConfig, this.testedInstance); this.testedInstance.init(mockServletConfig); this.testedInstance.handleMessage(message, httpHeaders, mockServletRequest, mockHttpSession); // verify EasyMock.verify(mockServletConfig, mockHttpSession, mockServletRequest); assertEquals(signatureValue, SignatureTestService.getSignatureValue()); assertEquals("1234", AuditTestService.getAuditSigningUserId()); }
From source file:edu.byu.wso2.apim.extensions.JWTDecoder.java
private boolean verifySignature(Certificate publicCert, byte[] decodedSignature, String base64EncodedHeader, String base64EncodedBody, String base64EncodedSignature) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException { // create signature instance with signature algorithm and public cert, // to verify the signature. Signature verifySig = Signature.getInstance("SHA256withRSA"); // init//from w ww . j a va2 s . c om verifySig.initVerify(publicCert); // update signature with signature data. verifySig.update((base64EncodedHeader + "." + base64EncodedBody).getBytes()); // do the verification return verifySig.verify(decodedSignature); }
From source file:com.example.android.basicandroidkeystore.BasicAndroidKeyStoreFragment.java
/** * Given some data and a signature, uses the key pair stored in the Android Key Store to verify * that the data was signed by this application, using that key pair. * @param input The data to be verified. * @param signatureStr The signature provided for the data. * @return A boolean value telling you whether the signature is valid or not. */// w w w. j av a 2s .c o m public boolean verifyData(String input, String signatureStr) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, UnrecoverableEntryException, InvalidKeyException, SignatureException { byte[] data = input.getBytes(); byte[] signature; // BEGIN_INCLUDE(decode_signature) // Make sure the signature string exists. If not, bail out, nothing to do. if (signatureStr == null) { Log.w(TAG, "Invalid signature."); Log.w(TAG, "Exiting verifyData()..."); return false; } try { // The signature is going to be examined as a byte array, // not as a base64 encoded string. signature = Base64.decode(signatureStr, Base64.DEFAULT); } catch (IllegalArgumentException e) { // signatureStr wasn't null, but might not have been encoded properly. // It's not a valid Base64 string. return false; } // END_INCLUDE(decode_signature) KeyStore ks = KeyStore.getInstance("AndroidKeyStore"); // Weird artifact of Java API. If you don't have an InputStream to load, you still need // to call "load", or it'll crash. ks.load(null); // Load the key pair from the Android Key Store KeyStore.Entry entry = ks.getEntry(mAlias, null); if (entry == null) { Log.w(TAG, "No key found under alias: " + mAlias); Log.w(TAG, "Exiting verifyData()..."); return false; } if (!(entry instanceof KeyStore.PrivateKeyEntry)) { Log.w(TAG, "Not an instance of a PrivateKeyEntry"); return false; } // This class doesn't actually represent the signature, // just the engine for creating/verifying signatures, using // the specified algorithm. Signature s = Signature.getInstance(SecurityConstants.SIGNATURE_SHA256withRSA); // BEGIN_INCLUDE(verify_data) // Verify the data. s.initVerify(((KeyStore.PrivateKeyEntry) entry).getCertificate()); s.update(data); return s.verify(signature); // END_INCLUDE(verify_data) }
From source file:test.integ.be.fedict.commons.eid.client.JCATest.java
@Test public void testLocale() throws Exception { Security.addProvider(new BeIDProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); BeIDKeyStoreParameter beIDKeyStoreParameter = new BeIDKeyStoreParameter(); beIDKeyStoreParameter.setLocale(Locale.FRENCH); beIDKeyStoreParameter.setLogger(new TestLogger()); keyStore.load(beIDKeyStoreParameter); PrivateKey privateKey = (PrivateKey) keyStore.getKey("Signature", null); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(privateKey);/*w w w . j a v a2 s. com*/ byte[] toBeSigned = "hello world".getBytes(); signature.update(toBeSigned); signature.sign(); }
From source file:mx.bigdata.sat.cfdi.CFDv33.java
String getSignature(PrivateKey key) throws Exception { byte[] bytes = getOriginalBytes(); Signature sig = Signature.getInstance("SHA256withRSA"); sig.initSign(key);/* w w w. java 2 s . com*/ sig.update(bytes); byte[] signed = sig.sign(); Base64 b64 = new Base64(-1); return b64.encodeToString(signed); }
From source file:com.mytalentfolio.h_daforum.CconnectToServer.java
/** * Returns the string formatted digital signature for the data. * //from ww w .ja v a2 s . co m * @param key * Private key for signing the data. * @param data * Data for which the signature is to be generated. * @return signed data with the provide private key. * @throws NoSuchAlgorithmException * if the specified algorithm is not available. * @throws InvalidKeyException * if privateKey is not valid. * @throws SignatureException * if this Signature instance is not initialized properly. */ private String getDataSig(PrivateKey key, String data) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException { // Generate Signature For the data Signature signature = Signature.getInstance("SHA256withRSA"); signature.initSign(key); signature.update(data.getBytes()); byte[] sigBytes = signature.sign(); return Base64.encodeToString(sigBytes, Base64.DEFAULT); }
From source file:es.gob.afirma.signers.ooxml.be.fedict.eid.applet.service.signer.AbstractXmlSignatureService.java
@SuppressWarnings("unchecked") private byte[] getSignedXML(final String digestAlgo, final List<DigestInfo> digestInfos, final List<X509Certificate> signingCertificateChain, final PrivateKey signingKey) throws ParserConfigurationException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, javax.xml.crypto.dsig.XMLSignatureException, TransformerException, IOException, SAXException {/*www . jav a 2 s .c o m*/ // DOM Document construction. Document document = getEnvelopingDocument(); if (null == document) { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); document = documentBuilderFactory.newDocumentBuilder().newDocument(); } final XMLSignContext xmlSignContext = new DOMSignContext(signingKey, document); final URIDereferencer uriDereferencer = getURIDereferencer(); if (null != uriDereferencer) { xmlSignContext.setURIDereferencer(uriDereferencer); } final XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM", //$NON-NLS-1$ new org.jcp.xml.dsig.internal.dom.XMLDSigRI()); // Add ds:References that come from signing client local files. final List<Reference> references = new LinkedList<Reference>(); addDigestInfosAsReferences(digestInfos, signatureFactory, references); // Invoke the signature facets. final String signatureId = "xmldsig-" + UUID.randomUUID().toString(); //$NON-NLS-1$ final List<XMLObject> objects = new LinkedList<XMLObject>(); for (final SignatureFacet signatureFacet : this.signatureFacets) { signatureFacet.preSign(signatureFactory, document, signatureId, signingCertificateChain, references, objects); } // ds:SignedInfo final SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(getSignatureMethod(digestAlgo), null); final SignedInfo signedInfo = signatureFactory.newSignedInfo(signatureFactory.newCanonicalizationMethod( getCanonicalizationMethod(), (C14NMethodParameterSpec) null), signatureMethod, references); // Creamos el KeyInfo final KeyInfoFactory kif = signatureFactory.getKeyInfoFactory(); final List<Object> x509Content = new ArrayList<Object>(); x509Content.add(signingCertificateChain.get(0)); final List<Object> content = new ArrayList<Object>(); try { content.add(kif.newKeyValue(signingCertificateChain.get(0).getPublicKey())); } catch (final Exception e) { Logger.getLogger("es.gob.afirma") //$NON-NLS-1$ .severe("Error creando el KeyInfo, la informacion puede resultar incompleta: " + e); //$NON-NLS-1$ } content.add(kif.newX509Data(x509Content)); // JSR105 ds:Signature creation final String signatureValueId = signatureId + "-signature-value"; //$NON-NLS-1$ final javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, kif.newKeyInfo(content), // KeyInfo objects, signatureId, signatureValueId); // ds:Signature Marshalling. final DOMXMLSignature domXmlSignature = (DOMXMLSignature) xmlSignature; Node documentNode = document.getDocumentElement(); if (null == documentNode) { documentNode = document; // In case of an empty DOM document. } final String dsPrefix = null; domXmlSignature.marshal(documentNode, dsPrefix, (DOMCryptoContext) xmlSignContext); // Completion of undigested ds:References in the ds:Manifests. for (final XMLObject object : objects) { final List<XMLStructure> objectContentList = object.getContent(); for (final XMLStructure objectContent : objectContentList) { if (!(objectContent instanceof Manifest)) { continue; } final Manifest manifest = (Manifest) objectContent; final List<Reference> manifestReferences = manifest.getReferences(); for (final Reference manifestReference : manifestReferences) { if (null != manifestReference.getDigestValue()) { continue; } final DOMReference manifestDOMReference = (DOMReference) manifestReference; manifestDOMReference.digest(xmlSignContext); } } } // Completion of undigested ds:References. final List<Reference> signedInfoReferences = signedInfo.getReferences(); for (final Reference signedInfoReference : signedInfoReferences) { final DOMReference domReference = (DOMReference) signedInfoReference; if (null != domReference.getDigestValue()) { // ds:Reference with external digest value continue; } domReference.digest(xmlSignContext); } // Calculation of signature final DOMSignedInfo domSignedInfo = (DOMSignedInfo) signedInfo; final ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); domSignedInfo.canonicalize(xmlSignContext, dataStream); final byte[] octets = dataStream.toByteArray(); final Signature sig = Signature.getInstance(digestAlgo.replace("-", "") + "withRSA"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ final byte[] sigBytes; try { sig.initSign(signingKey); sig.update(octets); sigBytes = sig.sign(); } catch (final Exception e) { throw new javax.xml.crypto.dsig.XMLSignatureException( "Error en la firma PKCS#1 ('" + digestAlgo + "withRSA): " + e); //$NON-NLS-1$ //$NON-NLS-2$ } // Sacamos el pre-XML a un OutputStream final ByteArrayOutputStream baos = new ByteArrayOutputStream(); writeDocument(document, baos); // Ya tenemos el XML, con la firma vacia y el SignatureValue, cada uno // por su lado... return postSign(baos.toByteArray(), signingCertificateChain, signatureId, sigBytes); }
From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java
@Override public boolean verify(byte[] pemCertificate, String signatureAlgorithm, byte[] signature, byte[] plainText) throws CryptoException { boolean isVerified = false; if (plainText == null || signature == null || pemCertificate == null) { return false; }//from ww w. j a va 2 s. c o m if (config.extraLogLevel(10)) { if (null != diagnosticFileDumper) { StringBuilder sb = new StringBuilder(10000); sb.append("plaintext in hex: ").append(DatatypeConverter.printHexBinary(plainText)).append("\n") .append("signature in hex: " + DatatypeConverter.printHexBinary(signature)).append("\n") .append("PEM cert in hex: " + DatatypeConverter.printHexBinary(pemCertificate)); logger.trace("verify : " + diagnosticFileDumper.createDiagnosticFile(sb.toString())); } } try { X509Certificate certificate = getX509Certificate(pemCertificate); if (certificate != null) { isVerified = validateCertificate(certificate); if (isVerified) { // only proceed if cert is trusted Signature sig = Signature.getInstance(signatureAlgorithm); sig.initVerify(certificate); sig.update(plainText); isVerified = sig.verify(signature); } } } catch (InvalidKeyException e) { CryptoException ex = new CryptoException("Cannot verify signature. Error is: " + e.getMessage() + "\r\nCertificate: " + DatatypeConverter.printHexBinary(pemCertificate), e); logger.error(ex.getMessage(), ex); throw ex; } catch (NoSuchAlgorithmException | SignatureException e) { CryptoException ex = new CryptoException( "Cannot verify. Signature algorithm is invalid. Error is: " + e.getMessage(), e); logger.error(ex.getMessage(), ex); throw ex; } return isVerified; }
From source file:edu.lternet.pasta.gatekeeper.GatekeeperFilter.java
private byte[] generateSignature(String tokenString) { byte[] signature = null; File ksFile = ConfigurationListener.getLterKeyStore(); String ksType = ConfigurationListener.getLterKeyStoreType(); String ksAlias = ConfigurationListener.getLterKeyStoreAlias(); char[] storePass = ConfigurationListener.getLterStorePasswd().toCharArray(); char[] keyPass = ConfigurationListener.getLterKeyPasswd().toCharArray(); try {/*w w w.j av a 2s. c o m*/ KeyStore ks = KeyStore.getInstance(ksType); FileInputStream ksFis = new FileInputStream(ksFile); BufferedInputStream ksBufIn = new BufferedInputStream(ksFis); ks.load(ksBufIn, storePass); PrivateKey priv = (PrivateKey) ks.getKey(ksAlias, keyPass); Signature rsa = Signature.getInstance("MD5withRSA"); rsa.initSign(priv); rsa.update(tokenString.getBytes()); signature = rsa.sign(); } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); } return signature; }