Example usage for java.security Signature getInstance

List of usage examples for java.security Signature getInstance

Introduction

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

Prototype

public static Signature getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a Signature object that implements the specified signature algorithm.

Usage

From source file:mx.bigdata.cfdi.CFDv3.java

String getSignature(PrivateKey key) throws Exception {
    byte[] bytes = getOriginalBytes();
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initSign(key);/*  ww  w .ja  v  a2s .c o m*/
    sig.update(bytes);
    byte[] signed = sig.sign();
    Base64 b64 = new Base64(-1);
    return b64.encodeToString(signed);
}

From source file:com.vmware.identity.sts.auth.impl.UserCertAuthenticator.java

private boolean verifyUserCertSignature(X509Certificate x509Certificate, String signedInfo,
        byte[] signatureValue) {

    try {//from  www. java2  s .com
        PublicKey publicKey = x509Certificate.getPublicKey();
        Signature signature = Signature.getInstance("SHA256WithRSA");
        signature.initVerify(publicKey);
        signature.update(signedInfo.getBytes());
        return signature.verify(signatureValue);
    } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
        throw new InvalidCredentialsException("User certificate token signature validation failed.", e);
    }
}

From source file:com.vimukti.accounter.license.LicenseManager.java

public LicensePair doEncode(License license) {

    byte[] licenseText = null;
    byte[] hash;//  w w w. j  a  v  a 2 s  .c o  m
    try {
        licenseText = Zip.compressBytes(new PropertiesPersister().getLicenseAsString(license));
    } catch (UnsupportedEncodingException e) {
        throw new LicenseException(e);
    } catch (IOException e) {
        throw new LicenseException(e);
    }

    try {
        Signature signature = Signature.getInstance("SHA1withDSA");
        signature.initSign(getPrivateKey());
        signature.update(licenseText);
        hash = signature.sign();
    } catch (InvalidKeyException e) {
        throw new LicenseException(e);
    } catch (SignatureException e) {
        throw new LicenseException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new LicenseException(e);
    }

    String packLicense = packLicense(licenseText, hash);

    return new LicensePair(licenseText, hash, packLicense);
}

From source file:com.cedarsoft.crypt.X509Support.java

/**
 * <p>verifySignature</p>/*from  w ww.j  a va2s  .c o  m*/
 *
 * @param plainText an array of byte.
 * @param signature a com.cedarsoft.crypt.Signature object.
 * @return a boolean.
 *
 * @throws GeneralSecurityException
 *          if any.
 */
public boolean verifySignature(@Nonnull byte[] plainText, @Nonnull com.cedarsoft.crypt.Signature signature)
        throws GeneralSecurityException {
    Signature sign = Signature.getInstance(SHA_256_WITH_RSA);
    sign.initVerify(certificate);
    sign.update(plainText);
    return sign.verify(signature.getBytes());
}

From source file:org.wso2.carbon.identity.agent.onprem.userstore.security.JWTSecurityInterceptor.java

private boolean isValid(String jwtToken) {

    String[] jwtTokenValues = jwtToken.split("\\.");
    String jwtAssertion = null;// w  w w .  j a  v a  2s .  c o  m
    byte[] jwtSignature = null;

    if (jwtTokenValues.length > 0) {
        String value = new String(base64Url.decode(jwtTokenValues[0].getBytes()));
        JSONParser parser = new JSONParser();
        try {
            jsonHeaderObject = (JSONObject) parser.parse(value);
        } catch (ParseException e) {
            log.error("Error occurred while parsing JSON header ", e);
        }
    }

    if (jwtTokenValues.length > 1) {
        jwtAssertion = jwtTokenValues[0] + "." + jwtTokenValues[1];
    }

    if (jwtTokenValues.length > 2) {
        jwtSignature = base64Url.decode(jwtTokenValues[2].getBytes());
    }

    if (jwtAssertion != null && jwtSignature != null) {

        try {
            File publicKeyFile = new File(System.getProperty(CommonConstants.CARBON_HOME),
                    File.separator + PUBLIC_KEY_LOCATION);
            InputStream inStream = new FileInputStream(publicKeyFile);

            DataInputStream dis = new DataInputStream(inStream);
            byte[] keyBytes = new byte[(int) publicKeyFile.length()];
            dis.readFully(keyBytes);
            dis.close();
            String publicKeyPEM = new String(keyBytes);
            BASE64Decoder b64 = new BASE64Decoder();
            byte[] decoded = b64.decodeBuffer(publicKeyPEM);

            X509EncodedKeySpec spec = new X509EncodedKeySpec(decoded);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            PublicKey publicKey = kf.generatePublic(spec);

            Signature signature = Signature.getInstance(getSignatureAlgorithm(jsonHeaderObject));
            signature.initVerify(publicKey);
            signature.update(jwtAssertion.getBytes());
            return signature.verify(jwtSignature);
        } catch (Exception e) {
            log.error("Error occurred while validating signature", e);
        }
    } else {
        log.warn("No signature exist in the request.");
        return false;
    }
    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.//  w w  w . jav  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: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./*w ww  .  ja  v  a 2s.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:org.icestuff.getdown.maven.SignConfig.java

private void sign(File inputFile, File signatureFile)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException, InvalidKeyException, SignatureException {
    // initialize the keystore
    KeyStore store = KeyStore.getInstance(storetype == null ? "JKS" : storetype);
    FileInputStream storeInput = new FileInputStream(getKeystore());
    store.load(storeInput, getStorepass().toCharArray());
    PrivateKey key = (PrivateKey) store.getKey(getAlias(),
            getKeypass() == null ? getKeypass().toCharArray() : getKeypass().toCharArray());

    // sign the digest file
    Signature sig = Signature.getInstance("SHA1withRSA");
    FileInputStream dataInput = new FileInputStream(inputFile);
    byte[] buffer = new byte[8192];
    int length;//ww w  .j  a v  a  2 s. c  o  m

    sig.initSign(key);
    while ((length = dataInput.read(buffer)) != -1) {
        sig.update(buffer, 0, length);
    }

    // Write out the signature
    FileOutputStream signatureOutput = new FileOutputStream(signatureFile);
    String signed = new String(Base64.encodeBase64(sig.sign()));
    signatureOutput.write(signed.getBytes("utf8"));
}

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 ww  w  .ja  v a 2  s. co 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: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./*from w w  w .j a  v  a 2 s  .  c  om*/
 *
 * @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;
}