List of usage examples for java.security Signature initSign
public final void initSign(PrivateKey privateKey) throws InvalidKeyException
From source file:libcore.tzdata.update_test_app.installupdatetestapp.MainActivity.java
private static String createSignature(File contentFile, String version, String requiredHash) throws Exception { byte[] contentBytes = readBytes(contentFile); Signature signer = Signature.getInstance("SHA512withRSA"); signer.initSign(createKey()); signer.update(contentBytes);// w w w .j a va 2s. co m signer.update(version.trim().getBytes()); signer.update(requiredHash.getBytes()); return new String(Base64.encode(signer.sign(), Base64.DEFAULT)); }
From source file:SignPdf.java
/** * Add a signature and a cryptographic timestamp to a pdf document. See www.ietf.org/rfc/rfc3161.txt. Proves that this * pdf had the current content at the current point in time. * * @param originalPdf/*from w ww .ja v a 2 s .co m*/ * @param targetPdf * @param pk * @param certChain * @param revoked * @param tsaAddress * address of a rfc 3161 compatible timestamp server * @param reason * reason for the signature * @param location * location of signing * @param contact * emailaddress of the person who is signing * @throws IOException * @throws DocumentException * @throws SignatureException */ public static void signAndTimestamp(final InputStream originalPdf, final OutputStream targetPdf, final PrivateKey pk, final X509Certificate[] certChain, final CRL[] revoked, final String tsaAddress, final String reason, final String location, final String contact) throws IOException, DocumentException, SignatureException { // only an estimate, depends on the certificates returned by the TSA final int timestampSize = 4400; Security.addProvider(new BouncyCastleProvider()); final PdfReader reader = new PdfReader(originalPdf); final PdfStamper stamper = PdfStamper.createSignature(reader, targetPdf, '\0'); final PdfSignatureAppearance sap = stamper.getSignatureAppearance(); // comment next lines to have an invisible signature Rectangle cropBox = reader.getCropBox(1); float width = 50; float height = 50; Rectangle rectangle = new Rectangle(cropBox.getRight(width) - 20, cropBox.getTop(height) - 20, cropBox.getRight() - 20, cropBox.getTop() - 20); sap.setVisibleSignature(rectangle, 1, null); //sap.setVisibleSignature(new Rectangle(450, 650, 500, 700), 1, null); sap.setLayer2Text(""); final PdfSigGenericPKCS sig = new PdfSigGenericPKCS.PPKMS("BC"); final HashMap<PdfName, Integer> exclusionSizes = new HashMap<PdfName, Integer>(); // some informational fields sig.setReason(reason); sig.setLocation(location); sig.setContact(contact); sig.setName(PdfPKCS7.getSubjectFields(certChain[0]).getField("CN")); sig.setDate(new PdfDate(Calendar.getInstance())); // signing stuff final byte[] digest = new byte[256]; final byte[] rsaData = new byte[20]; sig.setExternalDigest(digest, rsaData, "RSA"); sig.setSignInfo(pk, certChain, revoked); final PdfString contents = (PdfString) sig.get(PdfName.CONTENTS); // *2 to get hex size, +2 for delimiters PdfLiteral contentsLit = new PdfLiteral((contents.toString().length() + timestampSize) * 2 + 2); exclusionSizes.put(PdfName.CONTENTS, new Integer(contentsLit.getPosLength())); sig.put(PdfName.CONTENTS, contentsLit); // certification; will display dialog or blue bar in Acrobat Reader sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); // process all the information set above sap.setCryptoDictionary(sig); sap.preClose(exclusionSizes); // calculate digest (hash) try { final MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); final byte[] buf = new byte[8192]; int n; final InputStream inp = sap.getRangeStream(); while ((n = inp.read(buf)) != -1) { messageDigest.update(buf, 0, n); } final byte[] hash = messageDigest.digest(); // make signature (SHA1 the hash, prepend algorithm ID, pad, and encrypt with RSA) final Signature sign = Signature.getInstance("SHA1withRSA"); sign.initSign(pk); sign.update(hash); final byte[] signature = sign.sign(); // prepare the location of the signature in the target PDF contentsLit = (PdfLiteral) sig.get(PdfName.CONTENTS); final byte[] outc = new byte[(contentsLit.getPosLength() - 2) / 2]; final PdfPKCS7 pkcs7 = sig.getSigner(); pkcs7.setExternalDigest(signature, hash, "RSA"); final PdfDictionary dic = new PdfDictionary(); byte[] ssig = pkcs7.getEncodedPKCS7(); try { // try to retrieve cryptographic timestamp from configured tsa server ssig = pkcs7.getEncodedPKCS7(null, null, new TSAClientBouncyCastle(tsaAddress), null); } catch (final RuntimeException e) { log.error("Could not retrieve timestamp from server.", e); } System.arraycopy(ssig, 0, outc, 0, ssig.length); // add the timestamped signature dic.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true)); // finish up sap.close(dic); } catch (final InvalidKeyException e) { throw new RuntimeException("Internal implementation error! No such signature type.", e); } catch (final NoSuchAlgorithmException e) { throw new RuntimeException("Internal implementation error! No such algorithm type.", e); } }
From source file:org.javaweb.utils.RSAUtils.java
/** * RSA???// w w w . j av a 2 s.c om * * @param data ? * @param key ? * @return * @throws Exception */ public static String sign(byte[] data, Key key) throws Exception { byte[] keyBytes = key.getEncoded(); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm()); PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec); Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initSign(privateK); signature.update(data); return Base64.encodeBase64String(signature.sign()); }
From source file:org.opensaml.security.crypto.SigningUtil.java
/** * Compute the raw signature value over the supplied input. * //from w w w .j a va 2 s .c o m * It is up to the caller to ensure that the specified algorithm ID is consistent with the type of signing key * supplied. * * @param signingKey the private key with which to compute the signature * @param jcaAlgorithmID the Java JCA algorithm ID to use * @param input the input over which to compute the signature * @return the computed signature value * @throws SecurityException thrown if the signature computation results in an error */ @Nonnull public static byte[] sign(@Nonnull final PrivateKey signingKey, @Nonnull final String jcaAlgorithmID, @Nonnull final byte[] input) throws SecurityException { Constraint.isNotNull(signingKey, "Private key cannot be null"); Constraint.isNotNull(jcaAlgorithmID, "JCA algorithm ID cannot be null"); Constraint.isNotNull(input, "Input data to sign cannot be null"); Logger log = getLogger(); log.debug("Computing signature over input using private key of type {} and JCA algorithm ID {}", signingKey.getAlgorithm(), jcaAlgorithmID); try { Signature signature = Signature.getInstance(jcaAlgorithmID); signature.initSign(signingKey); signature.update(input); byte[] rawSignature = signature.sign(); log.debug("Computed signature: {}", Hex.encodeHex(rawSignature)); return rawSignature; } catch (GeneralSecurityException e) { log.error("Error during signature generation", e); throw new SecurityException("Error during signature generation", e); } }
From source file:pepperim.util.IMCrypt.java
/** * Regular RSA signing (using SHA1-hash) * @param data Data to be signed/*from w w w .j a v a2 s . c om*/ * @param key Key to be used for the signature * @return Base64-encoded RSA signature */ public static String RSA_Sign(String data, PrivateKey key) { try { Signature signer = Signature.getInstance("SHA1withRSA"); signer.initSign(key); signer.update(data.getBytes()); byte[] signature = signer.sign(); return B64_Enc(signature); } catch (GeneralSecurityException e) { Main.log(e.getMessage()); return ""; } }
From source file:net.sf.keystore_explorer.crypto.signing.MidletSigner.java
private static byte[] signJarDigest(File jarFile, RSAPrivateKey privateKey) throws CryptoException { // Create a SHA-1 signature for the supplied JAR file FileInputStream fis = null;/*from ww w . j a v a 2 s . c o m*/ try { Signature signature = Signature.getInstance(SignatureType.SHA1_RSA.jce()); signature.initSign(privateKey); fis = new FileInputStream(jarFile); byte buffer[] = new byte[1024]; int read = 0; while ((read = fis.read(buffer)) != -1) { signature.update(buffer, 0, read); } return signature.sign(); } catch (IOException ex) { throw new CryptoException(res.getString("JarDigestSignatureFailed.exception.message"), ex); } catch (GeneralSecurityException ex) { throw new CryptoException(res.getString("JarDigestSignatureFailed.exception.message"), ex); } finally { IOUtils.closeQuietly(fis); } }
From source file:com.sammyun.util.RSAUtils.java
/** * RSA??/*w w w.j a v a2s . c o m*/ * * @param content ??? * @param privateKey ? * @param input_charset ?? * @return ?? */ public static String sign(String content, String privateKey, String input_charset) { try { PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64Util.decode(privateKey)); KeyFactory keyf = KeyFactory.getInstance("RSA"); PrivateKey priKey = keyf.generatePrivate(priPKCS8); java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS); signature.initSign(priKey); signature.update(content.getBytes(input_charset)); byte[] signed = signature.sign(); return Base64Util.encode(signed); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.transport.CommunicationUtils.java
/** * Signed a given message using the PrivateKey that's passes in. * * @param message the message to be signed. Ideally some encrypted payload. * @param signatureKey the PrivateKey with which the message is to be signed. * @return the Base64Encoded String of the signed payload. * @throws TransportHandlerException if some error occurs with the signing process which may be related to the * signature algorithm used or the key used for signing. *//*from ww w. ja v a 2 s . com*/ public static String signMessage(String message, PrivateKey signatureKey) throws TransportHandlerException { Signature signature; String signedEncodedString; try { signature = Signature.getInstance(SHA_512); signature.initSign(signatureKey); signature.update(Base64.decodeBase64(message)); byte[] signatureBytes = signature.sign(); signedEncodedString = Base64.encodeBase64String(signatureBytes); } catch (NoSuchAlgorithmException e) { String errorMsg = "Algorithm not found exception occurred for Signature instance of [" + SHA_512 + "]"; log.error(errorMsg); throw new TransportHandlerException(errorMsg, e); } catch (SignatureException e) { String errorMsg = "Signature exception occurred for Signature instance of [" + SHA_512 + "]"; log.error(errorMsg); throw new TransportHandlerException(errorMsg, e); } catch (InvalidKeyException e) { String errorMsg = "InvalidKey exception occurred for signatureKey \n[\n" + signatureKey + "\n]\n"; log.error(errorMsg); throw new TransportHandlerException(errorMsg, e); } return signedEncodedString; }
From source file:ai.susi.tools.JsonSignature.java
/** * Create and add a signature to a JSONObject * @param obj the JSONObject// www .java2s. c o m * @param key the private key to use * @throws InvalidKeyException if the key is not valid (for example not RSA) * @throws SignatureException if something with the JSONObject is bogus */ public static void addSignature(JSONObject obj, PrivateKey key) throws InvalidKeyException, SignatureException { removeSignature(obj); Signature signature; try { signature = Signature.getInstance("SHA256withRSA"); } catch (NoSuchAlgorithmException e) { return; //does not happen } signature.initSign(key); signature.update(obj.toString().getBytes(StandardCharsets.UTF_8)); byte[] sigBytes = signature.sign(); obj.put(signatureString, new String(Base64.getEncoder().encode(sigBytes))); }
From source file:ai.susi.tools.JsonSignature.java
public static void addSignature(Map<String, byte[]> obj, PrivateKey key) throws InvalidKeyException, SignatureException { removeSignature(obj);//from ww w . j av a 2 s. c o m Signature signature; try { signature = Signature.getInstance("SHA256withRSA"); } catch (NoSuchAlgorithmException e) { return; //does not happen } signature.initSign(key); signature.update(obj.toString().getBytes(StandardCharsets.UTF_8)); byte[] sigBytes = signature.sign(); obj.put(signatureString, Base64.getEncoder().encode(sigBytes)); }