List of usage examples for java.security Signature update
public final void update(ByteBuffer data) throws SignatureException
From source file:com.eucalyptus.auth.euare.EuareServerCertificateUtil.java
public static String generateSignature(final PrivateKey key, final String msg) { try {// 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:org.carewebframework.api.security.CipherUtil.java
/** * Verifies a digitally signed payload./* ww w . j ava 2s. co m*/ * * @param key Public key to verify digital signature. * @param base64Signature Digital signature of content. * @param content The content that was signed. * @param timestamp Optional timestamp for time-sensitive payloads. * @param duration Optional validity duration in minutes for time-sensitive payloads. * @return True if signature is valid. * @throws Exception Unspecified exception. */ public static boolean verify(PublicKey key, String base64Signature, String content, String timestamp, int duration) throws Exception { if (key == null || base64Signature == null || content == null || timestamp == null) { return false; } try { if (timestamp != null && duration > 0) { validateTime(timestamp, duration); } Signature signature = Signature.getInstance(SIGN_ALGORITHM); signature.initVerify(key); signature.update(content.getBytes()); byte[] signatureBytes = Base64.decodeBase64(base64Signature); return signature.verify(signatureBytes); } catch (Exception e) { log.error("Authentication Exception:verifySignature", e); throw e; } }
From source file:com.sharky.Security.java
public static boolean verify(PublicKey publicKey, String signedData, String signature) { Signature sig; try {//from w w w . jav a 2 s .com sig = Signature.getInstance(SIGNATURE_ALGORITHM); sig.initVerify(publicKey); sig.update(signedData.getBytes()); if (!sig.verify(Base64.decode(signature))) { return false; } return true; } catch (NoSuchAlgorithmException e) { //code here } catch (InvalidKeyException e) { // code here } catch (SignatureException e) { // code here } catch (Base64DecoderException e) { // code here } return false; }
From source file:be.fedict.eidviewer.lib.X509Utilities.java
public static boolean isValidSignature(X509Certificate certificate, byte[] data, byte[] data2, byte[] signature) { try {/*from w w w. j av a 2 s .co m*/ Signature verifier = Signature.getInstance("SHA1withRSA"); verifier.initVerify(certificate); verifier.update(data); if (data2 != null) verifier.update(data2); return verifier.verify(signature); } catch (Exception e) { return false; } }
From source file:com.shenit.commons.codec.RsaUtils.java
/** * RSA??//from w w w.java2 s. com * * @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:com.alliander.osgp.oslp.OslpUtils.java
/** * Create a signature of specified message. * * @param message//from www .j ava 2s .c om * 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.znsx.util.licence.LicenceUtil.java
/** * ???/*from w w w . j av a2s .c om*/ * * @param data * ?? * @param publicKey * 2 * @param signature * base64???? * @return * @throws Exception * @author huangbuji * <p /> * Create at 2014-2-12 ?5:37:18 */ public static boolean verifyBinKey(String data, byte[] publicKey, String signature) throws Exception { Base64 base64 = new Base64(); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey); PublicKey pub = KeyFactory.getInstance("DSA").generatePublic(keySpec); // ? Signature sign = Signature.getInstance("DSA"); sign.initVerify(pub); sign.update(data.getBytes("utf8")); // return sign.verify(decoder.decodeBuffer(signature)); return sign.verify(base64.decode(signature.getBytes("utf8"))); }
From source file:com.alliander.osgp.oslp.OslpUtils.java
/** * Validate the signature against the message. * * @param message//from w w w . ja va 2 s . co m * message to validate * @param securityKey * signature to validate * @param publicKey * public key to use for decryption of signature * @param signature * signature algorithm to use * @param provider * provider which supplies algorithm * @return true when signature is correct, false when it's not * @throws GeneralSecurityException * when configuration is incorrect. */ public static boolean validateSignature(final byte[] message, final byte[] securityKey, final PublicKey publicKey, 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 validateEncryptedHash(message, securityKey, publicKey); } final Signature signatureBuilder = Signature.getInstance(signature, provider); signatureBuilder.initVerify(publicKey); signatureBuilder.update(message); return signatureBuilder.verify(securityKey); }
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 ww. j ava 2s . 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
/** * ???/*from ww w . ja v a 2 s . c o m*/ * * @param data * ?? * @param publicKeyString * ??base64? * @param signature * base64???? * @return * @throws Exception */ public static boolean verify(String data, String publicKeyString, String signature) throws Exception { // ??? // BASE64Decoder decoder = new BASE64Decoder(); // byte[] bytes = decoder.decodeBuffer(publicKeyString); Base64 base64 = new Base64(); byte[] bytes = base64.decode(publicKeyString.getBytes("utf8")); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes); PublicKey publicKey = KeyFactory.getInstance("DSA").generatePublic(keySpec); // ? Signature sign = Signature.getInstance("DSA"); sign.initVerify(publicKey); sign.update(data.getBytes("utf8")); // return sign.verify(decoder.decodeBuffer(signature)); return sign.verify(base64.decode(signature.getBytes("utf8"))); }