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.kuzumeji.platform.standard.SecurityService.java

/**
 * ?/*from  www.j av a  2 s  . c  om*/
 * <dl>
 * <dt>?
 * <dd>SHA-512?RSA????????
 * </dl>
 * @param key ?
 * @param signature ??
 * @param plain 
 * @return ?
 */
public boolean verify(final PublicKey key, final byte[] signature, final byte[] plain) {
    try {
        final Signature verifier = Signature.getInstance(SIGN_ALGO_NAME);
        verifier.initVerify(key);
        verifier.update(plain);
        return verifier.verify(signature);
    } catch (final NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
        throw new RuntimeException(e);
    }
}

From source file:be.fedict.commons.eid.consumer.BeIDIntegrity.java

/**
 * Verifies a signature./* w  w  w  . ja  v  a 2s . c  om*/
 * 
 * @param signatureAlgo
 * @param signatureData
 * @param publicKey
 * @param data
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws SignatureException
 */
public boolean verifySignature(final String signatureAlgo, final byte[] signatureData,
        final PublicKey publicKey, final byte[]... data)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    Signature signature;
    signature = Signature.getInstance(signatureAlgo);
    signature.initVerify(publicKey);
    for (byte[] dataItem : data) {
        signature.update(dataItem);
    }
    final boolean result = signature.verify(signatureData);
    return result;
}

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

private void verifyServiceSignature(String serviceSigned, String target, String signatureRequest,
        String signatureRequestId, String signatureResponse, String signatureResponseId,
        String encodedSignatureCertificate, byte[] serviceSignatureValue,
        List<X509Certificate> serviceCertificateChain)
        throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {

    LOG.debug("verifying service signature");
    X509Certificate serviceCertificate = serviceCertificateChain.get(0);
    LOG.debug("service identity: " + serviceCertificate.getSubjectX500Principal());
    Signature serviceSignature = Signature.getInstance("SHA1withRSA");
    serviceSignature.initVerify(serviceCertificate);

    StringTokenizer serviceSignedStringTokenizer = new StringTokenizer(serviceSigned, ",");
    while (serviceSignedStringTokenizer.hasMoreTokens()) {
        String serviceSignedElement = serviceSignedStringTokenizer.nextToken();
        LOG.debug("service signed: " + serviceSignedElement);
        byte[] data;
        if ("target".equals(serviceSignedElement)) {
            data = target.getBytes();//from  w ww  .  ja  v  a 2s. c om
        } else if ("SignatureRequest".equals(serviceSignedElement)) {
            data = signatureRequest.getBytes();
        } else if ("SignatureRequestId".equals(serviceSignedElement)) {
            data = signatureRequestId.getBytes();
        } else if ("SignatureResponse".equals(serviceSignedElement)) {
            data = signatureResponse.getBytes();
        } else if ("SignatureResponseId".equals(serviceSignedElement)) {
            data = signatureResponseId.getBytes();
        } else if ("SignatureCertificate".equals(serviceSignedElement)) {
            data = encodedSignatureCertificate.getBytes();
        } else {
            throw new SecurityException("service signed unknown element: " + serviceSignedElement);
        }
        serviceSignature.update(data);
    }

    boolean valid = serviceSignature.verify(serviceSignatureValue);
    if (!valid) {
        throw new SecurityException("service signature not valid");
    }

    if (null != this.serviceFingerprint) {
        LOG.debug("checking service fingerprint");
        byte[] actualServiceFingerprint = DigestUtils.sha(serviceCertificate.getEncoded());
        if (!Arrays.equals(this.serviceFingerprint, actualServiceFingerprint)) {
            throw new SecurityException("service certificate fingerprint mismatch");
        }
    }
}

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

/**
 * tests signing and verifying./*  w ww.  j a v a 2s.  co m*/
 */
public void testSignAndVerify() throws Exception {
    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
    generator.initialize(1024);
    KeyPair keyPair = generator.generateKeyPair();
    String baseString = "thisismysignaturebasestringthatshouldbemuchlongerthanthisbutitdoesnthavetobeandherearesomestrangecharacters!@#$%^&*)(*";

    byte[] signatureBytes;
    {
        Signature signer = Signature.getInstance("SHA1withRSA");
        signer.initSign(keyPair.getPrivate());
        signer.update(baseString.getBytes("UTF-8"));
        signatureBytes = signer.sign();
    }

    {
        Signature signer = Signature.getInstance("SHA1withRSA");
        signer.initVerify(keyPair.getPublic());
        signer.update(baseString.getBytes("UTF-8"));
        assertTrue(signer.verify(signatureBytes));
    }

    RSA_SHA1SignatureMethod signatureMethod = new RSA_SHA1SignatureMethod(keyPair.getPrivate(),
            keyPair.getPublic());
    String signature = signatureMethod.sign(baseString);
    signatureMethod.verify(baseString, signature);
}

From source file:org.tolven.security.bean.DocProtectionBean.java

/**
 * Verify the document signature belongs to aPublicKey using aDecryptionKey
 * to decrypt the document//from   w ww . j  a v a  2s. c o m
 * @param aPublicKey
 * @param aDecryptionKey
 * @return
 */
public boolean verify(DocumentSignature documentSignature, X509Certificate x509Certificate,
        AccountUser activeAccountUser, PrivateKey userPrivateKey) {
    try {
        Signature signature = Signature.getInstance(documentSignature.getSignatureAlgorithm());
        signature.initVerify(x509Certificate.getPublicKey());
        byte[] document = getDecryptedContent(documentSignature.getDocBase(), activeAccountUser,
                userPrivateKey);
        signature.update(document);
        return signature.verify(documentSignature.getSignature());
    } catch (Exception ex) {
        throw new RuntimeException("Could not verify the signature", ex);
    }
}

From source file:mx.com.quadrum.service.util.firma.ValidacionesCertificado.java

/**
 * Mtodo que valida el password y que la llave privada corresponda a la
 * llave publica//w  w  w  . j  a va2 s .  c  om
 *
 * @return true si el password y llave privada corresponden, en otro caso
 * false
 */
public boolean validaCorrespondencias() {

    try {

        PKCS8Key pkcs8 = new PKCS8Key(this.clavePrivada, this.password.toCharArray());
        //valida el pass
        PrivateKey pk = pkcs8.getPrivateKey();
        //valida que la llave privada corresponda  a la llave publica
        X509Certificate cert = X509Certificate.getInstance(this.clavePublica);
        Signature firma = Signature.getInstance("SHA1withRSA");
        firma.initSign(pk);
        byte[] firmado = firma.sign();
        firma.initVerify(cert.getPublicKey());
        if (firma.verify(firmado)) {
            return this.correcto;
        } else {
            return this.error;
        }
    } catch (GeneralSecurityException e) {

        return this.error;
    } catch (CertificateException e) {

        return this.error;
    }
}

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

private void verifyServiceSignature(String serviceSigned, String target, String signatureRequest,
        String signatureRequestId, String contentType, String language, String relayState,
        byte[] serviceSignatureValue, List<X509Certificate> serviceCertificateChain)
        throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {

    LOG.debug("verifying service signature");
    X509Certificate serviceCertificate = serviceCertificateChain.get(0);
    LOG.debug("service identity: " + serviceCertificate.getSubjectX500Principal());
    Signature serviceSignature = Signature.getInstance("SHA1withRSA");
    serviceSignature.initVerify(serviceCertificate);

    StringTokenizer serviceSignedStringTokenizer = new StringTokenizer(serviceSigned, ",");
    while (serviceSignedStringTokenizer.hasMoreTokens()) {
        String serviceSignedElement = serviceSignedStringTokenizer.nextToken();
        LOG.debug("service signed: " + serviceSignedElement);
        byte[] data;
        if ("target".equals(serviceSignedElement)) {
            data = target.getBytes();/*w  w w. j  av  a2  s.  c  o  m*/
        } else if ("SignatureRequest".equals(serviceSignedElement)) {
            data = signatureRequest.getBytes();
        } else if ("SignatureRequestId".equals(serviceSignedElement)) {
            data = signatureRequestId.getBytes();
        } else if ("ContentType".equals(serviceSignedElement)) {
            data = contentType.getBytes();
        } else if ("language".equals(serviceSignedElement)) {
            data = language.getBytes();
        } else if ("RelayState".equals(serviceSignedElement)) {
            data = relayState.getBytes();
        } else {
            throw new SecurityException("service signed unknown element: " + serviceSignedElement);
        }
        serviceSignature.update(data);
    }

    boolean valid = serviceSignature.verify(serviceSignatureValue);
    if (!valid) {
        throw new SecurityException("service signature not valid");
    }
}

From source file:com.torresbueno.RSAEncryptionDecryptionUtil.java

public boolean verifySignWithMD5withRSA(byte[] data, byte[] signatureBytes, PublicKey publicKey)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    Signature sig = Signature.getInstance("MD5WithRSA");
    sig.initVerify(publicKey);
    sig.update(data);//  w  ww.  j  a va 2s.c o  m
    return sig.verify(signatureBytes);
}

From source file:com.torresbueno.RSAEncryptionDecryptionUtil.java

public boolean verifySignWithSHA1withRSA(byte[] data, byte[] signatureBytes, PublicKey publicKey)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initVerify(publicKey);
    sig.update(data);//from  w  ww  .j  a  v a2  s .  co m
    return sig.verify(signatureBytes);
}

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

public void verificar(InputStream in) throws Exception {
    String certStr = document.getCertificado();
    Base64 b64 = new Base64();
    byte[] cbs = b64.decode(certStr);

    X509Certificate cert = KeyLoaderFactory
            .createInstance(KeyLoaderEnumeration.PUBLIC_KEY_LOADER, new ByteArrayInputStream(cbs)).getKey();

    String sigStr = document.getSello();
    byte[] signature = b64.decode(sigStr);
    byte[] bytes = getOriginalBytes(in);
    Signature sig = Signature.getInstance("SHA256withRSA");
    sig.initVerify(cert);
    sig.update(bytes);//from  w ww  .  j  a  v a2  s. c o m
    boolean bool = sig.verify(signature);
    if (!bool) {
        throw new Exception("Invalid signature.");
    }
}