List of usage examples for java.security Signature update
public final void update(ByteBuffer data) throws SignatureException
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/* ww w .j a v a 2 s .c o m*/ verifySig.initVerify(publicCert); // update signature with signature data. verifySig.update((base64EncodedHeader + "." + base64EncodedBody).getBytes()); // do the verification return verifySig.verify(decodedSignature); }
From source file:test.unit.be.fedict.eid.applet.service.signer.CMSTest.java
@Test public void testPkcs1Signature() throws Exception { // setup/*from w w w . j ava 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:test.integ.be.fedict.hsm.model.KeyStoreSingletonBeanTest.java
private void checkSigning(long keyStoreId) throws Exception { List<String> aliases = this.testedInstance.getKeyStoreAliases(keyStoreId); assertFalse(aliases.isEmpty());/*from w w w.j ava 2s.com*/ String alias = aliases.get(0); byte[] toBeSigned = "hello world".getBytes(); MessageDigest messageDigest = MessageDigest.getInstance("SHA-1"); messageDigest.update(toBeSigned); byte[] digestValue = messageDigest.digest(); byte[] signatureValue = this.testedInstance.sign(keyStoreId, alias, "SHA-1", digestValue); Signature signature = Signature.getInstance("SHA1withRSA"); Certificate[] certificateChain = this.testedInstance.getCertificateChain(keyStoreId, alias); assertTrue(certificateChain.length > 0); X509Certificate certificate = (X509Certificate) certificateChain[0]; signature.initVerify(certificate.getPublicKey()); signature.update(toBeSigned); assertTrue(signature.verify(signatureValue)); }
From source file:com.vmware.identity.samlservice.SamlServiceTest.java
@Test public void testVerifySignatureVcd2() throws Exception { // pick a sample VCD message String message = "SAMLResponse=fZJNb%2BIwEIb%2FSuR7%2FJWQJhYBrRatVK" + "lcCsuhl5XjTCAosbMZm%2B7P3wClHxx6nPE7M%2B884%2FnyX99FJxixdb" + "YkgnISgTWubu2%2BJL%2B3v%2BKcLBdz1H0nB%2FXk9i74Z8DBWYRoKrWo" + "rm8lCaNVTmOLyuoeUHmjNj%2FWT0pSrobReWdcR6IVoG%2Bt9pdxB%2B8H" + "VIyJQlKR5VTIggqu8jRNmOlcqNm5OdtMZjq4Dme6azWyk6lJ9LgqyZ%2Bq" + "SUzKCw41AM%2BNEEZC1dQJT7K0qJJmktmb460riZamqhueFW1xNKI6pqbh" + "TXtIjqbJk6Sa5IgBHi16bX1JJBcy5lkssy3nSsyUEFTM8hcS7W7QpgXJGy" + "J1KR4%2Fk%2FkejEaE8QyDLG4whrE%2FxLbtq4DxqY%2FFwywWklOwe3rq" + "X%2FUI1LhePaRpyl6hQnTs3E2yNXhda6%2BZwWHOPtt5v9%2FGax%2FwLv" + "zpaoh2ugvwvVW8qNUmGAOIhN21WU9JvYfFM%2FwN040jvOqa0L2ZuRfepT" + "%2Fir79s8R8%3D&SigAlg=http%3A%2F%2Fwww.w3.org%2F2001%2F04%" + "2Fxmldsig-more%23rsa-sha256"; // sign using our algorithm SignatureAlgorithm algo = SignatureAlgorithm.getSignatureAlgorithmForURI(TestConstants.SIGNATURE_ALGORITHM); Signature sig = Signature.getInstance(algo.getAlgorithmName()); sig.initSign(privateKey);// w ww . j av a 2 s.c o 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); /* disabled now: task 1301740 // import our csp settings CasIdmClient idmClient = new CasIdmClient(SharedUtils.getIdmHostName()); SharedUtils.importConfiguration(idmClient, VSPHERE_LOCAL_TENANT, "/csp2.xml"); CasIdmAccessor idmAccessor = new CasIdmAccessor(idmClient); log.debug("CSP settings imported successfully"); idmAccessor.setTenant(VSPHERE_LOCAL_TENANT); // create new SamlService SamlServiceFactory factory2 = new DefaultSamlServiceFactory(); CertificateFactory certFactory = CertificateFactory .getInstance("X.509"); CertPath certPath = certFactory.generateCertPath(idmAccessor .getSAMLAuthorityChain()); SamlService service2 = factory2.createSamlService( idmClient.getTenantPrivateKey(VSPHERE_LOCAL_TENANT), SignatureAlgorithm.RSA_SHA256, SignatureAlgorithm.RSA_SHA256, idmClient.getEntityID(VSPHERE_LOCAL_TENANT), certPath); // now call it again with generated signature String vcdSignature = "tTUaPscQSmPKkqP9XGgCHZYoH%2FUy2MvZ1eoeP%2B3Y" + "nTDLxiuV5glxngtMbOGspo9NbL37lNVjdCUo7qQVDznUNmKpIOGa%2BGwE" + "jcgqeS7mBDsYPcICxVHZPYxbIaFCmlTIo125olswe4LuP92lIroe%2B%2F" + "DpeNXIGjUAFLHQwlLO7r73cHLH%2BPY2pcYww4X2I7Mhk%2FQ7I3tdMX1O" + "eOhqcRpMn8uyOs6JmVbMoVXuTVKyO96LmQUPCQVLmVjDeD%2BZjVALVLbs" + "vjWsdFt%2F%2Ff2MEXIQkYmeIM5HxZ5rW0uXRocarUrp8nhgxk%2FEQGhk" + "00KYP1xZTCC9JZR6OcbXJZZemBgq%2BA%3D%3D"; vcdSignature = URLDecoder.decode(vcdSignature, "UTF-8"); // just call verifySignature method and expect to not throw service2.verifySignature(message, vcdSignature); */ }
From source file:com.vmware.identity.samlservice.SamlServiceTest.java
@Test public void testVerifySignatureVcd() throws Exception { // pick a sample VCD message String message = "SAMLResponse=fZJNb9swDIb%2FiqF7LPnbEeIUw4oCAVoMqN" + "MedhlomU49yJJrSml%2F%2FuykX8uhFwGkXpKvHmpz9Tro4IgT9dZULAoF" + "C9Ao2%2FbmULGH%2Fc2qZFfbDcGg41He2oP17h5ptIYwmEsNyfNdxfxkpA" + "XqSRoYkKRTsv5xdyvjUMhxss4qq1lwjeR6A%2B407sm5kSTnkQijtAgzES" + "apTNOEK219y%2B104IpGvkzg9exI49kBB90D8aNqWbC7rtifrmkhVaop26h" + "oijJLEOajXBdtl2KSZ7PMvNve24pBmkG%2BLiBumr%2BJyNZJLqKuzRC7J" + "4RmZrAj8rgz5MC4isUiilciW8XRPo5klktRhlGZ%2FmbB4zu5%2BZXsjZM" + "8FU9f8XxPB4hwWoiw7UJkBqJ7419XAGMeNqg1Hj2Gx%2BEFJgyVHWQhSsF" + "fsCGyfOkS87r%2BtaDa8K8OPvZWO3CeLsKftsXgEbTH793RSS1rrxQSMX7" + "R5m5OwgG39%2Fjs590GdNZ1Xr%2BZuRRepD%2Fj%2F3%2FX9h8%3D&SigA" + "lg=http%3A%2F%2Fwww.w3.org%2F2001%2F04%2Fxmldsig-more%23rs" + "a-sha256"; // sign using our algorithm SignatureAlgorithm algo = SignatureAlgorithm.getSignatureAlgorithmForURI(TestConstants.SIGNATURE_ALGORITHM); Signature sig = Signature.getInstance(algo.getAlgorithmName()); sig.initSign(privateKey);//from ww w . ja v a 2 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); /* disabled now: task 1301740 // import our csp settings CasIdmClient idmClient = new CasIdmClient(SharedUtils.getIdmHostName()); SharedUtils.importConfiguration(idmClient, VSPHERE_LOCAL_TENANT, "/csp.xml"); CasIdmAccessor idmAccessor = new CasIdmAccessor(idmClient); log.debug("CSP settings imported successfully"); idmAccessor.setTenant(VSPHERE_LOCAL_TENANT); // create new SamlService SamlServiceFactory factory2 = new DefaultSamlServiceFactory(); CertificateFactory certFactory = CertificateFactory .getInstance("X.509"); CertPath certPath = certFactory.generateCertPath(idmAccessor .getSAMLAuthorityChain()); SamlService service2 = factory2.createSamlService( idmClient.getTenantPrivateKey(VSPHERE_LOCAL_TENANT), SignatureAlgorithm.RSA_SHA256, SignatureAlgorithm.RSA_SHA256, idmClient.getEntityID(VSPHERE_LOCAL_TENANT), certPath); // now call it again with generated signature String vcdSignature = "YkgxdGRqY3FiVlQvUWRLTWRHUjF1V2dJeGJZa0pHNTJJ" + "NGd0RUsyUEtZTDAzcloyNWJ3dmxuLzg3TlNMN1JsSVhYc2NOSkxTaVZ4Mm" + "c4TjNxWTBTLzg2Z0dvYjZVdVU5elY2cEZtQnJ2N0ZFZFdndFJwVDlvZE5w" + "VVpaa3BxQ1ROZVU4STRQYTltMVVOTDB1TUp5ckJvaVBnY3dUbk5LTko4S0" + "dxMWNLMlVuWTZBZGlodW5XaXdTZW5CVDVVRjZ6MHFHWmZ2d25kM2dkTWl4" + "eHY2WWovVElXWUg5REZYN2FJN3R0a3RTaSs5dUhTbUViMTFWRElNcGhpbm" + "1rdldGT3VWWHIxWFR5RUNKYnpLNXhYR3ArZXZ1UGk2TzR1UDlEVjlVdjlU" + "V01uVVNPYkw1aExEUDFadC9Vbzl0S1MySWIwcUp0OGIzVzV2UzVDWVdlUU" + "JGRTBnPT0%3D"; vcdSignature = URLDecoder.decode(vcdSignature, "UTF-8"); vcdSignature = Shared.decodeString(vcdSignature); // just call verifySignature method and expect to not throw service2.verifySignature(message, vcdSignature);*/ }
From source file:be.fedict.eid.dss.protocol.simple.SimpleDSSProtocolService.java
public BrowserPOSTResponse handleResponse(SignatureStatus signatureStatus, byte[] signedDocument, String artifact, X509Certificate signerCertificate, HttpSession httpSession, HttpServletRequest request, HttpServletResponse response) throws Exception { LOG.debug("handleResponse"); String target = retrieveTarget(httpSession); BrowserPOSTResponse browserPOSTResponse = new BrowserPOSTResponse(target); browserPOSTResponse.addAttribute("SignatureStatus", signatureStatus.getStatus()); /*//w w w . j av a 2 s.c om * Add RelayState if available */ String relayState = retrieveRelayState(httpSession); if (null != relayState) { browserPOSTResponse.addAttribute("RelayState", relayState); } if (SignatureStatus.OK == signatureStatus) { String signatureRequest = retrieveSignatureRequest(httpSession); String signatureRequestId = retrieveSignatureRequestId(httpSession); String encodedSignedDocument = Base64.encodeBase64String(signedDocument); if (null != signatureRequest) { browserPOSTResponse.addAttribute("SignatureResponse", encodedSignedDocument); } else { browserPOSTResponse.addAttribute("SignatureResponseId", artifact); } byte[] derSignerCertificate = signerCertificate.getEncoded(); String encodedSignatureCertificate = Base64.encodeBase64String(derSignerCertificate); browserPOSTResponse.addAttribute("SignatureCertificate", encodedSignatureCertificate); KeyStore.PrivateKeyEntry identityPrivateKeyEntry = this.dssContext.getIdentity(); if (null != identityPrivateKeyEntry) { LOG.debug("signing the response"); if (null != signatureRequest) { browserPOSTResponse.addAttribute("ServiceSigned", URLEncoder.encode( "target,SignatureRequest," + "SignatureResponse," + "SignatureCertificate", "UTF-8")); } else { browserPOSTResponse.addAttribute("ServiceSigned", URLEncoder.encode( "target,SignatureRequestId," + "SignatureResponseId," + "SignatureCertificate", "UTF-8")); } // service signature Signature serviceSignature = Signature.getInstance("SHA1withRSA"); serviceSignature.initSign(identityPrivateKeyEntry.getPrivateKey()); serviceSignature.update(target.getBytes()); if (null != signatureRequest) { serviceSignature.update(signatureRequest.getBytes()); serviceSignature.update(encodedSignedDocument.getBytes()); } else { serviceSignature.update(signatureRequestId.getBytes()); serviceSignature.update(artifact.getBytes()); } serviceSignature.update(encodedSignatureCertificate.getBytes()); byte[] serviceSignatureValue = serviceSignature.sign(); String encodedServiceSignature = Base64.encodeBase64String(serviceSignatureValue); browserPOSTResponse.addAttribute("ServiceSignature", encodedServiceSignature); // service certificate chain Certificate[] serviceCertificateChain = identityPrivateKeyEntry.getCertificateChain(); browserPOSTResponse.addAttribute("ServiceCertificateChainSize", Integer.toString(serviceCertificateChain.length)); for (int certIdx = 0; certIdx < serviceCertificateChain.length; certIdx++) { Certificate certificate = serviceCertificateChain[certIdx]; String encodedServiceCertificate = Base64.encodeBase64String(certificate.getEncoded()); browserPOSTResponse.addAttribute("ServiceCertificate." + (certIdx + 1), encodedServiceCertificate); } } } return browserPOSTResponse; }
From source file:org.wso2.carbon.dataservices.core.auth.JWTAuthorizationProvider.java
/*** * Validates the signature of the JWT token. * @param signedJWTToken/*from w ww. j a va 2s . c om*/ * @return * @throws org.apache.axis2.AxisFault */ private Boolean validateSignature(String signedJWTToken) throws AxisFault { //verify signature boolean isVerified = false; String[] split_string = signedJWTToken.split("\\."); String base64EncodedHeader = split_string[0]; String base64EncodedBody = split_string[1]; String base64EncodedSignature = split_string[2]; String decodedHeader = new String(Base64Utils.decode(base64EncodedHeader)); byte[] decodedSignature = Base64Utils.decode(base64EncodedSignature); Pattern pattern = Pattern.compile("^[^:]*:[^:]*:[^:]*:\"(.+)\"}$"); Matcher matcher = pattern.matcher(decodedHeader); String base64EncodedCertThumb = null; if (matcher.find()) { base64EncodedCertThumb = matcher.group(1); } byte[] decodedCertThumb = Base64Utils.decode(base64EncodedCertThumb); KeyStore keystore = getKeyStore(); Certificate publicCert = null; if (keystore != null) { publicCert = publicCerts.get(keystore); if (publicCert == null) { String alias = getAliasForX509CertThumb(decodedCertThumb, keystore); try { publicCert = keystore.getCertificate(alias); } catch (KeyStoreException e) { log.error("Error getting public certificate from keystore using alias"); throw new AxisFault("Error getting public certificate from keystore using alias"); } } } else { log.error("No keystore found"); throw new AxisFault("No keystore found"); } if (publicCert != null) { try { //Create signature instance with signature algorithm and public cert, to verify the signature. Signature verifySig = null; verifySig = Signature.getInstance("SHA256withRSA"); verifySig.initVerify(publicCert); //Update signature with signature data. verifySig.update((base64EncodedHeader + "." + base64EncodedBody).getBytes()); isVerified = verifySig.verify(decodedSignature); } catch (NoSuchAlgorithmException e) { log.error("SHA256withRSA cannot be found"); throw new AxisFault("SHA256withRSA cannot be found"); } catch (InvalidKeyException e) { log.error("Invalid Key"); throw new AxisFault("Invalid Key"); } catch (SignatureException e) { log.error("Signature Object not initialized properly"); throw new AxisFault("Signature Object not initialized properly"); } } else { log.error("No public cert found"); throw new AxisFault("No public cert found"); } if (!isVerified) { log.error("Signature validation failed"); throw new AxisFault("Signature validation failed"); } return isVerified; }
From source file:com.mytalentfolio.h_daforum.CconnectToServer.java
/** * {@code getDataValidity} is used to verify the digital signature of the * received data. If the verification is true then {@code true} is returned * otherwise {@code false}.//www .j ava 2s . c o m * * @param key * the PublicKey received from server. * @param data * the data received from server. * @param serverDataSig * the Signature corresponding to the received data. * @return Boolean value. * @throws NoSuchAlgorithmException * if the specified algorithm is not available. * @throws InvalidKeyException * if publicKey is not valid. * @throws SignatureException * if this Signature instance is not initialized properly. */ private Boolean getDataValidity(PublicKey key, String data, String serverDataSig) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException { Signature s = Signature.getInstance("SHA256withRSA"); s.initVerify(key); byte[] byte_dataFromServer = data.getBytes(); s.update(byte_dataFromServer); byte[] byte_serverDataSig = Base64.decode(serverDataSig, Base64.DEFAULT); Boolean valid = s.verify(byte_serverDataSig); return valid; }
From source file:org.xdi.oxauth.model.crypto.OxAuthCryptoProvider.java
@Override public String sign(String signingInput, String alias, String sharedSecret, SignatureAlgorithm signatureAlgorithm) throws Exception { if (signatureAlgorithm == SignatureAlgorithm.NONE) { return ""; } else if (SignatureAlgorithmFamily.HMAC.equals(signatureAlgorithm.getFamily())) { SecretKey secretKey = new SecretKeySpec(sharedSecret.getBytes(Util.UTF8_STRING_ENCODING), signatureAlgorithm.getAlgorithm()); Mac mac = Mac.getInstance(signatureAlgorithm.getAlgorithm()); mac.init(secretKey);//from ww w .j av a 2 s . c om byte[] sig = mac.doFinal(signingInput.getBytes()); return Base64Util.base64urlencode(sig); } else { // EC or RSA PrivateKey privateKey = getPrivateKey(alias); Signature signature = Signature.getInstance(signatureAlgorithm.getAlgorithm(), "BC"); //Signature signature = Signature.getInstance(signatureAlgorithm.getAlgorithm()); signature.initSign(privateKey); signature.update(signingInput.getBytes()); return Base64Util.base64urlencode(signature.sign()); } }
From source file:test.be.fedict.eid.applet.SecurePinPadReaderTest.java
/** * When creating a non-repudiation signature using PKCS#1-SHA1 (non-naked) * the digest value should also be confirmed via the secure pinpad reader. * // w w w .j a va 2 s. c o m * @throws Exception */ @Test @QualityAssurance(firmware = Firmware.V015Z, approved = true) public void testNonRepSignPKCS1_SHA1() throws Exception { CardChannel cardChannel = this.pcscEid.getCardChannel(); List<X509Certificate> signCertChain = this.pcscEid.getSignCertificateChain(); CommandAPDU setApdu = new CommandAPDU(0x00, 0x22, 0x41, 0xB6, new byte[] { 0x04, // length of following data (byte) 0x80, // algo ref 0x02, // RSA PKCS#1 SHA1 (byte) 0x84, // tag for private key ref (byte) 0x83 }); // non-rep key ResponseAPDU responseApdu = cardChannel.transmit(setApdu); assertEquals(0x9000, responseApdu.getSW()); this.pcscEid.verifyPin(); byte[] data = "My Testcase".getBytes(); MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); byte[] digestValue = messageDigest.digest(data); CommandAPDU computeDigitalSignatureApdu = new CommandAPDU(0x00, 0x2A, 0x9E, 0x9A, digestValue); responseApdu = cardChannel.transmit(computeDigitalSignatureApdu); assertEquals(0x9000, responseApdu.getSW()); byte[] signatureValue = responseApdu.getData(); LOG.debug("signature value size: " + signatureValue.length); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initVerify(signCertChain.get(0).getPublicKey()); signature.update(data); boolean result = signature.verify(signatureValue); assertTrue(result); }