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.launchkey.sdk.crypto.JCECrypto.java

/**
 * @see Crypto#verifySignature(byte[], byte[], PublicKey)
 *///from w w w .  j a va 2s . c o  m
public boolean verifySignature(byte[] signature, byte[] message, PublicKey publicKey) {
    try {
        Signature sig = getSha256withRSA();
        sig.initVerify(publicKey);
        sig.update(message);
        return sig.verify(signature);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("Algorithm SHA256withRSA is not available", e);
    } catch (InvalidKeyException e) {
        throw new IllegalArgumentException("publicKey is not a valid RSA public key", e);
    } catch (SignatureException e) {
        throw new IllegalArgumentException("An error occurred processing the signature", e);
    }
}

From source file:com.POLIS.licensing.common.license.AbstractSerializationBasedLicense.java

@Override
public void signLicense(PrivateKey privateSignatureKey)
        throws BadLicenseException, SystemStateException, OperationException {
    try {//from   w ww  .jav a 2s  .  c  om
        Signature instance = Signature.getInstance(signatureEncoding, provider);
        instance.initSign(privateSignatureKey);
        instance.update(getFieldsAsString().getBytes());
        signature = instance.sign();
    } catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
        throw new SystemStateException("Could not sign the license. Algorithm not found", ex);
    } catch (InvalidKeyException | SignatureException ex) {
        throw new OperationException("Could not sign the license.", ex);
    }
}

From source file:org.springframework.security.oauth.common.signature.RSA_SHA1SignatureMethod.java

/**
 * Verify the signature of the given signature base string. The signature is verified by generating a new request signature octet string, and comparing it
 * to the signature provided by the Consumer, first URL-decoded per Parameter Encoding, then base64-decoded per RFC2045 section 6.8. The signature is
 * generated using the request parameters as provided by the Consumer, and the Consumer Secret and Token Secret as stored by the Service Provider.
 *
 * @param signatureBaseString The signature base string.
 * @param signature           The signature.
 * @throws InvalidSignatureException/*  ww  w.ja  va2 s. com*/
 *                                       If the signature is invalid for the specified base string.
 * @throws UnsupportedOperationException If there is no public key.
 */
public void verify(String signatureBaseString, String signature) throws InvalidSignatureException {
    if (publicKey == null) {
        throw new UnsupportedOperationException("A public key must be provided to verify signatures.");
    }

    try {
        byte[] signatureBytes = Base64.decodeBase64(signature.getBytes("UTF-8"));
        Signature verifier = Signature.getInstance("SHA1withRSA");
        verifier.initVerify(publicKey);
        verifier.update(signatureBaseString.getBytes("UTF-8"));
        if (!verifier.verify(signatureBytes)) {
            throw new InvalidSignatureException("Invalid signature for signature method " + getName());
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e);
    } catch (InvalidKeyException e) {
        throw new IllegalStateException(e);
    } catch (SignatureException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.POLIS.licensing.common.license.AbstractSerializationBasedLicense.java

@Override
public boolean verifyLicense(PublicKey senderSignatureKey)
        throws BadLicenseException, SystemStateException, OperationException {

    if (signature == null) {
        throw new OperationException("Could not vertify signature. License was never signed");
    }//from   w  ww .j av  a2s .com
    try {
        Signature instance = Signature.getInstance(signatureEncoding, provider);
        instance.initVerify(senderSignatureKey);
        instance.update(getFieldsAsString().getBytes());
        return instance.verify(signature);
    } catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
        throw new SystemStateException("Could not verify the license. Algorithm not found", ex);
    } catch (InvalidKeyException | SignatureException ex) {
        throw new OperationException("Could not verify the license.", ex);
    }
}

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);//w w w  . ja  va2s .c  om
    sig.update(bytes);
    byte[] signed = sig.sign();
    Base64 b64 = new Base64(-1);
    return b64.encodeToString(signed);
}

From source file:com.launchkey.sdk.crypto.JCECrypto.java

/**
 * @see Crypto#sign(byte[])//from w w  w.ja v  a  2s.c  om
 */
public byte[] sign(byte[] message) {
    try {
        Signature signature = getSha256withRSA();
        signature.initSign(privateKey);
        signature.update(message);
        return signature.sign();
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("Algorithm SHA256withRSA is not available", e);
    } catch (InvalidKeyException e) {
        throw new IllegalArgumentException("publicKey is not a valid RSA public key", e);
    } catch (SignatureException e) {
        throw new IllegalArgumentException("An error occurred processing the signature", e);
    }
}

From source file:no.digipost.api.client.filters.response.ResponseSignatureFilter.java

@Override
public void filter(final ClientRequestContext clientRequestContext,
        final ClientResponseContext clientResponseContext) throws IOException {

    // TODO configure this on relevant WebTarget instead
    if ("/".equals(clientRequestContext.getUri().getPath())) {
        eventLogger.log("Verifiserer ikke signatur fordi det er rotressurs vi hentet.");
        return;//from  w w w. j  ava  2 s .  c om
    }

    try {
        String serverSignaturBase64 = getServerSignaturFromResponse(clientResponseContext);
        byte[] serverSignaturBytes = Base64.decode(serverSignaturBase64.getBytes());

        String signatureString = getCanonicalResponseRepresentation(
                new ClientResponseToVerify(clientRequestContext, clientResponseContext));

        Signature instance = Signature.getInstance("SHA256WithRSAEncryption");
        instance.initVerify(lastSertifikat());
        instance.update(signatureString.getBytes());
        boolean verified = instance.verify(serverSignaturBytes);
        if (!verified) {
            throw new DigipostClientException(SERVER_SIGNATURE_ERROR,
                    "Melding fra server matcher ikke signatur.");
        } else {
            eventLogger.log("Verifiserte signert respons fra Digipost. Signatur fra HTTP-headeren "
                    + X_Digipost_Signature + " var OK: " + serverSignaturBase64);
        }
    } catch (Exception e) {
        LoggingUtil.logResponse(clientResponseContext);
        if (shouldThrow) {
            if (e instanceof DigipostClientException) {
                throw (DigipostClientException) e;
            } else {
                throw new DigipostClientException(SERVER_SIGNATURE_ERROR,
                        "Det skjedde en feil under signatursjekk: " + e.getMessage());
            }
        } else {
            LOG.warn("Feil under validering av server signatur: '" + e.getMessage() + "'. "
                    + (LOG.isDebugEnabled() ? ""
                            : "Konfigurer debug-logging for " + LOG.getName() + " for  se full stacktrace."));
            LOG.debug(e.getMessage(), e);
        }
    }
}

From source file:test.integ.be.fedict.hsm.client.HSMProxyClientTest.java

@Test
public void testSign() throws Exception {
    Security.addProvider(new BeIDProvider());
    KeyStore beidKeyStore = KeyStore.getInstance("BeID");
    beidKeyStore.load(null);//from   w  w w. ja v a  2 s .co  m
    X509Certificate authnCert = (X509Certificate) beidKeyStore.getCertificate("Authentication");
    PrivateKey authnPrivateKey = (PrivateKey) beidKeyStore.getKey("Authentication", null);

    String location = "http://localhost:8080/hsm-proxy-ws/dss";
    // String location = "https://www.e-contract.be/hsm-proxy-ws/dss";
    HSMProxyClient client = new HSMProxyClient(location, authnPrivateKey, authnCert);
    // client.setProxy("proxy.yourict.net", 8080);

    byte[] toBeSigned = "hello world".getBytes();
    MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
    messageDigest.update(toBeSigned);
    byte[] digestValue = messageDigest.digest();

    String keyAlias = "alias";

    byte[] signatureValue = client.sign(digestValue, "SHA1", keyAlias);
    assertNotNull(signatureValue);
    LOG.debug("signature value length: " + signatureValue.length);

    X509Certificate certificate = client.getCertificateChain(keyAlias).get(0);
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initVerify(certificate.getPublicKey());
    signature.update(toBeSigned);
    assertTrue(signature.verify(signatureValue));
}

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

public void verify() throws Exception {
    String certStr = document.getCertificado();
    Base64 b64 = new Base64();
    byte[] cbs = b64.decode(certStr);
    X509Certificate cert = KeyLoader.loadX509Certificate(new ByteArrayInputStream(cbs));
    cert.checkValidity();//from   w  w w .j ava 2s .c o m
    String sigStr = document.getSello();
    byte[] signature = b64.decode(sigStr);
    byte[] bytes = getOriginalBytes();
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initVerify(cert);
    sig.update(bytes);
    boolean bool = sig.verify(signature);
    if (!bool) {
        throw new Exception("Invalid signature");
    }
}

From source file:mx.bigdata.sat.cfdi.TFDv1.java

public int verificar() throws Exception {
    if (tfd == null) {
        return 601; //No contiene timbrado
    }/*from   w w  w .  ja v  a 2 s  .  com*/
    Base64 b64 = new Base64();
    String sigStr = tfd.getSelloSAT();
    byte[] signature = b64.decode(sigStr);
    byte[] bytes = getOriginalBytes();
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initVerify(cert);
    sig.update(bytes);
    boolean verified = sig.verify(signature);
    return verified ? 600 : 602; //Sello del timbrado no valido
}