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.wso2.carbon.device.mgt.iot.agent.firealarm.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.// w ww . j a v a2  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 AgentCoreOperationException 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 AgentCoreOperationException {

    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 AgentCoreOperationException(errorMsg, e);
    } catch (SignatureException e) {
        String errorMsg = "Signature exception occurred for Signature instance of [" + SIGNATURE_ALG + "]";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    } catch (InvalidKeyException e) {
        String errorMsg = "InvalidKey exception occurred for signatureKey \n[\n" + verificationKey + "\n]\n";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    }

    return verified;
}

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.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 w ww . java2  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:com.soomla.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//  www  .jav a 2  s.  c  om
 * @return true if the data and signature match
 */
public static boolean verify(PublicKey publicKey, String signedData, String signature) {
    StoreUtils.LogDebug(TAG, "signature: " + signature);
    Signature sig;
    try {
        sig = Signature.getInstance(SIGNATURE_ALGORITHM);
        sig.initVerify(publicKey);
        sig.update(signedData.getBytes());
        if (!sig.verify(Base64.decode(signature))) {
            StoreUtils.LogError(TAG, "Signature verification failed.");
            return false;
        }
        return true;
    } catch (NoSuchAlgorithmException e) {
        StoreUtils.LogError(TAG, "NoSuchAlgorithmException.");
    } catch (InvalidKeyException e) {
        StoreUtils.LogError(TAG, "Invalid key specification.");
    } catch (SignatureException e) {
        StoreUtils.LogError(TAG, "Signature exception.");
    } catch (Base64DecoderException e) {
        StoreUtils.LogError(TAG, "Base64 decoding failed.");
    }
    return false;
}

From source file:com.github.aynu.yukar.framework.util.SecurityHelper.java

/**
 * ???/*from  w  w w. j  a  v a  2s.  co m*/
 * <dl>
 * <dt>?
 * <dd>NONEwithECDSA??????????????
 * </dl>
 * @param publicKey ?
 * @param message 
 * @param signature ??
 * @return ?
 */
public static boolean verify(final PublicKey publicKey, final byte[] signature, final byte[] message) {
    try {
        final Signature sign = Signature.getInstance("NONEwithECDSA");
        sign.initVerify(publicKey);
        sign.update(message);
        return sign.verify(signature);
    } catch (final NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
        throw new StandardRuntimeException(e);
    }
}

From source file:com.parking.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 a v a 2s  .  c  o m
 * @return true if the data and signature match
 */
public static boolean verify(PublicKey publicKey, String signedData, String signature) {
    if (BillingConstants.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:org.cprados.wificellmanager.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// ww w  .ja va  2  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))) {
        if (!sig.verify(Base64.decode(signature, Base64.DEFAULT))) {
            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:dk.itst.oiosaml.sp.service.util.Utils.java

/**
 * Check if a SAML HTTP Redirect has been signed by the expected certificate
 * /*from   w ww .  j av a 2  s. c  om*/
 * @param data
 *            The query parameters in the HTTP Redirect, which has been
 *            signed
 * @param key
 *            The public key of the certificate from the expected sender
 * @param sig
 *            The signature generated by the sender after it has been base64
 *            decoded
 * @return true, if the signature is valid, otherwise false
 */
public static boolean verifySignature(byte[] data, PublicKey key, byte[] sig) {

    if (log.isDebugEnabled())
        log.debug("data...:" + new String(data));
    if (log.isDebugEnabled())
        log.debug("sig....:" + new String(sig));
    if (log.isDebugEnabled())
        log.debug("key....:" + key.toString());

    try {
        Signature signer = Signature.getInstance(OIOSAMLConstants.SHA1_WITH_RSA);
        signer.initVerify(key);
        signer.update(data);
        return signer.verify(sig);
    } catch (InvalidKeyException e) {
        throw new WrappedException(Layer.CLIENT, e);
    } catch (NoSuchAlgorithmException e) {
        throw new WrappedException(Layer.CLIENT, e);
    } catch (SignatureException e) {
        throw new WrappedException(Layer.CLIENT, e);
    }
}

From source file:im.whistle.crypt.Crypt.java

/**
 * Decrypts a message./*w ww  .  java 2 s  .c  om*/
 * @param args Arguments: enc, privateKey, sig, publicKey
 * @param callback Callback
 */
public static void decrypt(JSONArray args, AsyncCallback<JSONArray> callback) {
    try {
        // Get the arguments
        String enc = args.getString(0);
        String key = args.getString(1);
        String sig = null;
        String pub = null;
        if (args.length() == 4) {
            sig = args.getString(2);
            pub = args.getString(3);
        }
        Boolean ver = null;

        // Convert everything into byte arrays
        byte[] encRaw = Base64.decode(enc, Base64.DEFAULT);
        byte[] keyRaw = Base64.decode(stripKey(key), Base64.DEFAULT);

        // Verify signature
        if (sig != null && pub != null) {
            try {
                byte[] sigRaw = Base64.decode(sig, Base64.DEFAULT);
                byte[] pubRaw = Base64.decode(stripKey(pub), Base64.DEFAULT);
                X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubRaw);
                KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
                Signature s = Signature.getInstance("SHA1withRSA", "BC");
                s.initVerify(kf.generatePublic(publicKeySpec));
                s.update(encRaw);
                ver = s.verify(sigRaw);
            } catch (Exception ex) {
                Log.i("whistle", "Verification failed: " + ex.getMessage());
                ver = false;
            }
        }

        // Split enc into encrypted aes data and remaining enc
        byte[] encSplit = encRaw;
        byte[] aesRaw = new byte[RSA_BYTES];
        System.arraycopy(encSplit, 0, aesRaw, 0, aesRaw.length);
        encRaw = new byte[encSplit.length - RSA_BYTES];
        System.arraycopy(encSplit, RSA_BYTES, encRaw, 0, encRaw.length);

        // Decrypt encrypted aes data using RSAES-OAEP
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(keyRaw);
        KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
        Cipher c = Cipher.getInstance("RSA/None/OAEPWithSHA-1AndMGF1Padding");
        c.init(Cipher.DECRYPT_MODE, kf.generatePrivate(privateKeySpec));
        aesRaw = c.doFinal(aesRaw);

        // Decrypted enc using AES-CBC
        byte[] aesKey = new byte[AES_BYTES];
        byte[] aesIv = new byte[aesRaw.length - aesKey.length];
        System.arraycopy(aesRaw, 0, aesKey, 0, aesKey.length);
        System.arraycopy(aesRaw, aesKey.length, aesIv, 0, aesIv.length);
        c = Cipher.getInstance("AES/CBC/PKCS7Padding");
        c.init(Cipher.DECRYPT_MODE, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(aesIv));
        byte[] dec = c.doFinal(encRaw);

        JSONArray res = new JSONArray();
        res.put(new String(dec, "utf-8"));
        res.put(ver);
        callback.success(res);
    } catch (Exception ex) {
        Log.w("whistle", "Decrypt error:" + ex.getMessage(), ex);
        callback.error(ex);
    }
}

From source file:org.bankinterface.util.Utils.java

/**
 * SHA1withRSA???//from w  ww.j a v  a  2s . c om
 * 
 * @param sourceData
 * @param signData
 * @param certFilePath
 * @param publicKeyAlias
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws UnsupportedEncodingException
 * @throws SignatureException
 */
public static boolean verifySHA1withRSA(String sourceData, String signData, String charset, String certFilePath,
        String publicKeyAlias)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, UnsupportedEncodingException {
    PublicKey publicKey = KeyStoreUtil.getPublicKey(certFilePath, publicKeyAlias);
    Signature signature = Signature.getInstance(ALGORITHM_SHA1WITHRSA);
    signature.initVerify(publicKey);
    signature.update(getBytes(sourceData, charset));
    return signature.verify(getBytes(signData, charset));
}

From source file:com.zxy.commons.codec.rsa.RSAUtils.java

/**
 * <p>//from ww w .j  av  a 2  s.c  o m
 * ??
 * </p>
 * 
 * @param data ?
 * @param publicKey (BASE64?)
 * @param sign ??
 * 
 * @return boolean
 * @throws Exception Exception
 * 
 */
public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
    byte[] keyBytes = Base64.decodeBase64(publicKey);
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    PublicKey publicK = keyFactory.generatePublic(keySpec);
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initVerify(publicK);
    signature.update(data);
    return signature.verify(Base64.decodeBase64(sign));
}