List of usage examples for java.security Signature getInstance
public static Signature getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:com.sshtools.j2ssh.transport.publickey.dsa.SshDssPrivateKey.java
/** * * * @param data// ww w .j a va2 s .c o 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.google.samples.apps.abelana.AbelanaThings.java
private static String signData(String data) { try {/*from ww w . ja va 2 s . c o m*/ if (signer == null) { signer = Signature.getInstance("SHA256withRSA"); signer.initSign(credential.getServiceAccountPrivateKey()); } signer.update(data.getBytes("UTF-8")); byte[] rawSignature = signer.sign(); return new String(Base64.encode(rawSignature, Base64.DEFAULT)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (SignatureException e) { e.printStackTrace(); } return null; }
From source file:com.amazonaws.services.sns.util.SignatureChecker.java
/** * Does the actual Java cryptographic verification of the signature. This * method does no handling of the many rare exceptions it is required to * catch.//from ww w .j a v a 2s .c om * * This can also be used to verify the signature from the x-amz-sns-signature http header * * @param message * Exact string that was signed. In the case of the x-amz-sns-signature header the * signing string is the entire post body * @param signature * Base64-encoded signature of the message * @return */ public boolean verifySignature(String message, String signature, PublicKey publicKey) { boolean result = false; byte[] sigbytes = null; try { sigbytes = Base64.decodeBase64(signature.getBytes()); sigChecker = Signature.getInstance("SHA1withRSA"); //check the signature sigChecker.initVerify(publicKey); sigChecker.update(message.getBytes()); result = sigChecker.verify(sigbytes); } catch (NoSuchAlgorithmException e) { // Rare exception: JVM does not support SHA1 with RSA } catch (InvalidKeyException e) { // Rare exception: The private key was incorrectly formatted } catch (SignatureException e) { // Rare exception: Catch-all exception for the signature checker } return result; }
From source file:org.springframework.security.oauth.common.signature.RSA_SHA1SignatureMethod.java
/** * Verify the signature of the given signature base string. The signature is verified by generating a new request signature octet string, and comparing it * to the signature provided by the Consumer, first URL-decoded per Parameter Encoding, then base64-decoded per RFC2045 section 6.8. The signature is * generated using the request parameters as provided by the Consumer, and the Consumer Secret and Token Secret as stored by the Service Provider. * * @param signatureBaseString The signature base string. * @param signature The signature. * @throws InvalidSignatureException/*from ww w.j av a 2s .c o m*/ * If the signature is invalid for the specified base string. * @throws UnsupportedOperationException If there is no public key. */ public void verify(String signatureBaseString, String signature) throws InvalidSignatureException { if (publicKey == null) { throw new UnsupportedOperationException("A public key must be provided to verify signatures."); } try { byte[] signatureBytes = Base64.decodeBase64(signature.getBytes("UTF-8")); Signature verifier = Signature.getInstance("SHA1withRSA"); verifier.initVerify(publicKey); verifier.update(signatureBaseString.getBytes("UTF-8")); if (!verifier.verify(signatureBytes)) { throw new InvalidSignatureException("Invalid signature for signature method " + getName()); } } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } catch (InvalidKeyException e) { throw new IllegalStateException(e); } catch (SignatureException e) { throw new IllegalStateException(e); } }
From source file:test.integ.be.fedict.commons.eid.client.JCATest.java
@Test public void testRecoveryAfterRemoval() throws Exception { Security.addProvider(new BeIDProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null);/* w w w. j a va 2 s .c o m*/ PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null); final Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(authnPrivateKey); final byte[] toBeSigned = "hello world".getBytes(); signature.update(toBeSigned); signature.sign(); JOptionPane.showMessageDialog(null, "Please remove/insert eID card..."); keyStore.load(null); // reload the keystore. authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null); signature.initSign(authnPrivateKey); signature.update(toBeSigned); signature.sign(); }
From source file:cn.usually.common.pay.union.sdk.SecureUtil.java
/** * ??//w w w . j a v a 2s .c om * * @param privateKey * ? * @param data * ??? * @param signMethod * ?? * @return * @throws Exception */ public static byte[] signBySoft(PrivateKey privateKey, byte[] data) throws Exception { byte[] result = null; Signature st = Signature.getInstance(BC_PROV_ALGORITHM_SHA1RSA); st.initSign(privateKey); st.update(data); result = st.sign(); return result; }
From source file:Version2LicenseDecoder.java
private byte[] checkAndGetLicenseText(String licenseContent) { try {/*from w w w.j ava 2s .c o m*/ byte[] e = Base64.decodeBase64(licenseContent.getBytes()); ByteArrayInputStream in = new ByteArrayInputStream(e); DataInputStream dIn = new DataInputStream(in); int textLength = dIn.readInt(); byte[] licenseText = new byte[textLength]; dIn.read(licenseText); byte[] hash = new byte[dIn.available()]; dIn.read(hash); try { Signature e1 = Signature.getInstance("SHA1withDSA"); e1.initVerify(PUBLIC_KEY); e1.update(licenseText); if (!e1.verify(hash)) { throw new LicenseException("Failed to verify the license."); } else { return licenseText; } } catch (InvalidKeyException var9) { throw new LicenseException(var9); } catch (SignatureException var10) { throw new LicenseException(var10); } catch (NoSuchAlgorithmException var11) { throw new LicenseException(var11); } } catch (IOException var12) { throw new LicenseException(var12); } }
From source file:Manifest.java
/** * This method creates a manifest file with the specified name, for the * specified vector of files, using the named message digest algorithm. If * signername is non-null, it adds a digital signature to the manifest, * using the named signature algorithm. This method can throw a bunch of * exceptions.//w w w . ja v a2s .c o m */ public static void create(String manifestfile, String digestAlgorithm, String signername, String signatureAlgorithm, KeyStore keystore, String password, List filelist) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, KeyStoreException, UnrecoverableKeyException, IOException { // For computing a signature, we have to process the files in a fixed, // repeatable order, so sort them alphabetically. Collections.sort(filelist); int numfiles = filelist.size(); Properties manifest = new Properties(), metadata = new Properties(); MessageDigest md = MessageDigest.getInstance(digestAlgorithm); Signature signature = null; byte[] digest; // If a signer name was specified, then prepare to sign the manifest if (signername != null) { // Get a Signature object signature = Signature.getInstance(signatureAlgorithm); // Look up the private key of the signer from the keystore PrivateKey key = (PrivateKey) keystore.getKey(signername, password.toCharArray()); // No prepare to create a signature for the specified signer signature.initSign(key); } // Now, loop through the files, in a well-known alphabetical order System.out.print("Computing message digests"); for (int i = 0; i < numfiles; i++) { String filename = (String) filelist.get(i); // Compute the digest for each, and skip files that don't exist. try { digest = getFileDigest(filename, md); } catch (IOException e) { System.err.println("\nSkipping " + filename + ": " + e); continue; } // If we're computing a signature, use the bytes of the filename // and of the digest as part of the data to sign. if (signature != null) { signature.update(filename.getBytes()); signature.update(digest); } // Store the filename and the encoded digest bytes in the manifest manifest.put(filename, hexEncode(digest)); System.out.print('.'); System.out.flush(); } // If a signer was specified, compute signature for the manifest byte[] signaturebytes = null; if (signature != null) { System.out.print("done\nComputing digital signature..."); System.out.flush(); // Compute the digital signature by encrypting a message digest of // all the bytes passed to the update() method using the private // key of the signer. This is a time consuming operation. signaturebytes = signature.sign(); } // Tell the user what comes next System.out.print("done\nWriting manifest..."); System.out.flush(); // Store some metadata about this manifest, including the name of the // message digest algorithm it uses metadata.put("__META.DIGESTALGORITHM", digestAlgorithm); // If we're signing the manifest, store some more metadata if (signername != null) { // Store the name of the signer metadata.put("__META.SIGNER", signername); // Store the name of the algorithm metadata.put("__META.SIGNATUREALGORITHM", signatureAlgorithm); // And generate the signature, encode it, and store it metadata.put("__META.SIGNATURE", hexEncode(signaturebytes)); } // Now, save the manifest data and the metadata to the manifest file FileOutputStream f = new FileOutputStream(manifestfile); manifest.store(f, "Manifest message digests"); metadata.store(f, "Manifest metadata"); System.out.println("done"); }
From source file:edu.ucsb.eucalyptus.cloud.ws.HttpTransfer.java
public HttpMethodBase constructHttpMethod(String verb, String addr, String eucaOperation, String eucaHeader) { String date = new Date().toString(); String httpVerb = verb;/*w w w. ja v a2s. c o m*/ String addrPath; try { java.net.URI addrUri = new URL(addr).toURI(); addrPath = addrUri.getPath().toString(); String query = addrUri.getQuery(); if (query != null) { addrPath += "?" + query; } } catch (Exception ex) { LOG.error(ex, ex); return null; } String data = httpVerb + "\n" + date + "\n" + addrPath + "\n"; HttpMethodBase method = null; if (httpVerb.equals("PUT")) { method = new PutMethodWithProgress(addr); } else if (httpVerb.equals("DELETE")) { method = new DeleteMethod(addr); } else { method = new GetMethod(addr); } method.setRequestHeader("Authorization", "Euca"); method.setRequestHeader("Date", date); //method.setRequestHeader("Expect", "100-continue"); method.setRequestHeader(StorageProperties.EUCALYPTUS_OPERATION, eucaOperation); if (eucaHeader != null) { method.setRequestHeader(StorageProperties.EUCALYPTUS_HEADER, eucaHeader); } try { PrivateKey ccPrivateKey = SystemCredentials.lookup(Storage.class).getPrivateKey(); Signature sign = Signature.getInstance("SHA1withRSA"); sign.initSign(ccPrivateKey); sign.update(data.getBytes()); byte[] sig = sign.sign(); method.setRequestHeader("EucaSignature", new String(Base64.encode(sig))); } catch (Exception ex) { LOG.error(ex, ex); } return method; }
From source file:com.streamsets.datacollector.publicrestapi.CredentialsDeploymentResource.java
private boolean validateSignature(CredentialsBeanJson credentialsBeanJson) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException { // getProperty so we can test it String publicKey = Preconditions.checkNotNull(System.getProperty(DPM_AGENT_PUBLIC_KEY)); X509EncodedKeySpec kspec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey)); KeyFactory kf = KeyFactory.getInstance("RSA"); PublicKey key = kf.generatePublic(kspec); Signature sig = Signature.getInstance("SHA256withRSA"); sig.initVerify(key);/* w w w . j a v a 2s .c o m*/ sig.update(credentialsBeanJson.getToken().getBytes(Charsets.UTF_8)); LOG.info("Token : {}, Signature {}", credentialsBeanJson.getToken(), credentialsBeanJson.getTokenSignature()); return sig.verify(Base64.getDecoder().decode(credentialsBeanJson.getTokenSignature())); }