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.eucalyptus.auth.euare.EuareServerCertificateUtil.java

public static boolean verifySignature(final String certPem, final String msg, final String sigB64) {
    try {// ww  w  .  ja  va2  s .  com
        final Signature sig = Signature.getInstance("SHA256withRSA");
        final X509Certificate cert = PEMFiles.getCert(B64.standard.dec(certPem));
        sig.initVerify(cert);
        sig.update(msg.getBytes("UTF-8"));
        return sig.verify(B64.standard.dec(sigB64.getBytes()));
    } catch (final Exception ex) {
        throw Exceptions.toUndeclared(ex);
    }
}

From source file:ee.ria.xroad.common.request.ManagementRequestHandler.java

private static boolean verifySignature(X509Certificate cert, byte[] signatureData, String signatureAlgorithmId,
        byte[] dataToVerify) throws Exception {
    try {/*from  ww w.j ava 2 s  . c om*/
        Signature signature = Signature.getInstance(signatureAlgorithmId, "BC");
        signature.initVerify(cert.getPublicKey());
        signature.update(dataToVerify);

        return signature.verify(signatureData);
    } catch (Exception e) {
        log.error("Failed to verify signature", e);

        throw translateException(e);
    }
}

From source file:pepperim.util.IMCrypt.java

/**
 * Regular RSA signing (using SHA1-hash)
 * @param data Data to be signed/* ww w .ja  va 2  s  .  co  m*/
 * @param key Key to be used for the signature
 * @return Base64-encoded RSA signature
 */
public static String RSA_Sign(String data, PrivateKey key) {
    try {
        Signature signer = Signature.getInstance("SHA1withRSA");
        signer.initSign(key);
        signer.update(data.getBytes());
        byte[] signature = signer.sign();
        return B64_Enc(signature);
    } catch (GeneralSecurityException e) {
        Main.log(e.getMessage());
        return "";
    }
}

From source file:org.opensaml.security.crypto.SigningUtil.java

/**
 * Compute the raw signature value over the supplied input.
 * /*  w ww  . jav  a 2 s. c om*/
 * It is up to the caller to ensure that the specified algorithm ID is consistent with the type of signing key
 * supplied.
 * 
 * @param signingKey the private key with which to compute the signature
 * @param jcaAlgorithmID the Java JCA algorithm ID to use
 * @param input the input over which to compute the signature
 * @return the computed signature value
 * @throws SecurityException thrown if the signature computation results in an error
 */
@Nonnull
public static byte[] sign(@Nonnull final PrivateKey signingKey, @Nonnull final String jcaAlgorithmID,
        @Nonnull final byte[] input) throws SecurityException {
    Constraint.isNotNull(signingKey, "Private key cannot be null");
    Constraint.isNotNull(jcaAlgorithmID, "JCA algorithm ID cannot be null");
    Constraint.isNotNull(input, "Input data to sign cannot be null");

    Logger log = getLogger();
    log.debug("Computing signature over input using private key of type {} and JCA algorithm ID {}",
            signingKey.getAlgorithm(), jcaAlgorithmID);

    try {
        Signature signature = Signature.getInstance(jcaAlgorithmID);
        signature.initSign(signingKey);
        signature.update(input);
        byte[] rawSignature = signature.sign();
        log.debug("Computed signature: {}", Hex.encodeHex(rawSignature));
        return rawSignature;
    } catch (GeneralSecurityException e) {
        log.error("Error during signature generation", e);
        throw new SecurityException("Error during signature generation", e);
    }
}

From source file:pepperim.util.IMCrypt.java

/**
 * @param data Data to be verified/*  w w  w  .ja v a  2  s  . c  o m*/
 * @param b64sig Base64-encoded RSA signature
 * @param key Public key of the signature source
 * @return true on success, false if the verification fails
 */
public static boolean RSA_Verify(String data, String b64sig, PublicKey key) {
    try {
        Signature verifier = Signature.getInstance("SHA1withRSA");
        verifier.initVerify(key);
        verifier.update(data.getBytes());
        return verifier.verify(B64_Dec(b64sig));
    } catch (GeneralSecurityException e) {
        Main.log(e.getMessage());
        return false;
    }
}

From source file:Main.java

protected static void updateSignature(final Signature signature, final boolean relaxed,
        final boolean ischeduleRelaxed, final CharSequence header, final String fv) throws SignatureException {
    if (relaxed | ischeduleRelaxed) {
        if (deepDebug) {
            trace("#" + header.toString().toLowerCase() + ":-");
        }/*from   ww w .  ja  v a 2s.  co  m*/
        signature.update(header.toString().toLowerCase().getBytes());
        signature.update(":".getBytes());
        String headerValue = fv.substring(fv.indexOf(':') + 1);
        headerValue = headerValue.replaceAll("\r\n[\t ]", " ");
        headerValue = headerValue.replaceAll("[\t ]+", " ");

        if (ischeduleRelaxed) {
            headerValue = headerValue.replaceAll(" , ", ",");
        }

        headerValue = headerValue.trim();
        signature.update(headerValue.getBytes());
        if (deepDebug) {
            trace("#" + headerValue + "#");
        }
    } else {
        signature.update(fv.getBytes());
        if (deepDebug) {
            trace("#" + fv + "#");
        }
    }
}

From source file:com.amazon.speech.speechlet.authentication.SpeechletRequestSignatureVerifier.java

/**
 * Verifies the certificate authenticity using the configured TrustStore and the signature of
 * the speechlet request./*  w  ww  .  j  av a 2s .c  o m*/
 *
 * @param serializedSpeechletRequest
 *            speechlet request serialized as a string of JSON
 * @param baseEncoded64Signature
 *            the signature for provided in the request header
 * @param signingCertificateChainUrl
 *            the certificate chain URL provided in the request header
 */
public static void checkRequestSignature(final byte[] serializedSpeechletRequest,
        final String baseEncoded64Signature, final String signingCertificateChainUrl) {
    if ((baseEncoded64Signature == null) || (signingCertificateChainUrl == null)) {
        throw new SecurityException("Missing signature/certificate for the provided speechlet request");
    }

    try {
        X509Certificate signingCertificate;
        if (CERTIFICATE_CACHE.containsKey(signingCertificateChainUrl)) {
            signingCertificate = CERTIFICATE_CACHE.get(signingCertificateChainUrl);
            /*
             * check the before/after dates on the certificate are still valid for the present
             * time
             */
            signingCertificate.checkValidity();
        } else {
            signingCertificate = retrieveAndVerifyCertificateChain(signingCertificateChainUrl);

            // if certificate is valid, then add it to the cache
            CERTIFICATE_CACHE.put(signingCertificateChainUrl, signingCertificate);
        }

        // verify that the request was signed by the provided certificate
        Signature signature = Signature.getInstance(Sdk.SIGNATURE_ALGORITHM);
        signature.initVerify(signingCertificate.getPublicKey());
        signature.update(serializedSpeechletRequest);
        if (!signature.verify(Base64.decodeBase64(baseEncoded64Signature.getBytes(Sdk.CHARACTER_ENCODING)))) {
            throw new SecurityException(
                    "Failed to verify the signature/certificate for the provided speechlet request");
        }
    } catch (CertificateException | SignatureException | NoSuchAlgorithmException | InvalidKeyException
            | IOException ex) {
        throw new SecurityException(
                "Failed to verify the signature/certificate for the provided speechlet request", ex);
    }
}

From source file:ai.susi.tools.JsonSignature.java

/**
 * Create and add a signature to a JSONObject
 * @param obj the JSONObject//from  w  w  w .j  av a 2s  .  co m
 * @param key the private key to use
 * @throws InvalidKeyException if the key is not valid (for example not RSA)
 * @throws SignatureException if something with the JSONObject is bogus
 */
public static void addSignature(JSONObject obj, PrivateKey key) throws InvalidKeyException, SignatureException {

    removeSignature(obj);

    Signature signature;
    try {
        signature = Signature.getInstance("SHA256withRSA");
    } catch (NoSuchAlgorithmException e) {
        return; //does not happen
    }

    signature.initSign(key);
    signature.update(obj.toString().getBytes(StandardCharsets.UTF_8));

    byte[] sigBytes = signature.sign();

    obj.put(signatureString, new String(Base64.getEncoder().encode(sigBytes)));
}

From source file:ai.susi.tools.JsonSignature.java

public static void addSignature(Map<String, byte[]> obj, PrivateKey key)
        throws InvalidKeyException, SignatureException {

    removeSignature(obj);/*from w w  w  .  ja v a  2s . c o  m*/

    Signature signature;
    try {
        signature = Signature.getInstance("SHA256withRSA");
    } catch (NoSuchAlgorithmException e) {
        return; //does not happen
    }

    signature.initSign(key);
    signature.update(obj.toString().getBytes(StandardCharsets.UTF_8));

    byte[] sigBytes = signature.sign();

    obj.put(signatureString, Base64.getEncoder().encode(sigBytes));
}

From source file:com.sammyun.util.RSAUtils.java

/**
 * RSA??/*from   w  w  w .  ja  v  a 2 s . c o m*/
 * 
 * @param content ???
 * @param privateKey ?
 * @param input_charset ??
 * @return ??
 */
public static String sign(String content, String privateKey, String input_charset) {
    try {
        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64Util.decode(privateKey));
        KeyFactory keyf = KeyFactory.getInstance("RSA");
        PrivateKey priKey = keyf.generatePrivate(priPKCS8);
        java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
        signature.initSign(priKey);
        signature.update(content.getBytes(input_charset));
        byte[] signed = signature.sign();
        return Base64Util.encode(signed);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}