Example usage for java.security Signature update

List of usage examples for java.security Signature update

Introduction

In this page you can find the example usage for java.security Signature update.

Prototype

public final void update(ByteBuffer data) throws SignatureException 

Source Link

Document

Updates the data to be signed or verified using the specified ByteBuffer.

Usage

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./* w w w.  j a  va2  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:com.znsx.util.licence.LicenceUtil.java

/**
 * ?????//  w  ww .  java 2 s .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");
}

From source file:com.sixsq.slipstream.cookie.CryptoUtils.java

/**
 * Determine if the given signature matches the given data.
 *
 * @param signed//ww  w.  jav a  2  s  .c  o  m
 *            String representation of signature
 * @param data
 *            information to check
 *
 * @return true if the signature matches the given data, false otherwise
 */
public static boolean verify(String signed, String data) {

    boolean valid = false;

    try {

        Signature signature = Signature.getInstance(signatureAlgorithm);
        signature.initVerify(publicKey);

        signature.update(data.getBytes());

        byte[] signBytes = (new BigInteger(signed, radix)).toByteArray();
        valid = signature.verify(signBytes);

    } catch (NoSuchAlgorithmException e) {
        log.warning("Algorithm not recognized: " + signatureAlgorithm + " with details: " + e.getMessage());
    } catch (InvalidKeyException e) {
        log.warning(e.toString());
    } catch (SignatureException e) {
        log.warning(e.toString());
    }

    return valid;
}

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());/*w  w w  .java  2 s .c  o m*/
    signer.update(contentBytes);
    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/*ww  w.  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
    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:nl.arietimmerman.u2f.server.CryptoHelper.java

/**
 * Verifies the signature, as set on the registration response and authentication response messages
 * @param publicKey The public key//from  w w  w . ja  v a 2  s . c om
 * @param bytesSigned The bytes to be signed
 * @param signature See "FIDO U2F Raw Message Formats" for requirements regarding signatures
 * @return
 */
public static boolean verifySignature(PublicKey publicKey, byte[] bytesSigned, byte[] signature) {
    Log.info("start verifySignature");
    try {
        Signature signatureObject = Signature.getInstance("SHA256withECDSA", new BouncyCastleProvider());
        Log.info("Initialized SHA256withECDSA");
        signatureObject.initVerify(publicKey);
        Log.info("executed initVerify");
        signatureObject.update(bytesSigned);
        Log.info("start verifying");
        return signatureObject.verify(signature);
    } catch (InvalidKeyException | SignatureException | NoSuchAlgorithmException e) {
        e.printStackTrace();
        return false;
    }
}

From source file:com.shenit.commons.codec.RsaUtils.java

/**
 * RSA??/*from  w  w w . j  a v a 2s . c o  m*/
 * 
 * @param content
 *            ???
 * @param sign
 *            ??
 * @param publicKey
 *            ?
 * @param inputCharset
 *            ??
 * @return 
 */
public static boolean verify(String content, String sign, String publicKey, String algorithm,
        String inputCharset) {
    try {
        KeyFactory keyFactory = KeyFactory.getInstance(CODEC_RSA);
        byte[] encodedKey = Base64.decodeBase64(publicKey);
        PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));

        java.security.Signature signature = java.security.Signature.getInstance(algorithm);

        signature.initVerify(pubKey);
        signature.update(content.getBytes(inputCharset));

        boolean bverify = signature.verify(Base64.decodeBase64(sign));
        return bverify;

    } catch (Exception e) {
        if (LOG.isWarnEnabled())
            LOG.warn("[verify] verify with exception", e);
    }

    return false;
}

From source file:org.javaweb.utils.RSAUtils.java

/**
 * RSA???//from   w ww  .  j a  v a2s . c o  m
 *
 * @param data ?
 * @param key  
 * @param sign ??Base64
 * @return
 * @throws Exception
 */
public static boolean verify(byte[] data, Key key, String sign) throws Exception {
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(key.getEncoded());
    KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm());
    PublicKey publicK = keyFactory.generatePublic(keySpec);
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initVerify(publicK);
    signature.update(data);

    return signature.verify(Base64.decodeBase64(sign));
}

From source file:org.javaweb.utils.RSAUtils.java

/**
 * RSA???//from ww  w  . j av  a2  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

/**
 * Verify the signature value computed over the supplied input against the supplied signature value.
 * //from www . java 2 s.  c  o m
 * It is up to the caller to ensure that the specified algorithm ID is consistent with the type of verification key
 * supplied.
 * 
 * @param verificationKey the key with which to compute and verify the signature
 * @param jcaAlgorithmID the Java JCA algorithm ID to use
 * @param signature the computed signature value received from the signer
 * @param input the input over which the signature is computed and verified
 * @return true if the signature value computed over the input using the supplied key and algorithm ID is identical
 *         to the supplied signature value
 * @throws SecurityException thrown if the signature computation or verification process results in an error
 */
public static boolean verify(@Nonnull final PublicKey verificationKey, @Nonnull final String jcaAlgorithmID,
        @Nonnull final byte[] signature, @Nonnull final byte[] input) throws SecurityException {
    Constraint.isNotNull(verificationKey, "Public key cannot be null");
    Constraint.isNotNull(jcaAlgorithmID, "JCA algorithm ID cannot be null");
    Constraint.isNotNull(signature, "Signature data to verify cannot be null");
    Constraint.isNotNull(input, "Input data to verify cannot be null");

    Logger log = getLogger();
    log.debug("Verifying signature over input using public key of type {} and JCA algorithm ID {}",
            verificationKey.getAlgorithm(), jcaAlgorithmID);

    try {
        Signature sig = Signature.getInstance(jcaAlgorithmID);
        sig.initVerify(verificationKey);
        sig.update(input);
        return sig.verify(signature);
    } catch (GeneralSecurityException e) {
        log.error("Error during signature verification", e);
        throw new SecurityException("Error during signature verification", e);
    }
}