Example usage for java.security Signature initSign

List of usage examples for java.security Signature initSign

Introduction

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

Prototype

public final void initSign(PrivateKey privateKey) throws InvalidKeyException 

Source Link

Document

Initialize this object for signing.

Usage

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

/**
 * Signed a given message using the PrivateKey that's passes in.
 *
 * @param message      the message to be signed. Ideally some encrypted payload.
 * @param signatureKey the PrivateKey with which the message is to be signed.
 * @return the Base64Encoded String of the signed payload.
 * @throws TransportHandlerException if some error occurs with the signing process which may be related to the
 *                                   signature algorithm used or the key used for signing.
 *//*from   w ww.  jav a2  s .c  om*/
public static String signMessage(String message, PrivateKey signatureKey) throws TransportHandlerException {

    Signature signature;
    String signedEncodedString;

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

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

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

/**
 * ????/*w w  w  . j a va 2 s. co  m*/
 * <dl>
 * <dt>?
 * <dd>NONEwithECDSA???????????????
 * </dl>
 * @param key ?
 * @param data 
 * @return ??
 */
public static byte[] sign(final PrivateKey key, final byte[] data) {
    try {
        final Signature sign = Signature.getInstance("NONEwithECDSA");
        sign.initSign(key);
        sign.update(data);
        return sign.sign();
    } catch (final NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
        throw new StandardRuntimeException(e);
    }
}

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

/**
 * Signed a given message using the PrivateKey that's passes in.
 *
 * @param message      the message to be signed. Ideally some encrypted payload.
 * @param signatureKey the PrivateKey with which the message is to be signed.
 * @return the Base64Encoded String of the signed payload.
 * @throws AgentCoreOperationException if some error occurs with the signing process which may be related to the
 *                                     signature algorithm used or the key used for signing.
 *//*from   w  w w  .j  av a  2  s  . com*/
public static String signMessage(String message, PrivateKey signatureKey) throws AgentCoreOperationException {

    Signature signature;
    String signedEncodedString;

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

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

    return signedEncodedString;
}

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

/**
 * Signed a given message using the PrivateKey that's passes in.
 *
 * @param message      the message to be signed. Ideally some encrypted payload.
 * @param signatureKey the PrivateKey with which the message is to be signed.
 * @return the Base64Encoded String of the signed payload.
 * @throws TransportHandlerException if some error occurs with the signing process which may be related to the
 *                                   signature algorithm used or the key used for signing.
 *//*ww w .j  av  a 2 s .  c  o m*/
public static String signMessage(String message, PrivateKey signatureKey) throws TransportHandlerException {

    Signature signature;
    String signedEncodedString;

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

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

    return signedEncodedString;
}

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

/**
 * Encrypts a message.//from  w  w w .j av a  2  s  . com
 * @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.apache.cloudstack.utils.auth.SAMLUtils.java

public static String generateSAMLRequestSignature(String urlEncodedString, PrivateKey signingKey)
        throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, UnsupportedEncodingException {
    if (signingKey == null) {
        return urlEncodedString;
    }/*  ww w  . j  av  a 2 s.  co  m*/
    String url = urlEncodedString + "&SigAlg="
            + URLEncoder.encode(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1, HttpUtils.UTF_8);
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(signingKey);
    signature.update(url.getBytes());
    String signatureString = Base64.encodeBytes(signature.sign(), Base64.DONT_BREAK_LINES);
    if (signatureString != null) {
        return url + "&Signature=" + URLEncoder.encode(signatureString, HttpUtils.UTF_8);
    }
    return url;
}

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

/**
 * SHA1withRSA???,??//from   w  ww .j a  v a2  s  .c om
 * 
 * @param data
 * @param charset
 * @param certFilePath
 * @param privateKeyAlias
 * @param code
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws UnsupportedEncodingException
 * @throws SignatureException
 */
public static String signSHA1withRSA(String data, String charset, String certFilePath, String privateKeyAlias,
        String code)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, UnsupportedEncodingException {
    PrivateKey privateKey = KeyStoreUtil.getPrivateKey(certFilePath, privateKeyAlias);
    Signature signature = Signature.getInstance(ALGORITHM_SHA1WITHRSA);
    signature.initSign(privateKey);
    signature.update(getBytes(data, charset));
    byte[] bytes = signature.sign();
    return Utils.encode(bytes, code);
}

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

/**
 * Constructs a DSS Simple Protocol service signature.
 * <p/>// ww  w.  ja  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:com.zxy.commons.codec.rsa.RSAUtils.java

/**
 * <p>//w  ww  .j  a va2  s .  com
 * ?????
 * </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: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;/* w  w w .ja  v  a 2 s.co  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;
}