List of usage examples for java.security Signature update
public final void update(ByteBuffer data) throws SignatureException
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 ava 2s. co 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:org.eclipse.licensing.base.LicenseKey.java
public boolean isAuthentic(PublicKey publicKey) { try {/*w w w . j a v a 2 s . c o m*/ Signature signature = Signature.getInstance("SHA1withDSA", "SUN"); signature.initVerify(publicKey); String[] propKeys = properties.keySet().toArray(new String[0]); Arrays.sort(propKeys); for (String propKey : propKeys) { if (!SIGNATURE.equals(propKey)) { String propValue = getProperty(propKey); signature.update(propValue.getBytes("UTF-8")); } } byte[] encodedSignature = getSignature(); if (encodedSignature == null) { return false; } return signature.verify(getSignature()); } catch (GeneralSecurityException | UnsupportedEncodingException e) { e.printStackTrace(); return false; } }
From source file:com.amazonaws.ipnreturnurlvalidation.SignatureUtilsForOutbound.java
/** * Verifies the signature using PKI./*from w w w .j a v a 2 s. c o m*/ */ 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:org.tolven.security.bean.DocProtectionBean.java
/** * Verify the document signature belongs to aPublicKey using aDecryptionKey * to decrypt the document// w ww .j a va 2s . c o m * @param aPublicKey * @param aDecryptionKey * @return */ public boolean verify(DocumentSignature documentSignature, X509Certificate x509Certificate, AccountUser activeAccountUser, PrivateKey userPrivateKey) { try { Signature signature = Signature.getInstance(documentSignature.getSignatureAlgorithm()); signature.initVerify(x509Certificate.getPublicKey()); byte[] document = getDecryptedContent(documentSignature.getDocBase(), activeAccountUser, userPrivateKey); signature.update(document); return signature.verify(documentSignature.getSignature()); } catch (Exception ex) { throw new RuntimeException("Could not verify the signature", ex); } }
From source file:org.xdi.oxauth.model.crypto.OxAuthCryptoProvider.java
@Override public boolean verifySignature(String signingInput, String encodedSignature, String alias, JSONObject jwks, String sharedSecret, SignatureAlgorithm signatureAlgorithm) throws Exception { boolean verified = false; if (signatureAlgorithm == SignatureAlgorithm.NONE) { return Util.isNullOrEmpty(encodedSignature); } else if (SignatureAlgorithmFamily.HMAC.equals(signatureAlgorithm.getFamily())) { String expectedSignature = sign(signingInput, null, sharedSecret, signatureAlgorithm); return expectedSignature.equals(encodedSignature); } else { // EC or RSA PublicKey publicKey = null; try {// w ww . ja v a 2s . co m if (jwks == null) { publicKey = getPublicKey(alias); } else { publicKey = getPublicKey(alias, jwks); } if (publicKey == null) { return false; } byte[] signature = Base64Util.base64urldecode(encodedSignature); Signature verifier = Signature.getInstance(signatureAlgorithm.getAlgorithm(), "BC"); //Signature verifier = Signature.getInstance(signatureAlgorithm.getAlgorithm()); verifier.initVerify(publicKey); verifier.update(signingInput.getBytes()); verified = verifier.verify(signature); } catch (NoSuchAlgorithmException e) { LOG.error(e.getMessage(), e); verified = false; } catch (SignatureException e) { LOG.error(e.getMessage(), e); verified = false; } catch (InvalidKeyException e) { LOG.error(e.getMessage(), e); verified = false; } catch (Exception e) { LOG.error(e.getMessage(), e); verified = false; } } return verified; }
From source file:org.pepstock.jem.node.https.SubmitHandler.java
@Override public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { // extracts the host String host = context.getAttribute(JOB_SUBMIT_IP_ADDRESS_KEY).toString(); // gets HTTP method (uses locale ENGLISH to be sure to have POST) String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); // if NOT post, exception! if (!method.equals(POST)) { LogAppl.getInstance().emit(NodeMessage.JEMC284W, method, host); throw new MethodNotSupportedException( NodeMessage.JEMC284W.toMessage().getFormattedMessage(method, host)); }/*from w w w . j a va 2 s.c o m*/ // gets the URI or the request String target = request.getRequestLine().getUri(); // if is not the same , accepts, exception! if (!target.equalsIgnoreCase(DEFAULT_ACTION)) { LogAppl.getInstance().emit(NodeMessage.JEMC285W, target, host); throw new MethodNotSupportedException( NodeMessage.JEMC285W.toMessage().getFormattedMessage(target, host)); } // checks the HTTP request if (request instanceof HttpEntityEnclosingRequest) { // gets the entity of the request HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); // gets the body in string format String result = EntityUtils.toString(entity, CharSet.DEFAULT); // reads the first line, // with all URL encoded variables String vars = StringUtils.substringBefore(result, DELIMITER); // loads a map with all parms Map<String, String> parms = loadParametersMap(URLEncodedUtils.parse(vars, CharSet.DEFAULT)); // gets the USER String user = parms.get(SubmitParameters.USER.getName()); // if JEM is configured to have the Socket Interceptor on HC // the client MUST provide a SIGNATURE (using own private key) with // the user crypted inside if (Main.getHazelcastConfig().getNetworkConfig().getSocketInterceptorConfig().isEnabled()) { // checks if there is the signature if (parms.containsKey(USER_SIGNATURE_KEY)) { // gets the signature in HEX format String cryptedUserString = parms.get(USER_SIGNATURE_KEY); // gets keys stores KeyStoresInfo keyStoresInfo = KeyStoreUtil.getKeyStoresInfo(); try { // extracts from the USER key store the PUBLIC KEY (upload by UI) for the user PublicKey publicKey = KeysUtil.getPublicKeyByAlias(keyStoresInfo.getUserKeystoreInfo(), user); // creates tne SIGNATURE verifying steps Signature signature = Signature.getInstance("SHA256withRSA"); // sets public key signature.initVerify(publicKey); // sets content to check. It uses USER signature.update(user.getBytes(CharSet.DEFAULT_CHARSET_NAME)); // checks if is verified if (!signature.verify(Hex.decodeHex(cryptedUserString.toCharArray()))) { // if not, log and EXCEPTION LogAppl.getInstance().emit(NodeMessage.JEMC286W, user, host); throw new HttpException( NodeMessage.JEMC286W.toMessage().getFormattedMessage(user, host)); } } catch (MessageException e) { LogAppl.getInstance().emit(NodeMessage.JEMC286W, user, host); throw new ProtocolException(e.getMessage(), e); } catch (KeyException e) { throw new ProtocolException(e.getMessage(), e); } catch (DecoderException e) { throw new ProtocolException(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { throw new ProtocolException(e.getMessage(), e); } catch (SignatureException e) { throw new ProtocolException(e.getMessage(), e); } } else { LogAppl.getInstance().emit(NodeMessage.JEMC287W, user, host); // if here, the signature is missing throw new HttpException(NodeMessage.JEMC287W.toMessage().getFormattedMessage(user, host)); } } // gets JEM environemnt name and its passwrod String env = parms.get(SubmitParameters.ENV.getName()); String password = parms.get(SubmitParameters.PASSWORD.getName()); // checks if password and env are same, // comparing with the HC configuration if (!Main.getHazelcastConfig().getGroupConfig().getName().equalsIgnoreCase(env) || !Main.getHazelcastConfig().getGroupConfig().getPassword().equalsIgnoreCase(password)) { // if not equals, exception LogAppl.getInstance().emit(NodeMessage.JEMC288W, host); throw new HttpException(NodeMessage.JEMC288W.toMessage().getFormattedMessage(host)); } // reads teh second row of the body, with the JCL String jcl = StringUtils.substringAfter(result, DELIMITER); // sets the entity to send back, submitting the job. // it returns the JOBID StringEntity resultEntity = new StringEntity(submit(jcl, user, host, parms), ContentType.create(RESPONSE_MIME_TYPE, CharSet.DEFAULT_CHARSET_NAME)); // sets STATUS code and entity response.setStatusCode(HttpStatus.SC_OK); response.setEntity(resultEntity); } else { // if here, the request is not correct LogAppl.getInstance().emit(NodeMessage.JEMC284W, method, host); throw new MethodNotSupportedException( NodeMessage.JEMC284W.toMessage().getFormattedMessage(method, host)); } }
From source file:com.sshtools.j2ssh.transport.publickey.dsa.SshDssPrivateKey.java
/** * * * @param data// w ww. j a v a 2 s . co m * * @return * * @throws InvalidSshKeySignatureException */ public byte[] generateSignature(byte[] data) throws InvalidSshKeySignatureException { try { Signature sig = Signature.getInstance("SHA1withDSA"); sig.initSign(prvkey); /*java.util.Random rnd = new java.util.Random(); byte[] buffer = new byte[20]; rnd.nextBytes(buffer); sig.update(buffer); byte[] test = sig.sign();*/ sig.update(data); byte[] signature = sig.sign(); byte[] decoded = new byte[40]; SimpleASNReader asn = new SimpleASNReader(signature); asn.getByte(); asn.getLength(); asn.getByte(); byte[] r = asn.getData(); asn.getByte(); byte[] s = asn.getData(); if (r.length >= 20) { System.arraycopy(r, r.length - 20, decoded, 0, 20); } else { System.arraycopy(r, 0, decoded, 20 - r.length, r.length); } if (s.length >= 20) { System.arraycopy(s, s.length - 20, decoded, 20, 20); } else { System.arraycopy(s, 0, decoded, 20 + (20 - s.length), s.length); } if (log.isDebugEnabled()) { BigInteger rb = new BigInteger(1, r); log.debug(rb.toString(16)); BigInteger sb = new BigInteger(1, s); log.debug(sb.toString(16)); log.debug("s length is " + String.valueOf(s.length)); log.debug("r length is " + String.valueOf(r.length)); String str = ""; for (int i = 0; i < signature.length; i++) { str += (Integer.toHexString(signature[i] & 0xFF) + " "); } log.debug("Java signature is " + str); str = ""; for (int i = 0; i < decoded.length; i++) { str += (Integer.toHexString(decoded[i] & 0xFF) + " "); } log.debug("SSH signature is " + str); } ByteArrayWriter baw = new ByteArrayWriter(); baw.writeString(getAlgorithmName()); baw.writeBinaryString(decoded); return baw.toByteArray(); } catch (Exception e) { throw new InvalidSshKeySignatureException(e); } }
From source file:com.example.android.basicandroidkeystore.BasicAndroidKeyStoreFragment.java
/** * Signs the data using the key pair stored in the Android Key Store. This signature can be * used with the data later to verify it was signed by this application. * @return A string encoding of the data signature generated */// w w w. j av a 2s . co m public String signData(String inputStr) throws KeyStoreException, UnrecoverableEntryException, NoSuchAlgorithmException, InvalidKeyException, SignatureException, IOException, CertificateException { byte[] data = inputStr.getBytes(); // BEGIN_INCLUDE(sign_load_keystore) KeyStore ks = KeyStore.getInstance(SecurityConstants.KEYSTORE_PROVIDER_ANDROID_KEYSTORE); // 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 the entry is null, keys were never stored under this alias. * Debug steps in this situation would be: * -Check the list of aliases by iterating over Keystore.aliases(), be sure the alias * exists. * -If that's empty, verify they were both stored and pulled from the same keystore * "AndroidKeyStore" */ if (entry == null) { Log.w(TAG, "No key found under alias: " + mAlias); Log.w(TAG, "Exiting signData()..."); return null; } /* If entry is not a KeyStore.PrivateKeyEntry, it might have gotten stored in a previous * iteration of your application that was using some other mechanism, or been overwritten * by something else using the same keystore with the same alias. * You can determine the type using entry.getClass() and debug from there. */ if (!(entry instanceof KeyStore.PrivateKeyEntry)) { Log.w(TAG, "Not an instance of a PrivateKeyEntry"); Log.w(TAG, "Exiting signData()..."); return null; } // END_INCLUDE(sign_data) // BEGIN_INCLUDE(sign_create_signature) // 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); // Initialize Signature using specified private key s.initSign(((KeyStore.PrivateKeyEntry) entry).getPrivateKey()); // Sign the data, store the result as a Base64 encoded String. s.update(data); byte[] signature = s.sign(); String result = Base64.encodeToString(signature, Base64.DEFAULT); // END_INCLUDE(sign_data) return result; }
From source file:be.fedict.hsm.model.KeyStoreSingletonBean.java
/** * Sign the given digest value./*w w w. j av a 2 s. co m*/ * * @param keyStoreId * @param keyStoreAlias * @param digestAlgo * @param digestValue * @return the signature, or <code>null</code> in case something went wrong. * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws IOException * @throws SignatureException */ @Lock(LockType.READ) public byte[] sign(long keyStoreId, String keyStoreAlias, String digestAlgo, byte[] digestValue) throws NoSuchAlgorithmException, InvalidKeyException, IOException, SignatureException { Map<String, PrivateKeyEntry> keyStoreKeys = this.privateKeyEntries.get(keyStoreId); if (null == keyStoreKeys) { LOG.error("unknown key store: " + keyStoreId); return null; } PrivateKeyEntry privateKeyEntry = keyStoreKeys.get(keyStoreAlias); if (null == privateKeyEntry) { LOG.error("private key for alias not available: " + keyStoreAlias); return null; } PrivateKey privateKey = privateKeyEntry.getPrivateKey(); Signature signature = Signature.getInstance("NONEwithRSA"); signature.initSign(privateKey); ByteArrayOutputStream digestInfo = new ByteArrayOutputStream(); byte[] digestInfoPrefix = digestInfoPrefixes.get(digestAlgo); if (null == digestInfoPrefix) { throw new NoSuchAlgorithmException(digestAlgo); } digestInfo.write(digestInfoPrefix); digestInfo.write(digestValue); signature.update(digestInfo.toByteArray()); return signature.sign(); }
From source file:com.tremolosecurity.proxy.auth.saml2.Saml2SingleLogout.java
@Override public void handleLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException { if (request == null || response == null) { //do nothing return;//from w w w. jav a 2s.c om } String xmlAlg = SAML2Auth.xmlDigSigAlgs.get(digSigAlg); if (xmlAlg == null) { throw new ServletException("Unknown Signiture algorithm : '" + digSigAlg + "'"); } String javaAlg = SAML2Auth.javaDigSigAlgs.get(digSigAlg); UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG); ConfigManager cfgMgr = holder.getConfig(); LogoutRequestBuilder lrb = new LogoutRequestBuilder(); LogoutRequest lr = lrb.buildObject(); DateTime dt = new DateTime(); lr.setIssueInstant(dt); lr.setDestination(logoutURL); byte[] idBytes = new byte[20]; random.nextBytes(idBytes); String id = "f" + Hex.encodeHexString(idBytes); lr.setID(id); IssuerBuilder ib = new IssuerBuilder(); Issuer issuer = ib.buildObject(); issuer.setValue(assertionConsumerServiceURL); lr.setIssuer(issuer); NameIDBuilder nidbpb = new NameIDBuilder(); NameID nid = nidbpb.buildObject(); //nidp.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified"); nid.setFormat(nameIDFormat); //nid.setSPNameQualifier(assertionConsumerServiceURL); nid.setValue(nameID); lr.setNameID(nid); SessionIndexBuilder sib = new SessionIndexBuilder(); SessionIndex si = sib.buildObject(); si.setSessionIndex(sessionIndex); lr.getSessionIndexes().add(si); try { // Get the Subject marshaller Marshaller marshaller = new LogoutRequestMarshaller(); // Marshall the Subject //Element assertionElement = marshaller.marshall(lr); String xml = OpenSAMLUtils.xml2str(lr); xml = xml.substring(xml.indexOf("?>") + 2); if (logger.isDebugEnabled()) { logger.debug("=======AuthnRequest============"); logger.debug(xml); logger.debug("=======AuthnRequest============"); } byte[] bxml = xml.getBytes("UTF-8"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DeflaterOutputStream compressor = new DeflaterOutputStream(baos, new Deflater(Deflater.BEST_COMPRESSION, true)); compressor.write(bxml); compressor.flush(); compressor.close(); String b64 = new String(Base64.encodeBase64(baos.toByteArray())); StringBuffer redirURL = new StringBuffer(); StringBuffer query = new StringBuffer(); idBytes = new byte[20]; random.nextBytes(idBytes); query.append("SAMLRequest=").append(URLEncoder.encode(b64, "UTF-8")).append("&RelayState=") .append(URLEncoder.encode(Hex.encodeHexString(idBytes), "UTF-8")); query.append("&SigAlg=").append(URLEncoder.encode(xmlAlg, "UTF-8")); //http://www.w3.org/2000/09/xmldsig#rsa-sha1 java.security.Signature signer = java.security.Signature.getInstance(javaAlg); PrivateKey sigKey = cfgMgr.getPrivateKey(signingKeyAlias); if (sigKey == null) { throw new ServletException("Signing Key : '" + signingKeyAlias + "' not found"); } signer.initSign(sigKey); signer.update(query.toString().getBytes("UTF-8")); String base64Sig = new String(Base64.encodeBase64(signer.sign())); query.append("&Signature=").append(URLEncoder.encode(base64Sig, "UTF-8")); redirURL.append(logoutURL).append("?").append(query.toString()); if (logger.isDebugEnabled()) { logger.debug("Logout URL : '" + redirURL.toString() + "'"); } //((ProxyResponse) response).removeHeader("Location"); response.sendRedirect(redirURL.toString()); } catch (Exception e) { throw new ServletException("Could not generate logout request", e); } }