List of usage examples for java.security Signature initVerify
public final void initVerify(Certificate certificate) throws InvalidKeyException
From source file:org.esupportail.pay.services.PayBoxService.java
public boolean checkPayboxSignature(String queryString, String signature) { String sData = queryString.substring(0, queryString.lastIndexOf("&")); try {/* ww w .j av a 2 s .c o m*/ Signature sig = Signature.getInstance("SHA1WithRSA"); byte[] sigBytes = Base64.decodeBase64(signature.getBytes()); sig.initVerify(payboxPublicKey); sig.update(sData.getBytes()); boolean signatureOk = sig.verify(sigBytes); if (!signatureOk) { log.error("Erreur lors de la vrification de la signature, les donnes ne correspondent pas."); log.error(sData); log.error(signature); } return signatureOk; } catch (Exception e) { log.warn("Pb when checking SSL signature of Paybox", e); return false; } }
From source file:mx.bigdata.sat.cfdi.CFDv33.java
@Override public void verificar() throws Exception { String certStr = document.getCertificado(); Base64 b64 = new Base64(); byte[] cbs = b64.decode(certStr); X509Certificate cert = KeyLoaderFactory .createInstance(KeyLoaderEnumeration.PUBLIC_KEY_LOADER, new ByteArrayInputStream(cbs)).getKey(); String sigStr = document.getSello(); byte[] signature = b64.decode(sigStr); byte[] bytes = getOriginalBytes(); Signature sig = Signature.getInstance("SHA256withRSA"); sig.initVerify(cert); sig.update(bytes);/*from w w w.j a v a 2 s .c o m*/ boolean bool = sig.verify(signature); if (!bool) { throw new Exception("Invalid signature"); } }
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//www . 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:org.wso2.carbon.dataservices.core.auth.JWTAuthorizationProvider.java
/*** * Validates the signature of the JWT token. * @param signedJWTToken//from w w w .j a v a 2 s . 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:org.ejbca.core.protocol.cmp.CmpTestCase.java
protected static void checkCmpResponseGeneral(byte[] retMsg, String issuerDN, X500Name userDN, Certificate cacert, byte[] senderNonce, byte[] transId, boolean signed, String pbeSecret, String expectedSignAlg)/*from w w w. j ava2 s .c o m*/ throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException { assertNotNull("No response from server.", retMsg); assertTrue("Response was of 0 length.", retMsg.length > 0); boolean pbe = (pbeSecret != null); // // Parse response message // ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(retMsg)); PKIMessage respObject = null; try { respObject = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull(respObject); // The signer, i.e. the CA, check it's the right CA PKIHeader header = respObject.getHeader(); // Check that the message is signed with the correct digest alg if (StringUtils.isEmpty(expectedSignAlg)) { expectedSignAlg = PKCSObjectIdentifiers.sha1WithRSAEncryption.getId(); } // if cacert is ECDSA we should expect an ECDSA signature alg //if (AlgorithmTools.getSignatureAlgorithm(cacert).contains("ECDSA")) { // expectedSignAlg = X9ObjectIdentifiers.ecdsa_with_SHA1.getId(); //} else if(AlgorithmTools.getSignatureAlgorithm(cacert).contains("ECGOST3410")) { // expectedSignAlg = CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001.getId(); //} else if(AlgorithmTools.getSignatureAlgorithm(cacert).contains("DSTU4145")) { // expectedSignAlg = (new ASN1ObjectIdentifier(CesecoreConfiguration.getOidDstu4145())).getId(); //} if (signed) { AlgorithmIdentifier algId = header.getProtectionAlg(); assertNotNull( "Protection algorithm was null when expecting a signed response, this was propably an unprotected error message: " + header.getFreeText(), algId); assertEquals(expectedSignAlg, algId.getAlgorithm().getId()); } if (pbe) { AlgorithmIdentifier algId = header.getProtectionAlg(); assertNotNull( "Protection algorithm was null when expecting a pbe protected response, this was propably an unprotected error message: " + header.getFreeText(), algId); assertEquals("Protection algorithm id: " + algId.getAlgorithm().getId(), CMPObjectIdentifiers.passwordBasedMac.getId(), algId.getAlgorithm().getId()); // 1.2.840.113549.1.1.5 - SHA-1 with RSA Encryption } // Check that the signer is the expected CA assertEquals(header.getSender().getTagNo(), 4); X500Name expissuer = new X500Name(issuerDN); X500Name actissuer = new X500Name(header.getSender().getName().toString()); assertEquals(expissuer, actissuer); if (signed) { // Verify the signature byte[] protBytes = CmpMessageHelper.getProtectedBytes(respObject); DERBitString bs = respObject.getProtection(); Signature sig; try { sig = Signature.getInstance(expectedSignAlg, "BC"); sig.initVerify(cacert); sig.update(protBytes); boolean ret = sig.verify(bs.getBytes()); assertTrue(ret); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); assertTrue(false); } catch (NoSuchProviderException e) { e.printStackTrace(); assertTrue(false); } catch (InvalidKeyException e) { e.printStackTrace(); assertTrue(false); } catch (SignatureException e) { e.printStackTrace(); assertTrue(false); } } if (pbe) { ASN1OctetString os = header.getSenderKID(); assertNotNull(os); String keyId = CmpMessageHelper.getStringFromOctets(os); log.debug("Found a sender keyId: " + keyId); // Verify the PasswordBased protection of the message byte[] protectedBytes = CmpMessageHelper.getProtectedBytes(respObject); DERBitString protection = respObject.getProtection(); AlgorithmIdentifier pAlg = header.getProtectionAlg(); log.debug("Protection type is: " + pAlg.getAlgorithm().getId()); PBMParameter pp = PBMParameter.getInstance(pAlg.getParameters()); int iterationCount = pp.getIterationCount().getPositiveValue().intValue(); log.debug("Iteration count is: " + iterationCount); AlgorithmIdentifier owfAlg = pp.getOwf(); // Normal OWF alg is 1.3.14.3.2.26 - SHA1 log.debug("Owf type is: " + owfAlg.getAlgorithm().getId()); AlgorithmIdentifier macAlg = pp.getMac(); // Normal mac alg is 1.3.6.1.5.5.8.1.2 - HMAC/SHA1 log.debug("Mac type is: " + macAlg.getAlgorithm().getId()); byte[] salt = pp.getSalt().getOctets(); // log.info("Salt is: "+new String(salt)); byte[] raSecret = pbeSecret != null ? pbeSecret.getBytes() : new byte[0]; byte[] basekey = new byte[raSecret.length + salt.length]; System.arraycopy(raSecret, 0, basekey, 0, raSecret.length); for (int i = 0; i < salt.length; i++) { basekey[raSecret.length + i] = salt[i]; } // Construct the base key according to rfc4210, section 5.1.3.1 MessageDigest dig = MessageDigest.getInstance(owfAlg.getAlgorithm().getId(), BouncyCastleProvider.PROVIDER_NAME); for (int i = 0; i < iterationCount; i++) { basekey = dig.digest(basekey); dig.reset(); } // HMAC/SHA1 os normal 1.3.6.1.5.5.8.1.2 or 1.2.840.113549.2.7 String macOid = macAlg.getAlgorithm().getId(); Mac mac = Mac.getInstance(macOid, BouncyCastleProvider.PROVIDER_NAME); SecretKey key = new SecretKeySpec(basekey, macOid); mac.init(key); mac.reset(); mac.update(protectedBytes, 0, protectedBytes.length); byte[] out = mac.doFinal(); // My out should now be the same as the protection bits byte[] pb = protection.getBytes(); boolean ret = Arrays.equals(out, pb); assertTrue(ret); } // --SenderNonce // SenderNonce is something the server came up with, but it should be 16 // chars byte[] nonce = header.getSenderNonce().getOctets(); assertEquals(nonce.length, 16); // --Recipient Nonce // recipient nonce should be the same as we sent away as sender nonce nonce = header.getRecipNonce().getOctets(); assertEquals(new String(nonce), new String(senderNonce)); // --Transaction ID // transid should be the same as the one we sent nonce = header.getTransactionID().getOctets(); assertEquals(new String(nonce), new String(transId)); }
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}.// w w w . ja v a 2s . co 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:com.mycompany.bankinterface.crypto.Signer.java
public boolean isVerified(String clearText, String signature, String signerPublicKey) throws SignerException { boolean isVerified = false; byte[] signerPublicKeyBytes = Base64.decodeBase64(signerPublicKey); byte[] signatureAsBytes = Base64.decodeBase64(signature); X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(signerPublicKeyBytes); KeyFactory keyFactory;/*from w ww. jav a2 s .co m*/ try { keyFactory = KeyFactory.getInstance(PUBLIC_KEY_ALGORITHM, PROVIDER); } catch (NoSuchAlgorithmException | NoSuchProviderException ex) { throw new SignerException("Failed to create key factory", ex); } PublicKey pubKey; try { pubKey = keyFactory.generatePublic(pubKeySpec); } catch (InvalidKeySpecException ex) { throw new SignerException("Failed to create public key", ex); } Signature dsa; try { dsa = Signature.getInstance(SIGNER_ALGORITHM, PROVIDER); } catch (NoSuchAlgorithmException | NoSuchProviderException ex) { throw new SignerException("Could not get signing instance", ex); } try { dsa.initVerify(pubKey); dsa.update(clearText.getBytes()); isVerified = dsa.verify(signatureAsBytes); } catch (InvalidKeyException | SignatureException ex) { throw new SignerException("Could not verify data", ex); } return isVerified; }
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());/*www . jav a 2 s . co m*/ 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.axelor.apps.account.service.payment.PayboxService.java
/** * verification signature RSA des donnees avec cle publique * @param dataBytes//w ww . j a v a 2 s . c o m * @param sigBytes * @param pubKey * @return * @throws Exception */ private boolean verify(byte[] dataBytes, byte[] sigBytes, String sigAlg, PublicKey pubKey) throws Exception { Signature signature = Signature.getInstance(sigAlg); signature.initVerify(pubKey); signature.update(dataBytes); return signature.verify(sigBytes); }