List of usage examples for java.security Signature initSign
public final void initSign(PrivateKey privateKey) throws InvalidKeyException
From source file:org.wso2.carbon.connector.CreateJWT.java
/** * The method to sign the byte array of data using the private key. * * @param data the byte array of data to generate the signature * @param privateKey the private key to sign the byte array * @return the signed signature// w ww.ja v a 2 s .co m * @throws InvalidKeyException * @throws SignatureException * @throws NoSuchAlgorithmException */ public static byte[] signData(byte[] data, PrivateKey privateKey) throws InvalidKeyException, SignatureException, NoSuchAlgorithmException { Signature signature = Signature.getInstance(JWTConstant.SIGNATURE); signature.initSign(privateKey); signature.update(data); return signature.sign(); }
From source file:org.carewebframework.api.security.CipherUtil.java
/** * Returns the digital signature for the specified content. * /* w w w.j a v a 2s . c om*/ * @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:com.eucalyptus.auth.euare.EuareServerCertificateUtil.java
public static String generateSignature(final PrivateKey key, final String msg) { try {/*from www .j ava 2 s . c o m*/ final Signature sig = Signature.getInstance("SHA256withRSA"); sig.initSign(key); sig.update(msg.getBytes("UTF-8")); final byte[] bsig = sig.sign(); return B64.standard.encString(bsig); } catch (final Exception ex) { throw Exceptions.toUndeclared(ex); } }
From source file:com.threerings.getdown.tools.Digester.java
/** * Creates a digest file in the specified application directory. *///from w w w .jav a 2 s . com public static void signDigest(File appdir, File storePath, String storePass, String storeAlias) throws IOException, GeneralSecurityException { File inputFile = new File(appdir, Digest.DIGEST_FILE); File signatureFile = new File(appdir, Digest.DIGEST_FILE + Application.SIGNATURE_SUFFIX); FileInputStream storeInput = null, dataInput = null; FileOutputStream signatureOutput = null; try { // initialize the keystore KeyStore store = KeyStore.getInstance("JKS"); storeInput = new FileInputStream(storePath); store.load(storeInput, storePass.toCharArray()); PrivateKey key = (PrivateKey) store.getKey(storeAlias, storePass.toCharArray()); // sign the digest file Signature sig = Signature.getInstance("SHA1withRSA"); dataInput = new FileInputStream(inputFile); byte[] buffer = new byte[8192]; int length; sig.initSign(key); while ((length = dataInput.read(buffer)) != -1) { sig.update(buffer, 0, length); } // Write out the signature signatureOutput = new FileOutputStream(signatureFile); String signed = new String(Base64.encodeBase64(sig.sign())); signatureOutput.write(signed.getBytes("utf8")); } finally { StreamUtil.close(signatureOutput); StreamUtil.close(dataInput); StreamUtil.close(storeInput); } }
From source file:com.alliander.osgp.oslp.OslpUtils.java
/** * Create a signature of specified message. * * @param message//from w w w .java2 s .com * message bytes to sign * @param privateKey * private key to use for signing * @param signature * signature algorithm to use * @param provider * provider which supplies the signature algorithm * @return signature * @throws GeneralSecurityException * when configuration is incorrect. */ public static byte[] createSignature(final byte[] message, final PrivateKey privateKey, final String signature, final String provider) throws GeneralSecurityException { // Use fallback to plain SHA512 hash, which is encrypted with RSA // instead of real RSA signature if (signature.equalsIgnoreCase(FALLBACK_SIGNATURE)) { return createEncryptedHash(message, privateKey); } // Use real signature final Signature signatureBuilder = Signature.getInstance(signature, provider); signatureBuilder.initSign(privateKey); signatureBuilder.update(message); return signatureBuilder.sign(); }
From source file:com.shenit.commons.codec.RsaUtils.java
/** * RSA??/*from ww w .java 2s. c o m*/ * * @param content * ??? * @param privateKey * ? * @param input_charset * ?? * @return ?? */ public static String sign(String content, String privateKey, String algorithm, String input_charset) { try { PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey)); KeyFactory keyf = KeyFactory.getInstance(CODEC_RSA); PrivateKey priKey = keyf.generatePrivate(priPKCS8); Signature signature = Signature.getInstance(algorithm); signature.initSign(priKey); signature.update(content.getBytes(input_charset)); byte[] signed = signature.sign(); return Base64Utils.base64EncodeHex(signed); } catch (Exception e) { if (LOG.isWarnEnabled()) LOG.warn("[sign] could not sign with exception", e); } return null; }
From source file:pxb.android.tinysign.TinySign.java
private static Signature instanceSignature() throws Exception { byte[] data = dBase64(Constants.privateKey); KeyFactory rSAKeyFactory = KeyFactory.getInstance("RSA"); PrivateKey privateKey = rSAKeyFactory.generatePrivate(new PKCS8EncodedKeySpec(data)); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(privateKey); return signature; }
From source file:com.sixsq.slipstream.cookie.CryptoUtils.java
/** * Sign the given data and return a String representation of the signature. * The argument may not be null.//from w ww .j a v a 2 s . c o m * * @param data * information to sign * * @return String representation of the signature. */ public static String sign(String data) { try { Signature signature = Signature.getInstance(signatureAlgorithm); signature.initSign(privateKey); signature.update(data.getBytes()); BigInteger biSignature = new BigInteger(signature.sign()); return biSignature.toString(radix); } catch (NoSuchAlgorithmException nsae) { return null; } catch (InvalidKeyException ike) { return null; } catch (SignatureException se) { return null; } }
From source file:de.thorstenberger.examServer.pdf.signature.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 w w .j a v a 2 s . c o 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 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:com.znsx.util.licence.LicenceUtil.java
/** * ?????/* ww w . ja v a 2s .c o m*/ * * @param data * ?? * @param privateKey * ???base64? * @return base64???? * @throws Exception */ public static String sign(String data, String privateKeyString) throws Exception { Base64 base64 = new Base64(); // ???? // BASE64Decoder decoder = new BASE64Decoder(); // byte[] bytes = decoder.decodeBuffer(privateKeyString); byte[] bytes = base64.decode(privateKeyString.getBytes("utf8")); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes); PrivateKey privateKey = KeyFactory.getInstance("DSA").generatePrivate(keySpec); // ??? Signature signature = Signature.getInstance("DSA"); signature.initSign(privateKey); signature.update(data.getBytes("utf8")); // return new BASE64Encoder().encode(signature.sign()); return new String(base64.encode(signature.sign()), "utf8"); }