Example usage for java.security Signature initVerify

List of usage examples for java.security Signature initVerify

Introduction

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

Prototype

public final void initVerify(Certificate certificate) throws InvalidKeyException 

Source Link

Document

Initializes this object for verification, using the public key from the given certificate.

Usage

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

/**
 * @see Crypto#verifySignature(byte[], byte[], PublicKey)
 *///from   ww  w  .j a  v  a  2 s .  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: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  ww  . j  a  v  a 2 s .  com
    }

    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.be.fedict.eid.applet.SignatureServiceImpl.java

public void postSign(byte[] signatureValue, List<X509Certificate> signingCertificateChain) {
    LOG.debug("postSign");

    String signatureValueStr = new String(Hex.encodeHex(signatureValue));

    HttpSession session = getHttpSession();
    session.setAttribute("SignatureValue", signatureValueStr);
    session.setAttribute("SigningCertificateChain", signingCertificateChain);

    boolean signatureValid = false;
    String toBeSigned = (String) session.getAttribute("toBeSigned");
    LOG.debug("to be signed: " + toBeSigned);
    String digestAlgo = (String) session.getAttribute("digestAlgo");
    String signAlgo = digestAlgoToSignAlgo.get(digestAlgo);

    try {/*from   www  . j  a  va  2 s .  c o  m*/
        Signature signature = Signature.getInstance(signAlgo, BouncyCastleProvider.PROVIDER_NAME);
        signature.initVerify(signingCertificateChain.get(0).getPublicKey());
        signature.update(toBeSigned.getBytes());
        signatureValid = signature.verify(signatureValue);
    } catch (Exception e) {
        LOG.error("error validating the signature: " + e.getMessage(), e);
    }

    session.setAttribute("SignatureValid", signatureValid);
}

From source file:Decoder.java

private byte[] checkAndGetLicenseText(String licenseContent) throws Exception {
    byte[] licenseText;
    try {/*  w ww  . j  av a 2 s.  co  m*/
        byte[] decodedBytes = Base64.decodeBase64(licenseContent.getBytes());
        ByteArrayInputStream in = new ByteArrayInputStream(decodedBytes);
        DataInputStream dIn = new DataInputStream(in);
        int textLength = dIn.readInt();
        licenseText = new byte[textLength];
        dIn.read(licenseText);
        byte[] hash = new byte[dIn.available()];
        dIn.read(hash);
        try {
            Signature signature = Signature.getInstance("SHA1withDSA");
            signature.initVerify(PUBLIC_KEY);
            signature.update(licenseText);
            if (!signature.verify(hash)) {
                throw new Exception("Failed to verify the license.");
            }

        } catch (InvalidKeyException e) {
            throw new Exception(e);
        } catch (SignatureException e) {
            throw new Exception(e);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception(e);
        }

    } catch (IOException e) {
        throw new Exception(e);
    }

    return licenseText;
}

From source file:com.turo.pushy.apns.auth.ApnsVerificationKey.java

/**
 * Constructs a new verification key with the given key identifier, team identifier, and elliptic curve private key.
 *
 * @param keyId the ten-character, Apple-issued identifier for the key itself
 * @param teamId the ten-character, Apple-issued identifier for the team to which the key belongs
 * @param key the elliptic curve private key underpinning this signing key
 *
 * @throws NoSuchAlgorithmException if the {@value APNS_SIGNATURE_ALGORITHM} algorith is not supported by the JVM
 * @throws InvalidKeyException if the given elliptic curve private key is invalid for any reason
 *///from  w w  w  .jav  a 2s.c o m
public ApnsVerificationKey(final String keyId, final String teamId, final ECPublicKey key)
        throws NoSuchAlgorithmException, InvalidKeyException {
    super(keyId, teamId, key);

    // This is a little goofy, but we want to check early for missing algorithms or bogus keys, and the most direct
    // way to do that is to try to actually use the key to create a signature.
    final Signature signature = Signature.getInstance(ApnsKey.APNS_SIGNATURE_ALGORITHM);
    signature.initVerify(key);
}

From source file:com.alvexcore.share.jscript.JSShareExtensionRegistry.java

@SuppressWarnings("serial")
public String removeSignature(String data) {
    if (data == null)
        return null;
    int idx = data.indexOf("\n");
    if (idx <= 20)
        return null;
    String s = data.substring(0, idx);
    if (!s.startsWith("SIGNATURE:"))
        return null;
    s = s.substring(10);//  ww  w  .  jav a  2s .c  o  m
    Signature sig;
    try {
        sig = Signature.getInstance("SHA1withRSA");
        sig.initVerify(new PublicKey() {

            @Override
            public String getAlgorithm() {
                return "RSA";
            }

            @Override
            public String getFormat() {
                return "X.509";
            }

            @Override
            public byte[] getEncoded() {
                return new byte[] { 48, -126, 1, 34, 48, 13, 6, 9, 42, -122, 72, -122, -9, 13, 1, 1, 1, 5, 0, 3,
                        -126, 1, 15, 0, 48, -126, 1, 10, 2, -126, 1, 1, 0, -115, 117, -12, -114, -121, -128, 76,
                        99, -114, -37, 107, -44, 108, 36, 38, 99, 13, -93, -73, -62, 44, 10, 120, -22, -31, -25,
                        -109, 45, 24, -47, 59, -87, -39, -29, -35, -96, 13, -117, 31, -98, 107, 80, -104, -72,
                        5, -32, 79, -115, 59, -87, 109, -121, 104, 36, -14, 123, -113, 87, -50, 40, -52, -59,
                        -52, -7, -13, -34, 17, -29, -39, 63, -62, -44, 51, 68, -98, -115, -13, 10, -7, -101, 81,
                        -72, 81, 91, -94, 91, -94, 6, 65, 84, 35, -121, 14, -103, 38, 6, 59, 115, -110, 4, -63,
                        -89, -22, 27, 126, -96, -32, 97, 105, -108, 14, -23, -62, -89, -41, 30, -126, -114, 121,
                        17, 125, 18, 124, -114, 0, -13, 85, -11, 92, 87, -16, 3, 30, 23, -126, -33, 122, 126,
                        -72, -95, 29, 73, -24, -34, -27, -41, 109, -77, -108, -34, 91, -36, -3, 112, 13, 30,
                        111, 9, -105, 7, 8, -70, 95, -128, -82, -13, -4, 127, -58, 68, -114, 89, 69, 101, -106,
                        -123, -36, -90, -110, -44, 45, 25, 107, 52, 6, 69, -35, 89, 7, -59, 96, 4, 97, 29, 24,
                        -50, -59, -40, 104, 70, 68, -28, 77, 94, -57, -38, 91, -99, 37, -89, 105, -126, 52, 80,
                        111, 107, -69, 22, 39, -70, -5, 87, -33, -77, -79, -64, 76, -12, -58, -37, 56, 102, 17,
                        59, 11, -73, -68, -96, -108, -47, 13, -113, -77, 60, 88, -128, 19, -42, 12, 49, 89, 7,
                        -11, -11, -87, 37, 2, 3, 1, 0, 1 };
            }
        });
        String d = data.substring(idx + 1);
        sig.update(d.getBytes());
        if (sig.verify(Base64.decodeBase64(s)))
            return d;
        else
            return null;
    } catch (Exception e) {
        return null;
    }
}

From source file:org.eclipse.licensing.base.LicenseKey.java

public boolean isAuthentic(PublicKey publicKey) {
    try {/*w ww  .  ja  va 2  s.  c o  m*/
        Signature signature = Signature.getInstance("SHA1withDSA", "SUN");
        signature.initVerify(publicKey);

        String[] propKeys = properties.keySet().toArray(new String[0]);
        Arrays.sort(propKeys);
        for (String propKey : propKeys) {
            if (!SIGNATURE.equals(propKey)) {
                String propValue = getProperty(propKey);
                signature.update(propValue.getBytes("UTF-8"));
            }
        }

        byte[] encodedSignature = getSignature();
        if (encodedSignature == null) {
            return false;
        }

        return signature.verify(getSignature());
    } catch (GeneralSecurityException | UnsupportedEncodingException e) {
        e.printStackTrace();
        return false;
    }
}

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 ww.jav  a 2 s  . 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 . j  a v a 2 s  . c om*/
    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
}

From source file:com.vmware.o11n.plugin.crypto.service.CryptoRSAService.java

/**
 * Verify a RSA Signature with a RSA Public Key
 *
 * @param pemKey RSA Key (Public or Private, Public will be derived from Private)
 * @param dataB64 Base64 encoded data the signature was created from
 * @param signatureB64 Base64 Encoded RSA Signature to verify
 * @return/*w  w w  .j  a v a  2  s.  c om*/
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws IOException
 * @throws InvalidKeyException
 * @throws SignatureException
 */
public boolean verifySignature(String pemKey, String dataB64, String signatureB64)
        throws NoSuchAlgorithmException, InvalidKeySpecException, IOException, InvalidKeyException,
        SignatureException {
    boolean valid = false;
    PublicKey publicKey = null;

    Key key = null;
    try {
        key = CryptoUtil.getKey(pemKey); //can be private or public
    } catch (IOException e) {
        //try to fix key:
        key = CryptoUtil.getKey(CryptoUtil.fixPemString(pemKey));
    }

    if (key instanceof RSAPublicKey) {
        publicKey = (RSAPublicKey) key;
    } else if (key instanceof RSAPrivateCrtKey) {
        RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) key;
        publicKey = CryptoUtil.getPublicFromPrivate(privateKey);
    } else {
        throw new IllegalArgumentException("Unknown key object type: " + key.getClass().getName());
    }

    Signature signer = Signature.getInstance(SIGNATURE_ALGORITHM);
    signer.initVerify(publicKey);
    signer.update(Base64.decodeBase64(dataB64));
    valid = signer.verify(Base64.decodeBase64(signatureB64));

    return valid;
}