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:org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.util.VirtualFirealarmSecurityManager.java

public static boolean verifySignature(String data, String signedData, PublicKey verificationKey)
        throws VirtualFirealarmDeviceMgtPluginException {

    Signature signature;
    boolean verified;

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

    return verified;
}

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

/**
 * Decrypts a message.//from w w  w  . j a  v a 2  s  .c  o  m
 * @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:com.vmware.identity.rest.core.util.RequestSigner.java

/**
 * Signs a string using the private key and SHA 256 with RSA signing algorithm, and
 * returns it as a hex-encoded string./*  w ww. jav  a  2s.  c om*/
 *
 * @param signingString the string to sign.
 * @param privateKey the private key to sign the string with.
 * @return the signed string in a hex-encoded format.
 * @throws InvalidKeyException if the key is invalid.
 * @throws SignatureException if the signature algorithm is unable to process the input
 * data provided.
 */
public static String sign(String signingString, PrivateKey privateKey)
        throws InvalidKeyException, SignatureException {
    byte[] bytes = signingString.getBytes(StandardCharsets.UTF_8);

    Signature sig;

    try {
        sig = Signature.getInstance(SHA256_WITH_RSA);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("An error occurred while getting the signature algorithm", e);
    }

    sig.initSign(privateKey);
    sig.update(bytes);

    return Hex.encodeHexString(sig.sign());
}

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.util.VirtualFirealarmSecurityManager.java

public static String signMessage(String encryptedData, PrivateKey signatureKey)
        throws VirtualFirealarmDeviceMgtPluginException {

    Signature signature;
    String signedEncodedString;// ww w .j a  v  a 2  s  . co m

    try {
        signature = Signature.getInstance(SIGNATURE_ALG);
        signature.initSign(signatureKey);
        signature.update(Base64.decodeBase64(encryptedData));

        byte[] signatureBytes = signature.sign();
        signedEncodedString = Base64.encodeBase64String(signatureBytes);

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

    return signedEncodedString;
}

From source file:com.vmware.identity.rest.core.util.RequestSigner.java

/**
 * Verify a signed request using a hex-formatted string, the string to sign, and a certificate's public key.
 *
 * @param signedRequestHex a hex-encoded string representing the signed request to verify.
 * @param stringToSign the string that will be signed with the public key for
 * verification purposes./*  w  w  w  . ja v a  2 s .  c  om*/
 * @param publicKey the public key used for verification.
 * @return true if the signature was verified, false if not.
 * @throws DecoderException if there is an error decoding the hex string.
 * @throws InvalidKeyException if the public key is invalid.
 * @throws SignatureException if the signature algorithm is unable to process the input
 * data provided.
 */
public static boolean verify(String signedRequestHex, String stringToSign, PublicKey publicKey)
        throws DecoderException, InvalidKeyException, SignatureException {
    byte[] signedRequest = Hex.decodeHex(signedRequestHex.toCharArray());

    Signature sig;

    try {
        sig = Signature.getInstance(SHA256_WITH_RSA);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("An error occurred while getting the signature algorithm", e);
    }

    sig.initVerify(publicKey);
    sig.update(stringToSign.getBytes(StandardCharsets.UTF_8));

    return sig.verify(signedRequest);
}

From source file:org.apache.abdera2.common.security.HashHelper.java

public static String sig(PrivateKey key, String alg, byte[] mat) {
    try {//from  w w w  .  ja  va2s .  c o  m
        Signature sig = Signature.getInstance(alg);
        sig.initSign((PrivateKey) key);
        sig.update(mat);
        byte[] dat = sig.sign();
        return Base64.encodeBase64URLSafeString(dat);
    } catch (Throwable t) {
        throw ExceptionHelper.propogate(t);
    }
}

From source file:cn.mrdear.pay.util.RSAUtils.java

/**
 * ???//ww  w . ja v  a  2s.c  o m
 * 
 * @param algorithm
 *            ??
 * @param privateKey
 *            ?
 * @param data
 *            ?
 * @return ??
 */
public static byte[] sign(String algorithm, PrivateKey privateKey, byte[] data) {
    Assert.isNotEmpty(algorithm);
    Assert.notNull(privateKey);
    Assert.notNull(data);

    try {
        Signature signature = Signature.getInstance(algorithm, PROVIDER);
        signature.initSign(privateKey);
        signature.update(data);
        return signature.sign();
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (SignatureException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:cn.mrdear.pay.util.RSAUtils.java

/**
 * ???//from w  ww.  j  a  va  2  s  .com
 * 
 * @param algorithm
 *            ??
 * @param publicKey
 *            
 * @param sign
 *            ??
 * @param data
 *            ?
 * @return ??
 */
public static boolean verify(String algorithm, PublicKey publicKey, byte[] sign, byte[] data) {
    Assert.isNotEmpty(algorithm);
    Assert.notNull(publicKey);
    Assert.notNull(sign);
    Assert.notNull(data);

    try {
        Signature signature = Signature.getInstance(algorithm, PROVIDER);
        signature.initVerify(publicKey);
        signature.update(data);
        return signature.verify(sign);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (SignatureException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:cn.mrdear.pay.util.RSAUtils.java

/**
 * ???/*from   ww  w  .jav a2 s  .  c  o  m*/
 * 
 * @param algorithm
 *            ??
 * @param certificate
 *            ?
 * @param sign
 *            ??
 * @param data
 *            ?
 * @return ??
 */
public static boolean verify(String algorithm, Certificate certificate, byte[] sign, byte[] data) {
    Assert.isNotEmpty(algorithm);
    Assert.notNull(certificate);
    Assert.notNull(sign);
    Assert.notNull(data);

    try {
        Signature signature = Signature.getInstance(algorithm, PROVIDER);
        signature.initVerify(certificate);
        signature.update(data);
        return signature.verify(sign);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (SignatureException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:com.valco.utility.FacturasUtility.java

private static byte[] getBytesCadenaFirmada(java.security.PrivateKey pk, OutputStream output)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, UnsupportedEncodingException {
    Signature firma = Signature.getInstance("SHA1withRSA");
    firma.initSign(pk);/*from   w w  w  .  j a  v a2 s  .co m*/
    firma.update(output.toString().getBytes("UTF-8"));
    byte[] cadenaFirmada = firma.sign();
    return cadenaFirmada;
}