Example usage for java.security Signature initVerify

List of usage examples for java.security Signature initVerify

Introduction

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

Prototype

public final void initVerify(Certificate certificate) throws InvalidKeyException 

Source Link

Document

Initializes this object for verification, using the public key from the given certificate.

Usage

From source file:org.opensaml.security.crypto.SigningUtil.java

/**
 * Verify the signature value computed over the supplied input against the supplied signature value.
 * //from   w  w w  .jav a  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);
    }
}

From source file:com.eucalyptus.auth.euare.EuareServerCertificateUtil.java

public static boolean verifySignature(final String certPem, final String msg, final String sigB64) {
    try {/* www.  java 2 s. com*/
        final Signature sig = Signature.getInstance("SHA256withRSA");
        final X509Certificate cert = PEMFiles.getCert(B64.standard.dec(certPem));
        sig.initVerify(cert);
        sig.update(msg.getBytes("UTF-8"));
        return sig.verify(B64.standard.dec(sigB64.getBytes()));
    } catch (final Exception ex) {
        throw Exceptions.toUndeclared(ex);
    }
}

From source file:pepperim.util.IMCrypt.java

/**
 * @param data Data to be verified/*from w  w w  .j  ava  2s.  c  o  m*/
 * @param b64sig Base64-encoded RSA signature
 * @param key Public key of the signature source
 * @return true on success, false if the verification fails
 */
public static boolean RSA_Verify(String data, String b64sig, PublicKey key) {
    try {
        Signature verifier = Signature.getInstance("SHA1withRSA");
        verifier.initVerify(key);
        verifier.update(data.getBytes());
        return verifier.verify(B64_Dec(b64sig));
    } catch (GeneralSecurityException e) {
        Main.log(e.getMessage());
        return false;
    }
}

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.transport.CommunicationUtils.java

/**
 * Verifies some signed-data against the a Public-Key to ensure that it was produced by the holder of the
 * corresponding Private Key.//from ww  w. j a  v a  2  s. c  o m
 *
 * @param data            the actual payoad which was signed by some Private Key.
 * @param signedData      the signed data produced by signing the payload using a Private Key.
 * @param verificationKey the corresponding Public Key which is an exact pair of the Private-Key with we expect
 *                        the data to be signed by.
 * @return true if the signed data verifies to be signed by the corresponding Private Key.
 * @throws TransportHandlerException if some error occurs with the verification process which may be related to
 *                                     the signature algorithm used or the key used for signing.
 */
public static boolean verifySignature(String data, String signedData, PublicKey verificationKey)
        throws TransportHandlerException {

    Signature signature;
    boolean verified;

    try {
        signature = Signature.getInstance(SHA_512);
        signature.initVerify(verificationKey);
        signature.update(Base64.decodeBase64(data));

        verified = signature.verify(Base64.decodeBase64(signedData));

    } 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" + verificationKey + "\n]\n";
        log.error(errorMsg);
        throw new TransportHandlerException(errorMsg, e);
    }

    return verified;
}

From source file:oscar.oscarLab.ca.all.pageUtil.LabUploadAction.java

public static boolean validateSignature(PublicKey key, String sigString, File input) {
    Base64 base64 = new Base64(0);
    byte[] buf = new byte[1024];

    try {/* www .j  a  v  a  2s  . c  om*/

        InputStream msgIs = new FileInputStream(input);
        Signature sig = Signature.getInstance("MD5WithRSA");
        sig.initVerify(key);

        // Read in the message bytes and update the signature
        int numRead = 0;
        while ((numRead = msgIs.read(buf)) >= 0) {
            sig.update(buf, 0, numRead);
        }
        msgIs.close();

        return (sig.verify(base64.decode(sigString.getBytes(MiscUtils.ENCODING))));

    } catch (Exception e) {
        logger.debug("Could not validate signature: " + e);
        MiscUtils.getLogger().error("Error", e);
        return (false);
    }
}

From source file:Main.java

/**
 * Verify a signature of a stream.//from   w w w.j  a va2s.c o  m
 *
 * @param cert      The certificate containing the public key which will be used
 *                  to verify the signature.
 * @param signature The signature to verify.
 * @param stream    The stream to verify.
 * @return boolean true if the signature was valid otherwise false.
 */
public static boolean verifySignature(String algorithm, Certificate cert, byte[] signature, InputStream stream)
        throws InvalidKeyException, SignatureException, IOException {
    Signature sign;

    try {
        sign = Signature.getInstance(algorithm);
    } catch (NoSuchAlgorithmException badsigner) {
        throw new IOException("Could not initialize signer with algorithm " + algorithm);
    }

    sign.initVerify(cert);

    byte[] buffer = new byte[1024];

    while (true) {
        int read = stream.read(buffer);

        if (read < 0) {
            break;
        }

        sign.update(buffer, 0, read);
    }

    return sign.verify(signature);
}

From source file:com.sammyun.util.RSAUtils.java

/**
 * RSA??/*from w w  w .  j a v a 2  s  .  c  o  m*/
 * 
 * @param content ???
 * @return
 */
public static String encryptContent(String content, String ali_public_key) {
    try {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] encodedKey = Base64Util.decode(ali_public_key);
        PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
        java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
        signature.initVerify(pubKey);
        signature.update(content.getBytes("utf-8"));
        byte[] signed = signature.sign();
        return Base64Util.encode(signed);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        return "";
    }
}

From source file:org.wso2.carbon.device.mgt.iot.transport.CommunicationUtils.java

/**
 * Verifies some signed-data against the a Public-Key to ensure that it was produced by the holder of the
 * corresponding Private Key./*from   ww  w. ja  v a 2 s  .c  o m*/
 *
 * @param data            the actual payoad which was signed by some Private Key.
 * @param signedData      the signed data produced by signing the payload using a Private Key.
 * @param verificationKey the corresponding Public Key which is an exact pair of the Private-Key with we expect
 *                        the data to be signed by.
 * @return true if the signed data verifies to be signed by the corresponding Private Key.
 * @throws TransportHandlerException if some error occurs with the verification process which may be related to
 *                                   the signature algorithm used or the key used for signing.
 */
public static boolean verifySignature(String data, String signedData, PublicKey verificationKey)
        throws TransportHandlerException {

    Signature signature;
    boolean verified;

    try {
        signature = Signature.getInstance(SIGNATURE_ALG);
        signature.initVerify(verificationKey);
        signature.update(Base64.decodeBase64(data));

        verified = signature.verify(Base64.decodeBase64(signedData));

    } catch (NoSuchAlgorithmException e) {
        String errorMsg = "Algorithm not found exception occurred for Signature instance of [" + SIGNATURE_ALG
                + "]";
        log.error(errorMsg);
        throw new TransportHandlerException(errorMsg, e);
    } catch (SignatureException e) {
        String errorMsg = "Signature exception occurred for Signature instance of [" + SIGNATURE_ALG + "]";
        log.error(errorMsg);
        throw new TransportHandlerException(errorMsg, e);
    } catch (InvalidKeyException e) {
        String errorMsg = "InvalidKey exception occurred for signatureKey \n[\n" + verificationKey + "\n]\n";
        log.error(errorMsg);
        throw new TransportHandlerException(errorMsg, e);
    }
    return verified;
}

From source file:ch.hsr.challp.and4.billing.Security.java

/**
 * Verifies that the signature from the server matches the computed
 * signature on the data.  Returns true if the data is correctly signed.
 *
 * @param publicKey public key associated with the developer account
 * @param signedData signed data from server
 * @param signature server signature//from   w  w  w  . j av  a2 s. c  o  m
 * @return true if the data and signature match
 */
public static boolean verify(PublicKey publicKey, String signedData, String signature) {
    if (Consts.DEBUG) {
        Log.i(TAG, "signature: " + signature);
    }
    Signature sig;
    try {
        sig = Signature.getInstance(SIGNATURE_ALGORITHM);
        sig.initVerify(publicKey);
        sig.update(signedData.getBytes());
        if (!sig.verify(Base64.decode(signature))) {
            Log.e(TAG, "Signature verification failed.");
            return false;
        }
        return true;
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "NoSuchAlgorithmException.");
    } catch (InvalidKeyException e) {
        Log.e(TAG, "Invalid key specification.");
    } catch (SignatureException e) {
        Log.e(TAG, "Signature exception.");
    } catch (Base64DecoderException e) {
        Log.e(TAG, "Base64 decoding failed.");
    }
    return false;
}

From source file:com.sammyun.util.RSAUtils.java

/**
 * RSA??//from   ww  w  .  j  a  va  2 s. c  o m
 * 
 * @param content ???
 * @param sign ??
 * @param ali_public_key ?
 * @param input_charset ??
 * @return 
 */
public static boolean verify(String content, String sign, String ali_public_key, String input_charset) {
    try {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] encodedKey = Base64Util.decode(ali_public_key);
        PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));

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

        signature.initVerify(pubKey);
        signature.update(content.getBytes(input_charset));
        boolean bverify = signature.verify(Base64Util.decode(sign));
        return bverify;

    } catch (Exception e) {
        e.printStackTrace();
    }

    return false;
}