List of usage examples for java.security Signature getInstance
public static Signature getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:com.alvexcore.share.jscript.JSShareExtensionRegistry.java
@SuppressWarnings("serial") public String removeSignature(String data) { if (data == null) return null; int idx = data.indexOf("\n"); if (idx <= 20) return null; String s = data.substring(0, idx); if (!s.startsWith("SIGNATURE:")) return null; s = s.substring(10);/*from ww w . j av a 2s . c o m*/ Signature sig; try { sig = Signature.getInstance("SHA1withRSA"); sig.initVerify(new PublicKey() { @Override public String getAlgorithm() { return "RSA"; } @Override public String getFormat() { return "X.509"; } @Override public byte[] getEncoded() { return new byte[] { 48, -126, 1, 34, 48, 13, 6, 9, 42, -122, 72, -122, -9, 13, 1, 1, 1, 5, 0, 3, -126, 1, 15, 0, 48, -126, 1, 10, 2, -126, 1, 1, 0, -115, 117, -12, -114, -121, -128, 76, 99, -114, -37, 107, -44, 108, 36, 38, 99, 13, -93, -73, -62, 44, 10, 120, -22, -31, -25, -109, 45, 24, -47, 59, -87, -39, -29, -35, -96, 13, -117, 31, -98, 107, 80, -104, -72, 5, -32, 79, -115, 59, -87, 109, -121, 104, 36, -14, 123, -113, 87, -50, 40, -52, -59, -52, -7, -13, -34, 17, -29, -39, 63, -62, -44, 51, 68, -98, -115, -13, 10, -7, -101, 81, -72, 81, 91, -94, 91, -94, 6, 65, 84, 35, -121, 14, -103, 38, 6, 59, 115, -110, 4, -63, -89, -22, 27, 126, -96, -32, 97, 105, -108, 14, -23, -62, -89, -41, 30, -126, -114, 121, 17, 125, 18, 124, -114, 0, -13, 85, -11, 92, 87, -16, 3, 30, 23, -126, -33, 122, 126, -72, -95, 29, 73, -24, -34, -27, -41, 109, -77, -108, -34, 91, -36, -3, 112, 13, 30, 111, 9, -105, 7, 8, -70, 95, -128, -82, -13, -4, 127, -58, 68, -114, 89, 69, 101, -106, -123, -36, -90, -110, -44, 45, 25, 107, 52, 6, 69, -35, 89, 7, -59, 96, 4, 97, 29, 24, -50, -59, -40, 104, 70, 68, -28, 77, 94, -57, -38, 91, -99, 37, -89, 105, -126, 52, 80, 111, 107, -69, 22, 39, -70, -5, 87, -33, -77, -79, -64, 76, -12, -58, -37, 56, 102, 17, 59, 11, -73, -68, -96, -108, -47, 13, -113, -77, 60, 88, -128, 19, -42, 12, 49, 89, 7, -11, -11, -87, 37, 2, 3, 1, 0, 1 }; } }); String d = data.substring(idx + 1); sig.update(d.getBytes()); if (sig.verify(Base64.decodeBase64(s))) return d; else return null; } catch (Exception e) { return null; } }
From source file:org.carewebframework.api.security.CipherUtil.java
/** * Returns the digital signature for the specified content. * /*from ww w .j a va 2s . co m*/ * @param key The private key to sign the content. * @param content The content to sign. * @return The digital signature. * @throws Exception Unspecified exception. */ public static String sign(PrivateKey key, String content) throws Exception { Signature signature = Signature.getInstance(SIGN_ALGORITHM); signature.initSign(key); signature.update(content.getBytes()); return Base64.encodeBase64String(signature.sign()); }
From source file:org.jvnet.hudson.update_center.Signing.java
/** * Generates a canonicalized JSON format of the given object, and put the signature in it. * Because it mutates the signed object itself, validating the signature needs a bit of work, * but this enables a signature to be added transparently. *///from w ww.j a va 2 s. c om public void sign(JSONObject o) throws GeneralSecurityException, IOException { JSONObject sign = new JSONObject(); List<X509Certificate> certs = getCertificateChain(); X509Certificate signer = certs.get(0); // the first one is the signer, and the rest is the chain to a root CA. // this is for computing a digest MessageDigest sha1 = MessageDigest.getInstance("SHA1"); DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(), sha1); // this is for computing a signature PrivateKey key = ((KeyPair) new PEMReader(new FileReader(privateKey)).readObject()).getPrivate(); Signature sig = Signature.getInstance("SHA1withRSA"); sig.initSign(key); SignatureOutputStream sos = new SignatureOutputStream(sig); // this is for verifying that signature validates Signature verifier = Signature.getInstance("SHA1withRSA"); verifier.initVerify(signer.getPublicKey()); SignatureOutputStream vos = new SignatureOutputStream(verifier); o.writeCanonical(new OutputStreamWriter(new TeeOutputStream(new TeeOutputStream(dos, sos), vos), "UTF-8")); // digest byte[] digest = sha1.digest(); sign.put("digest", new String(Base64.encodeBase64(digest))); // signature byte[] s = sig.sign(); sign.put("signature", new String(Base64.encodeBase64(s))); // and certificate chain JSONArray a = new JSONArray(); for (X509Certificate cert : certs) a.add(new String(Base64.encodeBase64(cert.getEncoded()))); sign.put("certificates", a); // did the signature validate? if (!verifier.verify(s)) throw new GeneralSecurityException( "Signature failed to validate. Either the certificate and the private key weren't matching, or a bug in the program."); o.put("signature", sign); }
From source file:GCS_Auth.java
public GCS_Auth(String client_id, String key) { String SCOPE = "https://www.googleapis.com/auth/shoppingapi"; SCOPE = SCOPE + " " + "https://www.googleapis.com/auth/structuredcontent"; try {//from w ww . j a va 2 s . co m String jwt_header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}"; long now = System.currentTimeMillis() / 1000L; long exp = now + 3600; String iss = client_id; String claim = "{\"iss\":\"" + iss + "\",\"scope\":\"" + SCOPE + "\",\"aud\":\"https://accounts.google.com/o/oauth2/token\",\"exp\":" + exp + ",\"iat\":" + now + "}"; String jwt = Base64.encodeBase64URLSafeString(jwt_header.getBytes()) + "." + Base64.encodeBase64URLSafeString(claim.getBytes("UTF-8")); byte[] jwt_data = jwt.getBytes("UTF8"); Signature sig = Signature.getInstance("SHA256WithRSA"); KeyStore ks = java.security.KeyStore.getInstance("PKCS12"); ks.load(new FileInputStream(key), "notasecret".toCharArray()); sig.initSign((PrivateKey) ks.getKey("privatekey", "notasecret".toCharArray())); sig.update(jwt_data); byte[] signatureBytes = sig.sign(); String b64sig = Base64.encodeBase64URLSafeString(signatureBytes); String assertion = jwt + "." + b64sig; //System.out.println("Assertion: " + assertion); String data = "grant_type=assertion"; data += "&" + "assertion_type" + "=" + URLEncoder.encode("http://oauth.net/grant_type/jwt/1.0/bearer", "UTF-8"); data += "&" + "assertion=" + URLEncoder.encode(assertion, "UTF-8"); URLConnection conn = null; try { URL url = new URL("https://accounts.google.com/o/oauth2/token"); conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { if (line.split(":").length > 0) if (line.split(":")[0].trim().equals("\"access_token\"")) access_token = line.split(":")[1].trim().replace("\"", "").replace(",", ""); System.out.println(line); } wr.close(); rd.close(); } catch (Exception ex) { InputStream error = ((HttpURLConnection) conn).getErrorStream(); BufferedReader br = new BufferedReader(new InputStreamReader(error)); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); } System.out.println("Error: " + ex + "\n " + sb.toString()); } //System.out.println(access_token); } catch (Exception ex) { System.out.println("Error: " + ex); } }
From source file:com.streamsets.lib.security.util.DataSignature.java
public Verifier getVerifier(final PublicKey publicKey) { return new Verifier() { @Override/*from ww w . ja v a 2 s . c om*/ public boolean verify(byte[] data, byte[] signature) throws GeneralSecurityException { Signature signer = Signature.getInstance("SHA1withDSA"); signer.initVerify(publicKey); signer.update(data); return signer.verify(signature); } }; }
From source file:eu.europa.esig.dss.extension.AbstractTestExtension.java
protected SignatureValue sign(SignatureAlgorithm algo, MockPrivateKeyEntry privateKey, ToBeSigned bytesToSign) throws GeneralSecurityException { final Signature signature = Signature.getInstance(algo.getJCEId()); signature.initSign(privateKey.getPrivateKey()); signature.update(bytesToSign.getBytes()); final byte[] signatureValue = signature.sign(); return new SignatureValue(algo, signatureValue); }
From source file:test.be.fedict.eid.applet.model.AuthenticationSignatureServiceBean.java
public PreSignResult preSign(List<X509Certificate> authnCertificateChain, AuthenticationSignatureContext authenticationSignatureContext) { LOG.debug("preSign"); LOG.debug("authn cert chain size: " + authnCertificateChain.size()); KeyStore proxyKeyStore;/* w w w . ja v a2 s . com*/ final ProxyPrivateKey proxyPrivateKey; try { proxyKeyStore = KeyStore.getInstance("ProxyBeID"); proxyKeyStore.load(null); proxyPrivateKey = (ProxyPrivateKey) proxyKeyStore.getKey("Signature", null); } catch (Exception e) { throw new RuntimeException("error loading ProxyBeID keystore"); } FutureTask<String> signTask = new FutureTask<String>(new Callable<String>() { public String call() throws Exception { final Signature signature = Signature.getInstance("SHA256withRSA"); signature.initSign(proxyPrivateKey); final byte[] toBeSigned = "hello world".getBytes(); signature.update(toBeSigned); final byte[] signatureValue = signature.sign(); LOG.debug("received signature value"); return "signature result"; } }); final ExecutorService executor = Executors.newFixedThreadPool(1); executor.execute(signTask); authenticationSignatureContext.store("key", proxyPrivateKey); authenticationSignatureContext.store("signTask", signTask); byte[] digestValue; try { digestValue = proxyPrivateKey.getDigestInfo().getDigestValue(); } catch (InterruptedException e) { throw new RuntimeException("signature error: " + e.getMessage(), e); } DigestInfo digestInfo = new DigestInfo(digestValue, "SHA-256", "WS-Security message"); PreSignResult preSignResult = new PreSignResult(digestInfo, true); return preSignResult; }
From source file:me.disconnect.mobile.billing.Security.java
/** * Verifies that the signature from the server matches the computed * signature on the data. Returns true if the data is correctly signed. * * @param publicKey public key associated with the developer account * @param signedData signed data from server * @param signature server signature//from w w w .ja v a 2 s. c o m * @return true if the data and signature match */ public static boolean verify(PublicKey publicKey, String signedData, String signature) { Signature sig; try { sig = Signature.getInstance(SIGNATURE_ALGORITHM); sig.initVerify(publicKey); sig.update(signedData.getBytes()); if (!sig.verify(Base64.decode(signature))) { Log.e(TAG, "Signature verification failed."); return false; } return true; } catch (NoSuchAlgorithmException e) { Log.e(TAG, "NoSuchAlgorithmException."); } catch (InvalidKeyException e) { Log.e(TAG, "Invalid key specification."); } catch (SignatureException e) { Log.e(TAG, "Signature exception."); } catch (Base64DecoderException e) { Log.e(TAG, "Base64 decoding failed."); } catch (RuntimeException e) { Log.e(TAG, "RuntimeException in Security.verify():"); e.printStackTrace(); } return false; }
From source file:com.dev.cty.utils.googleplay.Security.java
/** * Verifies that the signature from the server matches the computed * signature on the data. Returns true if the data is correctly signed. * * @param publicKey public key associated with the developer account * @param signedData signed data from server * @param signature server signature//from ww w . j av a2 s . c om * @return true if the data and signature match */ public static boolean verify(PublicKey publicKey, String signedData, String signature) { Signature sig; try { sig = Signature.getInstance(SIGNATURE_ALGORITHM); sig.initVerify(publicKey); sig.update(signedData.getBytes()); if (!sig.verify(Base64.decode(signature))) { logger.info("Signature verification failed."); return false; } return true; } catch (NoSuchAlgorithmException e) { logger.info("NoSuchAlgorithmException."); } catch (InvalidKeyException e) { logger.info("Invalid key specification."); } catch (SignatureException e) { logger.info("Signature exception."); } catch (Base64DecoderException e) { logger.info("Base64 decoding failed."); } return false; }
From source file:org.apache.abdera2.common.security.HashHelper.java
public static String sig(PrivateKey key, String alg, byte[] mat) { try {// w w w . j a va 2 s . c o m Signature sig = Signature.getInstance(alg); sig.initSign((PrivateKey) key); sig.update(mat); byte[] dat = sig.sign(); return Base64.encodeBase64URLSafeString(dat); } catch (Throwable t) { throw ExceptionHelper.propogate(t); } }