List of usage examples for java.security Signature getInstance
public static Signature getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.util.VirtualFirealarmSecurityManager.java
public static boolean verifySignature(String data, String signedData, PublicKey verificationKey) throws VirtualFirealarmDeviceMgtPluginException { Signature signature;//from w w w.ja v a 2 s . c om boolean verified; try { signature = Signature.getInstance(SIGNATURE_ALG); signature.initVerify(verificationKey); signature.update(Base64.decodeBase64(data)); verified = signature.verify(Base64.decodeBase64(signedData)); } catch (NoSuchAlgorithmException e) { String errorMsg = "Algorithm not found exception occurred for Signature instance of [" + SIGNATURE_ALG + "]"; log.error(errorMsg); throw new VirtualFirealarmDeviceMgtPluginException(errorMsg, e); } catch (SignatureException e) { String errorMsg = "Signature exception occurred for Signature instance of [" + SIGNATURE_ALG + "]"; log.error(errorMsg); throw new VirtualFirealarmDeviceMgtPluginException(errorMsg, e); } catch (InvalidKeyException e) { String errorMsg = "InvalidKey exception occurred for signatureKey \n[\n" + verificationKey + "\n]\n"; log.error(errorMsg); throw new VirtualFirealarmDeviceMgtPluginException(errorMsg, e); } return verified; }
From source file:pepperim.util.IMCrypt.java
/** * @param data Data to be verified// w w w . j a v a2s.c o m * @param b64sig Base64-encoded RSA signature * @param key Public key of the signature source * @return true on success, false if the verification fails */ public static boolean RSA_Verify(String data, String b64sig, PublicKey key) { try { Signature verifier = Signature.getInstance("SHA1withRSA"); verifier.initVerify(key); verifier.update(data.getBytes()); return verifier.verify(B64_Dec(b64sig)); } catch (GeneralSecurityException e) { Main.log(e.getMessage()); return false; } }
From source file:org.bankinterface.util.Utils.java
/** * SHA1withRSA???,??//from w ww .j a va 2 s. c o m * * @param data * @param charset * @param certFilePath * @param privateKeyAlias * @param code * @return * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws UnsupportedEncodingException * @throws SignatureException */ public static String signSHA1withRSA(String data, String charset, String certFilePath, String privateKeyAlias, String code) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, UnsupportedEncodingException { PrivateKey privateKey = KeyStoreUtil.getPrivateKey(certFilePath, privateKeyAlias); Signature signature = Signature.getInstance(ALGORITHM_SHA1WITHRSA); signature.initSign(privateKey); signature.update(getBytes(data, charset)); byte[] bytes = signature.sign(); return Utils.encode(bytes, code); }
From source file:com.amazonaws.ipnreturnurlvalidation.SignatureUtilsForOutbound.java
/** * Verifies the signature using PKI.//from ww w. j a v a 2 s. c om */ private boolean validateSignatureV2(Map<String, String> parameters, String urlEndPoint, String httpMethod) throws SignatureException { // 1. input validation. String signature = parameters.get(SIGNATURE_KEYNAME); if (signature == null) { throw new SignatureException("'signature' is missing from the parameters."); } String signatureMethod = parameters.get(SIGNATURE_METHOD_KEYNAME); if (signatureMethod == null) { throw new SignatureException("'signatureMethod' is missing from the parameters."); } String signatureAlgorithm = getSignatureAlgorithm(signatureMethod); if (signatureAlgorithm == null) { throw new SignatureException("'signatureMethod' present in parameters is invalid. " + "Valid signatureMethods are : 'RSA-SHA1'"); } String certificateUrl = parameters.get(CERTIFICATE_URL_KEYNAME); if (certificateUrl == null) { throw new SignatureException("'certificateUrl' is missing from the parameters."); } String certificate = getPublicKeyCertificateAsString(certificateUrl); if (certificate == null) { throw new SignatureException("public key certificate could not fetched from url: " + certificateUrl); } // 2. calculating the string to sign String stringToSign = EMPTY_STRING; try { URL url = new URL(urlEndPoint); String hostHeader = getHostHeader(url); String requestURI = getRequestURI(url); stringToSign = calculateStringToSignV2(parameters, httpMethod, hostHeader, requestURI); } catch (MalformedURLException e) { throw new SignatureException(e); } // 3. verify signature try { CertificateFactory factory = CertificateFactory.getInstance("X.509"); X509Certificate x509Certificate = (X509Certificate) factory .generateCertificate(new ByteArrayInputStream(certificate.getBytes())); Signature signatureInstance = Signature.getInstance(signatureAlgorithm); signatureInstance.initVerify(x509Certificate.getPublicKey()); signatureInstance.update(stringToSign.getBytes(UTF_8_Encoding)); return signatureInstance.verify(Base64.decodeBase64(signature.getBytes())); } catch (CertificateException e) { throw new SignatureException(e); } catch (NoSuchAlgorithmException e) { throw new SignatureException(e); } catch (InvalidKeyException e) { throw new SignatureException(e); } catch (UnsupportedEncodingException e) { throw new SignatureException(e); } }
From source file:com.sshtools.j2ssh.transport.publickey.dsa.SshDssPublicKey.java
/** * * * @param signature/*from www . j a v a 2 s . com*/ * @param data * * @return * * @throws InvalidSshKeySignatureException */ public boolean verifySignature(byte[] signature, byte[] data) throws InvalidSshKeySignatureException { try { // Check for differing version of the transport protocol if (signature.length != 40) { ByteArrayReader bar = new ByteArrayReader(signature); byte[] sig = bar.readBinaryString(); //log.debug("Signature blob is " + new String(sig)); String header = new String(sig); log.debug("Header is " + header); if (!header.equals("ssh-dss")) { throw new InvalidSshKeySignatureException(); } signature = bar.readBinaryString(); //log.debug("Read signature from blob: " + new String(signature)); } // Using a SimpleASNWriter ByteArrayOutputStream r = new ByteArrayOutputStream(); ByteArrayOutputStream s = new ByteArrayOutputStream(); SimpleASNWriter asn = new SimpleASNWriter(); asn.writeByte(0x02); if (((signature[0] & 0x80) == 0x80) && (signature[0] != 0x00)) { r.write(0); r.write(signature, 0, 20); } else { r.write(signature, 0, 20); } asn.writeData(r.toByteArray()); asn.writeByte(0x02); if (((signature[20] & 0x80) == 0x80) && (signature[20] != 0x00)) { s.write(0); s.write(signature, 20, 20); } else { s.write(signature, 20, 20); } asn.writeData(s.toByteArray()); SimpleASNWriter asnEncoded = new SimpleASNWriter(); asnEncoded.writeByte(0x30); asnEncoded.writeData(asn.toByteArray()); byte[] encoded = asnEncoded.toByteArray(); if (log.isDebugEnabled()) { log.debug("Verifying host key signature"); log.debug("Signature length is " + String.valueOf(signature.length)); String hex = ""; for (int i = 0; i < signature.length; i++) { hex += (Integer.toHexString(signature[i] & 0xFF) + " "); } log.debug("SSH: " + hex); hex = ""; for (int i = 0; i < encoded.length; i++) { hex += (Integer.toHexString(encoded[i] & 0xFF) + " "); } log.debug("Encoded: " + hex); } // The previous way /*byte[] encoded; // Determine the encoded length of the big integers int rlen = (((signature[0] & 0x80) == 0x80) ? 0x15 : 0x14); log.debug("rlen=" + String.valueOf(rlen)); int slen = (((signature[20] & 0x80) == 0x80) ? 0x15 : 0x14); log.debug("slen=" + String.valueOf(slen)); byte[] asn1r = { 0x30, (byte) (rlen + slen + 4), 0x02, (byte) rlen }; byte[] asn1s = { 0x02, (byte) slen }; // Create the encoded byte array encoded = new byte[asn1r.length + rlen + asn1s.length + slen]; // Copy the data and encode it into the array System.arraycopy(asn1r, 0, encoded, 0, asn1r.length); // Copy the integer inserting a zero byte if signed int roffset = (((signature[0] & 0x80) == 0x80) ? 1 : 0); System.arraycopy(signature, 0, encoded, asn1r.length + roffset, 20); System.arraycopy(asn1s, 0, encoded, asn1r.length + roffset + 20, asn1s.length); int soffset = (((signature[20] & 0x80) == 0x80) ? 1 : 0); System.arraycopy(signature, 20, encoded, asn1r.length + roffset + 20 + asn1s.length + soffset, 20); */ Signature sig = Signature.getInstance("SHA1withDSA"); sig.initVerify(pubkey); sig.update(data); return sig.verify(encoded); } catch (NoSuchAlgorithmException nsae) { throw new InvalidSshKeySignatureException(); } catch (InvalidKeyException ike) { throw new InvalidSshKeySignatureException(); } catch (IOException ioe) { throw new InvalidSshKeySignatureException(); } catch (SignatureException se) { throw new InvalidSshKeySignatureException(); } }
From source file:com.adito.security.pki.dsa.SshDssPublicKey.java
/** * * * @param signature//from w w w.ja v a2s .c o m * @param data * * @return * * @throws InvalidSshKeySignatureException */ public boolean verifySignature(byte[] signature, byte[] data) throws InvalidSignatureException { try { // Check for differing version of the transport protocol if (signature.length != 40) { ByteArrayReader bar = new ByteArrayReader(signature); byte[] sig = bar.readBinaryString(); //if (log.isDebugEnabled()) {log.debug("Signature blob is " + new String(sig));} String header = new String(sig); if (log.isDebugEnabled()) log.debug("Header is " + header); if (!header.equals("ssh-dss")) { throw new InvalidSignatureException(); } signature = bar.readBinaryString(); //if (log.isDebugEnabled()) {log.debug("Read signature from blob: " + new String(signature));} } // Using a SimpleASNWriter ByteArrayOutputStream r = new ByteArrayOutputStream(); ByteArrayOutputStream s = new ByteArrayOutputStream(); SimpleASNWriter asn = new SimpleASNWriter(); asn.writeByte(0x02); if (((signature[0] & 0x80) == 0x80) && (signature[0] != 0x00)) { r.write(0); r.write(signature, 0, 20); } else { r.write(signature, 0, 20); } asn.writeData(r.toByteArray()); asn.writeByte(0x02); if (((signature[20] & 0x80) == 0x80) && (signature[20] != 0x00)) { s.write(0); s.write(signature, 20, 20); } else { s.write(signature, 20, 20); } asn.writeData(s.toByteArray()); SimpleASNWriter asnEncoded = new SimpleASNWriter(); asnEncoded.writeByte(0x30); asnEncoded.writeData(asn.toByteArray()); byte[] encoded = asnEncoded.toByteArray(); if (log.isDebugEnabled()) { log.debug("Verifying host key signature"); log.debug("Signature length is " + String.valueOf(signature.length)); String hex = ""; for (int i = 0; i < signature.length; i++) { hex += (Integer.toHexString(signature[i] & 0xFF) + " "); } log.debug("SSH: " + hex); hex = ""; for (int i = 0; i < encoded.length; i++) { hex += (Integer.toHexString(encoded[i] & 0xFF) + " "); } log.debug("Encoded: " + hex); } // The previous way /*byte[] encoded; // Determine the encoded length of the big integers int rlen = (((signature[0] & 0x80) == 0x80) ? 0x15 : 0x14); log.debug("rlen=" + String.valueOf(rlen)); int slen = (((signature[20] & 0x80) == 0x80) ? 0x15 : 0x14); log.debug("slen=" + String.valueOf(slen)); byte[] asn1r = { 0x30, (byte) (rlen + slen + 4), 0x02, (byte) rlen }; byte[] asn1s = { 0x02, (byte) slen }; // Create the encoded byte array encoded = new byte[asn1r.length + rlen + asn1s.length + slen]; // Copy the data and encode it into the array System.arraycopy(asn1r, 0, encoded, 0, asn1r.length); // Copy the integer inserting a zero byte if signed int roffset = (((signature[0] & 0x80) == 0x80) ? 1 : 0); System.arraycopy(signature, 0, encoded, asn1r.length + roffset, 20); System.arraycopy(asn1s, 0, encoded, asn1r.length + roffset + 20, asn1s.length); int soffset = (((signature[20] & 0x80) == 0x80) ? 1 : 0); System.arraycopy(signature, 20, encoded, asn1r.length + roffset + 20 + asn1s.length + soffset, 20); */ Signature sig = Signature.getInstance("SHA1withDSA"); sig.initVerify(pubkey); sig.update(data); return sig.verify(encoded); } catch (NoSuchAlgorithmException nsae) { throw new InvalidSignatureException(); } catch (java.security.InvalidKeyException ike) { throw new InvalidSignatureException(); } catch (IOException ioe) { throw new InvalidSignatureException(); } catch (SignatureException se) { throw new InvalidSignatureException(); } }
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 2 s.co m * @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:be.fedict.eid.dss.protocol.simple.client.SignatureRequestUtil.java
/** * Constructs a DSS Simple Protocol service signature. * <p/>//from ww w .ja va2 s . co m * If no spIdentity is specified returns <code>null</code> * * @param spIdentity * the SP Identity used for signing. * @param signatureRequest * signature request, if <code>null</code> signatureRequestId * needs to be specified. * @param signatureRequestId * signature request ID, if <code>null</code>, signatureRequest * needs to be specified * @param target * required target * @param language * optional language param * @param contentType * optional document content type * @param relayState * optional relay state * @return service signature DO containing the signature value, service * signed property listing up all signed properties and the SP * certificate chain. * @throws NoSuchAlgorithmException * algorithm to sign/digest not found. * @throws InvalidKeyException * signing key not valid * @throws SignatureException * signature creation failure * @throws CertificateEncodingException * certificate encoding failure */ public static ServiceSignatureDO getServiceSignature( KeyStore.PrivateKeyEntry spIdentity, String signatureRequest, String signatureRequestId, String target, String language, String contentType, String relayState) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, CertificateEncodingException { LOG.debug("get service signature"); if (null == spIdentity) { LOG.warn("No SP Identity specified, no signature added."); return null; } if (null == signatureRequest && null == signatureRequestId) { throw new RuntimeException( "Either \"SignatureRequest\" or " + "\"SignatureRequestId\" needs to be provided."); } // construct service signature // TODO: configurable? Signature serviceSignature = Signature.getInstance("SHA1withRSA"); serviceSignature.initSign(spIdentity.getPrivateKey()); serviceSignature.update(target.getBytes()); if (null != signatureRequest) { serviceSignature.update(signatureRequest.getBytes()); } else { serviceSignature.update(signatureRequestId.getBytes()); } if (null != language) { serviceSignature.update(language.getBytes()); } if (null != contentType) { serviceSignature.update(contentType.getBytes()); } if (null != relayState) { serviceSignature.update(relayState.getBytes()); } byte[] serviceSignatureValue = serviceSignature.sign(); String encodedServiceSignature = Base64.encodeBase64String(serviceSignatureValue); // construct service signed String serviceSigned = "target"; if (null != signatureRequest) { serviceSigned += ",SignatureRequest"; } else { serviceSigned += ",SignatureRequestId"; } if (null != language) { serviceSigned += ",language"; } if (null != contentType) { serviceSigned += ",ContentType"; } if (null != relayState) { serviceSigned += ",RelayState"; } // construct service certificate chain java.security.cert.Certificate[] serviceCertificateChain = spIdentity.getCertificateChain(); String serviceCertificateChainSize = Integer.toString(serviceCertificateChain.length); List<String> serviceCertificates = new LinkedList<String>(); for (java.security.cert.Certificate certificate : serviceCertificateChain) { String encodedServiceCertificate = Base64.encodeBase64String(certificate.getEncoded()); serviceCertificates.add(encodedServiceCertificate); } return new ServiceSignatureDO(serviceSigned, encodedServiceSignature, serviceCertificateChainSize, serviceCertificates); }
From source file:be.fedict.eid.dss.protocol.simple.SimpleDSSProtocolService.java
private void verifyServiceSignature(String serviceSigned, String target, String signatureRequest, String signatureRequestId, String contentType, String language, String relayState, byte[] serviceSignatureValue, List<X509Certificate> serviceCertificateChain) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { LOG.debug("verifying service signature"); X509Certificate serviceCertificate = serviceCertificateChain.get(0); LOG.debug("service identity: " + serviceCertificate.getSubjectX500Principal()); Signature serviceSignature = Signature.getInstance("SHA1withRSA"); serviceSignature.initVerify(serviceCertificate); StringTokenizer serviceSignedStringTokenizer = new StringTokenizer(serviceSigned, ","); while (serviceSignedStringTokenizer.hasMoreTokens()) { String serviceSignedElement = serviceSignedStringTokenizer.nextToken(); LOG.debug("service signed: " + serviceSignedElement); byte[] data; if ("target".equals(serviceSignedElement)) { data = target.getBytes();/*from w w w . j av a 2 s.c o m*/ } else if ("SignatureRequest".equals(serviceSignedElement)) { data = signatureRequest.getBytes(); } else if ("SignatureRequestId".equals(serviceSignedElement)) { data = signatureRequestId.getBytes(); } else if ("ContentType".equals(serviceSignedElement)) { data = contentType.getBytes(); } else if ("language".equals(serviceSignedElement)) { data = language.getBytes(); } else if ("RelayState".equals(serviceSignedElement)) { data = relayState.getBytes(); } else { throw new SecurityException("service signed unknown element: " + serviceSignedElement); } serviceSignature.update(data); } boolean valid = serviceSignature.verify(serviceSignatureValue); if (!valid) { throw new SecurityException("service signature not valid"); } }
From source file:org.esupportail.pay.services.PayBoxService.java
public boolean checkPayboxSignature(String queryString, String signature) { String sData = queryString.substring(0, queryString.lastIndexOf("&")); try {/*from ww w .java2 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; } }