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.zxy.commons.codec.rsa.RSAUtils.java

/**
 * <p>//from  w ww  .  ja v  a  2  s.  c  o m
 * ?????
 * </p>
 * 
 * @param data ?
 * @param privateKey ?(BASE64?)
 * 
 * @return String
 * @throws Exception Exception
 */
public static String sign(byte[] data, String privateKey) throws Exception {
    byte[] keyBytes = Base64.decodeBase64(privateKey);
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initSign(privateK);
    signature.update(data);
    return new String(Base64.encodeBase64(signature.sign()));
}

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

/**
 * <p>//ww w  . j a v  a2 s.  co 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));
}

From source file:jfabrix101.billing.BillingSecurity.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. 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 (BillingConsts.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 (Exception e) {
        Log.e(TAG, "Base64 decoding failed.");
    }
    return false;
}

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

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

    Signature signature;
    boolean verified;

    try {//from   ww  w .j  av  a2 s.  c  om
        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 VirtualFirealarmDeviceMgtPluginException(errorMsg, e);
    } catch (SignatureException e) {
        String errorMsg = "Signature exception occurred for Signature instance of [" + SHA_512 + "]";
        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:org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.SecurityManager.java

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

    Signature signature;
    boolean verified;

    try {//from w  w  w  .  j  a  v a2  s. c  om
        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 VirtualFireAlarmException(errorMsg, e);
    } catch (SignatureException e) {
        String errorMsg = "Signature exception occurred for Signature instance of [" + SIGNATURE_ALG + "]";
        log.error(errorMsg);
        throw new VirtualFireAlarmException(errorMsg, e);
    } catch (InvalidKeyException e) {
        String errorMsg = "InvalidKey exception occurred for signatureKey \n[\n" + verificationKey + "\n]\n";
        log.error(errorMsg);
        throw new VirtualFireAlarmException(errorMsg, e);
    }

    return verified;
}

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

/**
 * Encrypts a message./*from   w w w. j  a v  a 2  s.  c  o  m*/
 * @param args Arguments: data, publicKey[, privateKey]
 * @param callback Callback
 */
public static void encrypt(JSONArray args, AsyncCallback<JSONArray> callback) {
    try {
        PRNGProvider.init(); // Ensure OpenSSL fix

        // Get the arguments
        String data = args.getString(0);
        String pub = args.getString(1);
        String priv = null;
        if (args.length() == 3) {
            priv = args.getString(2);
        }
        String sig = null;

        // Convert everything into byte arrays
        byte[] dataRaw = data.getBytes("utf-8");
        byte[] pubRaw = Base64.decode(stripKey(pub), Base64.DEFAULT);

        // Generate random AES key and IV
        byte[] aesKey = new byte[AES_BYTES];
        new SecureRandom().nextBytes(aesKey);
        byte[] aesIv = new byte[16]; // Block size
        new SecureRandom().nextBytes(aesIv);
        Cipher c = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
        c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(aesIv));

        // Encrypt data with AES
        byte[] encData = c.doFinal(dataRaw);

        // Encrypt aes data with RSA
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubRaw);
        KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
        c = Cipher.getInstance("RSA/None/OAEPWithSHA-1AndMGF1Padding", "BC");
        c.init(Cipher.ENCRYPT_MODE, kf.generatePublic(publicKeySpec));
        c.update(aesKey);
        c.update(aesIv);
        byte[] encKey = c.doFinal();

        // Concatenate and transform
        byte[] encRaw = new byte[encKey.length + encData.length];
        System.arraycopy(encKey, 0, encRaw, 0, encKey.length);
        System.arraycopy(encData, 0, encRaw, encKey.length, encData.length);
        encKey = null;
        encData = null;
        String enc = new String(Base64.encode(encRaw /* needed for sign */, Base64.NO_WRAP), "utf-8");

        // Sign
        if (priv != null) {
            // Fail on error (no try-catch)
            byte[] privRaw = Base64.decode(stripKey(priv), Base64.DEFAULT);
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privRaw);
            Signature s = Signature.getInstance("SHA1withRSA", "BC");
            s.initSign(kf.generatePrivate(privateKeySpec));
            s.update(encRaw);
            sig = new String(Base64.encode(s.sign(), Base64.NO_WRAP), "utf-8");
        }

        JSONArray res = new JSONArray();
        res.put(enc);
        res.put(sig);
        callback.success(res);
    } catch (Exception ex) {
        Log.w("whistle", "Encrypt error: " + ex.getMessage(), ex);
        callback.error(ex);
    }
}

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

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

    Signature signature;
    String signedEncodedString;/*from  w  w w  . j a  v  a  2s  . c  o  m*/

    try {
        signature = Signature.getInstance(SHA_512);
        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 [" + SHA_512 + "]";
        log.error(errorMsg);
        throw new VirtualFirealarmDeviceMgtPluginException(errorMsg, e);
    } catch (SignatureException e) {
        String errorMsg = "Signature exception occurred for Signature instance of [" + SHA_512 + "]";
        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:org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.SecurityManager.java

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

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

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

    return signedEncodedString;
}

From source file:be.fedict.eid.dss.protocol.simple.client.SignatureRequestUtil.java

/**
 * Constructs a DSS Simple Protocol service signature.
 * <p/>/*ww w.j  a va  2  s.  c  om*/
 * If no spIdentity is specified returns <code>null</code>
 * 
 * @param spIdentity
 *            the SP Identity used for signing.
 * @param signatureRequest
 *            signature request, if <code>null</code> signatureRequestId
 *            needs to be specified.
 * @param signatureRequestId
 *            signature request ID, if <code>null</code>, signatureRequest
 *            needs to be specified
 * @param target
 *            required target
 * @param language
 *            optional language param
 * @param contentType
 *            optional document content type
 * @param relayState
 *            optional relay state
 * @return service signature DO containing the signature value, service
 *         signed property listing up all signed properties and the SP
 *         certificate chain.
 * @throws NoSuchAlgorithmException
 *             algorithm to sign/digest not found.
 * @throws InvalidKeyException
 *             signing key not valid
 * @throws SignatureException
 *             signature creation failure
 * @throws CertificateEncodingException
 *             certificate encoding failure
 */
public static ServiceSignatureDO getServiceSignature(

        KeyStore.PrivateKeyEntry spIdentity, String signatureRequest, String signatureRequestId, String target,
        String language, String contentType, String relayState)

        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, CertificateEncodingException {

    LOG.debug("get service signature");

    if (null == spIdentity) {
        LOG.warn("No SP Identity specified, no signature added.");
        return null;
    }
    if (null == signatureRequest && null == signatureRequestId) {
        throw new RuntimeException(
                "Either \"SignatureRequest\" or " + "\"SignatureRequestId\" needs to be provided.");
    }

    // construct service signature
    // TODO: configurable?
    Signature serviceSignature = Signature.getInstance("SHA1withRSA");
    serviceSignature.initSign(spIdentity.getPrivateKey());

    serviceSignature.update(target.getBytes());
    if (null != signatureRequest) {
        serviceSignature.update(signatureRequest.getBytes());
    } else {
        serviceSignature.update(signatureRequestId.getBytes());
    }
    if (null != language) {
        serviceSignature.update(language.getBytes());
    }
    if (null != contentType) {
        serviceSignature.update(contentType.getBytes());
    }
    if (null != relayState) {
        serviceSignature.update(relayState.getBytes());
    }

    byte[] serviceSignatureValue = serviceSignature.sign();

    String encodedServiceSignature = Base64.encodeBase64String(serviceSignatureValue);

    // construct service signed
    String serviceSigned = "target";
    if (null != signatureRequest) {
        serviceSigned += ",SignatureRequest";
    } else {
        serviceSigned += ",SignatureRequestId";
    }
    if (null != language) {
        serviceSigned += ",language";
    }
    if (null != contentType) {
        serviceSigned += ",ContentType";
    }
    if (null != relayState) {
        serviceSigned += ",RelayState";
    }

    // construct service certificate chain
    java.security.cert.Certificate[] serviceCertificateChain = spIdentity.getCertificateChain();
    String serviceCertificateChainSize = Integer.toString(serviceCertificateChain.length);

    List<String> serviceCertificates = new LinkedList<String>();
    for (java.security.cert.Certificate certificate : serviceCertificateChain) {
        String encodedServiceCertificate = Base64.encodeBase64String(certificate.getEncoded());
        serviceCertificates.add(encodedServiceCertificate);
    }

    return new ServiceSignatureDO(serviceSigned, encodedServiceSignature, serviceCertificateChainSize,
            serviceCertificates);
}

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

public static boolean sigval(PublicKey key, String alg, byte[] mat, byte[] dat) {
    try {//from w  w  w  .  j  av  a2  s  .c o  m
        Signature sig = Signature.getInstance(alg);
        sig.initVerify(key);
        sig.update(mat);
        return sig.verify(dat);
    } catch (Throwable t) {
        throw ExceptionHelper.propogate(t);
    }
}