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.example.android.basicandroidkeystore.BasicAndroidKeyStoreFragment.java

/**
 * Given some data and a signature, uses the key pair stored in the Android Key Store to verify
 * that the data was signed by this application, using that key pair.
 * @param input The data to be verified.
 * @param signatureStr The signature provided for the data.
 * @return A boolean value telling you whether the signature is valid or not.
 *///  www .  j a  v a2 s .c  o  m
public boolean verifyData(String input, String signatureStr)
        throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException,
        UnrecoverableEntryException, InvalidKeyException, SignatureException {
    byte[] data = input.getBytes();
    byte[] signature;
    // BEGIN_INCLUDE(decode_signature)

    // Make sure the signature string exists.  If not, bail out, nothing to do.

    if (signatureStr == null) {
        Log.w(TAG, "Invalid signature.");
        Log.w(TAG, "Exiting verifyData()...");
        return false;
    }

    try {
        // The signature is going to be examined as a byte array,
        // not as a base64 encoded string.
        signature = Base64.decode(signatureStr, Base64.DEFAULT);
    } catch (IllegalArgumentException e) {
        // signatureStr wasn't null, but might not have been encoded properly.
        // It's not a valid Base64 string.
        return false;
    }
    // END_INCLUDE(decode_signature)

    KeyStore ks = KeyStore.getInstance("AndroidKeyStore");

    // Weird artifact of Java API.  If you don't have an InputStream to load, you still need
    // to call "load", or it'll crash.
    ks.load(null);

    // Load the key pair from the Android Key Store
    KeyStore.Entry entry = ks.getEntry(mAlias, null);

    if (entry == null) {
        Log.w(TAG, "No key found under alias: " + mAlias);
        Log.w(TAG, "Exiting verifyData()...");
        return false;
    }

    if (!(entry instanceof KeyStore.PrivateKeyEntry)) {
        Log.w(TAG, "Not an instance of a PrivateKeyEntry");
        return false;
    }

    // This class doesn't actually represent the signature,
    // just the engine for creating/verifying signatures, using
    // the specified algorithm.
    Signature s = Signature.getInstance(SecurityConstants.SIGNATURE_SHA256withRSA);

    // BEGIN_INCLUDE(verify_data)
    // Verify the data.
    s.initVerify(((KeyStore.PrivateKeyEntry) entry).getCertificate());
    s.update(data);
    return s.verify(signature);
    // END_INCLUDE(verify_data)
}

From source file:org.pepstock.jem.node.https.SubmitHandler.java

@Override
public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws HttpException, IOException {
    // extracts the host
    String host = context.getAttribute(JOB_SUBMIT_IP_ADDRESS_KEY).toString();
    // gets HTTP method (uses locale ENGLISH to be sure to have POST)
    String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    // if NOT post, exception!
    if (!method.equals(POST)) {
        LogAppl.getInstance().emit(NodeMessage.JEMC284W, method, host);
        throw new MethodNotSupportedException(
                NodeMessage.JEMC284W.toMessage().getFormattedMessage(method, host));
    }//from w  w  w.  j  av a  2 s  .  c  o  m
    // gets the URI or the request
    String target = request.getRequestLine().getUri();
    // if is not the same , accepts, exception!
    if (!target.equalsIgnoreCase(DEFAULT_ACTION)) {
        LogAppl.getInstance().emit(NodeMessage.JEMC285W, target, host);
        throw new MethodNotSupportedException(
                NodeMessage.JEMC285W.toMessage().getFormattedMessage(target, host));
    }
    // checks the HTTP request
    if (request instanceof HttpEntityEnclosingRequest) {
        // gets the entity of the request
        HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
        // gets the body in string format
        String result = EntityUtils.toString(entity, CharSet.DEFAULT);
        // reads the first line,
        // with all URL encoded variables  
        String vars = StringUtils.substringBefore(result, DELIMITER);
        // loads a map with all parms
        Map<String, String> parms = loadParametersMap(URLEncodedUtils.parse(vars, CharSet.DEFAULT));
        // gets the USER
        String user = parms.get(SubmitParameters.USER.getName());
        // if JEM is configured to have the Socket Interceptor on HC
        // the client MUST provide a SIGNATURE (using own private key) with
        // the user crypted inside
        if (Main.getHazelcastConfig().getNetworkConfig().getSocketInterceptorConfig().isEnabled()) {
            // checks if there is the signature
            if (parms.containsKey(USER_SIGNATURE_KEY)) {
                // gets the signature in HEX format
                String cryptedUserString = parms.get(USER_SIGNATURE_KEY);
                // gets keys stores
                KeyStoresInfo keyStoresInfo = KeyStoreUtil.getKeyStoresInfo();
                try {
                    // extracts from the USER key store the PUBLIC KEY (upload by UI) for the user  
                    PublicKey publicKey = KeysUtil.getPublicKeyByAlias(keyStoresInfo.getUserKeystoreInfo(),
                            user);
                    // creates tne SIGNATURE verifying steps
                    Signature signature = Signature.getInstance("SHA256withRSA");
                    // sets public key
                    signature.initVerify(publicKey);
                    // sets content to check. It uses USER
                    signature.update(user.getBytes(CharSet.DEFAULT_CHARSET_NAME));
                    // checks if is verified
                    if (!signature.verify(Hex.decodeHex(cryptedUserString.toCharArray()))) {
                        // if not, log and EXCEPTION
                        LogAppl.getInstance().emit(NodeMessage.JEMC286W, user, host);
                        throw new HttpException(
                                NodeMessage.JEMC286W.toMessage().getFormattedMessage(user, host));
                    }
                } catch (MessageException e) {
                    LogAppl.getInstance().emit(NodeMessage.JEMC286W, user, host);
                    throw new ProtocolException(e.getMessage(), e);
                } catch (KeyException e) {
                    throw new ProtocolException(e.getMessage(), e);
                } catch (DecoderException e) {
                    throw new ProtocolException(e.getMessage(), e);
                } catch (NoSuchAlgorithmException e) {
                    throw new ProtocolException(e.getMessage(), e);
                } catch (SignatureException e) {
                    throw new ProtocolException(e.getMessage(), e);
                }
            } else {
                LogAppl.getInstance().emit(NodeMessage.JEMC287W, user, host);
                // if here, the signature is missing
                throw new HttpException(NodeMessage.JEMC287W.toMessage().getFormattedMessage(user, host));
            }
        }
        // gets JEM environemnt name and its passwrod
        String env = parms.get(SubmitParameters.ENV.getName());
        String password = parms.get(SubmitParameters.PASSWORD.getName());
        // checks if password and env are same, 
        // comparing with the HC configuration
        if (!Main.getHazelcastConfig().getGroupConfig().getName().equalsIgnoreCase(env)
                || !Main.getHazelcastConfig().getGroupConfig().getPassword().equalsIgnoreCase(password)) {
            // if not equals, exception
            LogAppl.getInstance().emit(NodeMessage.JEMC288W, host);
            throw new HttpException(NodeMessage.JEMC288W.toMessage().getFormattedMessage(host));
        }

        // reads teh second row of the body, with the JCL
        String jcl = StringUtils.substringAfter(result, DELIMITER);

        // sets the entity to send back, submitting the job.
        // it returns the JOBID
        StringEntity resultEntity = new StringEntity(submit(jcl, user, host, parms),
                ContentType.create(RESPONSE_MIME_TYPE, CharSet.DEFAULT_CHARSET_NAME));
        // sets STATUS code and entity 
        response.setStatusCode(HttpStatus.SC_OK);
        response.setEntity(resultEntity);
    } else {
        // if here, the request is not correct
        LogAppl.getInstance().emit(NodeMessage.JEMC284W, method, host);
        throw new MethodNotSupportedException(
                NodeMessage.JEMC284W.toMessage().getFormattedMessage(method, host));
    }
}

From source file:test.be.fedict.eid.applet.SecurePinPadReaderTest.java

/**
 * When creating a non-repudiation signature using PKCS#1-SHA1 (non-naked)
 * the digest value should also be confirmed via the secure pinpad reader.
 * //from ww w. java2s  . c  o  m
 * @throws Exception
 */
@Test
@QualityAssurance(firmware = Firmware.V015Z, approved = true)
public void testNonRepSignPKCS1_SHA1() throws Exception {
    CardChannel cardChannel = this.pcscEid.getCardChannel();

    List<X509Certificate> signCertChain = this.pcscEid.getSignCertificateChain();

    CommandAPDU setApdu = new CommandAPDU(0x00, 0x22, 0x41, 0xB6, new byte[] { 0x04, // length of following data
            (byte) 0x80, // algo ref
            0x02, // RSA PKCS#1 SHA1
            (byte) 0x84, // tag for private key ref
            (byte) 0x83 }); // non-rep key
    ResponseAPDU responseApdu = cardChannel.transmit(setApdu);
    assertEquals(0x9000, responseApdu.getSW());

    this.pcscEid.verifyPin();

    byte[] data = "My Testcase".getBytes();
    MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
    byte[] digestValue = messageDigest.digest(data);

    CommandAPDU computeDigitalSignatureApdu = new CommandAPDU(0x00, 0x2A, 0x9E, 0x9A, digestValue);

    responseApdu = cardChannel.transmit(computeDigitalSignatureApdu);
    assertEquals(0x9000, responseApdu.getSW());
    byte[] signatureValue = responseApdu.getData();
    LOG.debug("signature value size: " + signatureValue.length);

    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initVerify(signCertChain.get(0).getPublicKey());
    signature.update(data);
    boolean result = signature.verify(signatureValue);
    assertTrue(result);
}

From source file:com.amazonaws.ipnreturnurlvalidation.SignatureUtilsForOutbound.java

/**
 * Verifies the signature using PKI./*from  w ww  .  ja  v a 2s .  c  om*/
 */
private boolean validateSignatureV2(Map<String, String> parameters, String urlEndPoint, String httpMethod)
        throws SignatureException {

    // 1. input validation.
    String signature = parameters.get(SIGNATURE_KEYNAME);
    if (signature == null) {
        throw new SignatureException("'signature' is missing from the parameters.");
    }

    String signatureMethod = parameters.get(SIGNATURE_METHOD_KEYNAME);
    if (signatureMethod == null) {
        throw new SignatureException("'signatureMethod' is missing from the parameters.");
    }

    String signatureAlgorithm = getSignatureAlgorithm(signatureMethod);
    if (signatureAlgorithm == null) {
        throw new SignatureException("'signatureMethod' present in parameters is invalid. "
                + "Valid signatureMethods are : 'RSA-SHA1'");
    }

    String certificateUrl = parameters.get(CERTIFICATE_URL_KEYNAME);
    if (certificateUrl == null) {
        throw new SignatureException("'certificateUrl' is missing from the parameters.");
    }

    String certificate = getPublicKeyCertificateAsString(certificateUrl);
    if (certificate == null) {
        throw new SignatureException("public key certificate could not fetched from url: " + certificateUrl);
    }

    // 2. calculating the string to sign
    String stringToSign = EMPTY_STRING;
    try {
        URL url = new URL(urlEndPoint);
        String hostHeader = getHostHeader(url);
        String requestURI = getRequestURI(url);
        stringToSign = calculateStringToSignV2(parameters, httpMethod, hostHeader, requestURI);
    } catch (MalformedURLException e) {
        throw new SignatureException(e);
    }

    // 3. verify signature
    try {
        CertificateFactory factory = CertificateFactory.getInstance("X.509");
        X509Certificate x509Certificate = (X509Certificate) factory
                .generateCertificate(new ByteArrayInputStream(certificate.getBytes()));
        Signature signatureInstance = Signature.getInstance(signatureAlgorithm);
        signatureInstance.initVerify(x509Certificate.getPublicKey());
        signatureInstance.update(stringToSign.getBytes(UTF_8_Encoding));
        return signatureInstance.verify(Base64.decodeBase64(signature.getBytes()));
    } catch (CertificateException e) {
        throw new SignatureException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new SignatureException(e);
    } catch (InvalidKeyException e) {
        throw new SignatureException(e);
    } catch (UnsupportedEncodingException e) {
        throw new SignatureException(e);
    }
}

From source file:org.intermine.webservice.server.JWTVerifier.java

private boolean verifySignature(PublicKey key, String algorithm, String signed, byte[] toVerify)
        throws VerificationError {
    Signature signature;
    try {/*from w w w.  j  ava 2s.  c o  m*/
        signature = Signature.getInstance(algorithm);
    } catch (NoSuchAlgorithmException e) {
        throw new VerificationError(e.getMessage());
    }
    try {
        signature.initVerify(key);
    } catch (InvalidKeyException e) {
        throw new VerificationError("Key is invalid. " + e.getMessage());
    }

    try {
        signature.update(signed.getBytes());
    } catch (SignatureException e) {
        throw new VerificationError("Error creating signature: " + e.getMessage());
    }

    try {
        return signature.verify(toVerify);
    } catch (SignatureException e) {
        throw new VerificationError("Error during verification: " + e.getMessage());
    }
}

From source file:com.blackducksoftware.integration.hub.jenkins.site.BlackDuckHubUpdateSite.java

/**
 * Verifies the signature in the update center data file.
 *//*from w  w w. j  av a  2 s  .  c  o  m*/
private FormValidation verifySignature(final JSONObject o) throws IOException {
    try {
        FormValidation warning = null;

        final JSONObject signature = o.getJSONObject("signature");
        if (signature.isNullObject()) {
            return FormValidation.error("No signature block found in update center '" + getId() + "'");
        }
        o.remove("signature");

        final List<X509Certificate> certs = new ArrayList<X509Certificate>();
        {// load and verify certificates
            final CertificateFactory cf = CertificateFactory.getInstance("X509");
            for (final Object cert : signature.getJSONArray("certificates")) {
                final X509Certificate c = (X509Certificate) cf.generateCertificate(
                        new ByteArrayInputStream(Base64.decode(cert.toString().toCharArray())));
                try {
                    c.checkValidity();
                } catch (final CertificateExpiredException e) { // even if the certificate isn't valid yet,
                    // we'll proceed it anyway
                    warning = FormValidation.warning(e, String.format(
                            "Certificate %s has expired in update center '%s'", cert.toString(), getId()));
                } catch (final CertificateNotYetValidException e) {
                    warning = FormValidation.warning(e, String.format(
                            "Certificate %s is not yet valid in update center '%s'", cert.toString(), getId()));
                }
                certs.add(c);
            }

            // all default root CAs in JVM are trusted, plus certs bundled in Jenkins
            final Set<TrustAnchor> anchors = new HashSet<TrustAnchor>(); // CertificateUtil.getDefaultRootCAs();
            final ServletContext context = Jenkins.getInstance().servletContext;
            anchors.add(new TrustAnchor(loadLicenseCaCertificate(), null));
            for (final String cert : (Set<String>) context.getResourcePaths("/WEB-INF/update-center-rootCAs")) {
                if (cert.endsWith(".txt")) {
                    continue; // skip text files that are meant to be documentation
                }
                final InputStream stream = context.getResourceAsStream(cert);
                if (stream != null) {
                    try {
                        anchors.add(new TrustAnchor((X509Certificate) cf.generateCertificate(stream), null));
                    } finally {
                        IOUtils.closeQuietly(stream);
                    }
                }
            }
            CertificateUtil.validatePath(certs, anchors);
        }

        // this is for computing a digest to check sanity
        final MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        final DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(), sha1);

        // this is for computing a signature
        final Signature sig = Signature.getInstance("SHA1withRSA");
        sig.initVerify(certs.get(0));
        final SignatureOutputStream sos = new SignatureOutputStream(sig);

        // until JENKINS-11110 fix, UC used to serve invalid digest (and therefore unverifiable signature)
        // that only covers the earlier portion of the file. This was caused by the lack of close() call
        // in the canonical writing, which apparently leave some bytes somewhere that's not flushed to
        // the digest output stream. This affects Jenkins [1.424,1,431].
        // Jenkins 1.432 shipped with the "fix" (1eb0c64abb3794edce29cbb1de50c93fa03a8229) that made it
        // compute the correct digest, but it breaks all the existing UC json metadata out there. We then
        // quickly discovered ourselves in the catch-22 situation. If we generate UC with the correct signature,
        // it'll cut off [1.424,1.431] from the UC. But if we don't, we'll cut off [1.432,*).
        //
        // In 1.433, we revisited 1eb0c64abb3794edce29cbb1de50c93fa03a8229 so that the original "digest"/"signature"
        // pair continues to be generated in a buggy form, while "correct_digest"/"correct_signature" are generated
        // correctly.
        //
        // Jenkins should ignore "digest"/"signature" pair. Accepting it creates a vulnerability that allows
        // the attacker to inject a fragment at the end of the json.
        o.writeCanonical(new OutputStreamWriter(new TeeOutputStream(dos, sos), "UTF-8")).close();

        // did the digest match? this is not a part of the signature validation, but if we have a bug in the c14n
        // (which is more likely than someone tampering with update center), we can tell
        final String computedDigest = new String(Base64.encode(sha1.digest()));
        final String providedDigest = signature.optString("correct_digest");
        if (providedDigest == null) {
            return FormValidation.error("No correct_digest parameter in update center '" + getId()
                    + "'. This metadata appears to be old.");
        }
        if (!computedDigest.equalsIgnoreCase(providedDigest)) {
            return FormValidation.error("Digest mismatch: " + computedDigest + " vs " + providedDigest
                    + " in update center '" + getId() + "'");
        }

        final String providedSignature = signature.getString("correct_signature");
        if (!sig.verify(Base64.decode(providedSignature.toCharArray()))) {
            return FormValidation.error(
                    "Signature in the update center doesn't match with the certificate in update center '"
                            + getId() + "'");
        }

        if (warning != null) {
            return warning;
        }
        return FormValidation.ok();
    } catch (final GeneralSecurityException e) {
        return FormValidation.error(e, "Signature verification failed in the update center '" + getId() + "'");
    }
}

From source file:org.xdi.oxauth.model.crypto.OxAuthCryptoProvider.java

@Override
public boolean verifySignature(String signingInput, String encodedSignature, String alias, JSONObject jwks,
        String sharedSecret, SignatureAlgorithm signatureAlgorithm) throws Exception {
    boolean verified = false;

    if (signatureAlgorithm == SignatureAlgorithm.NONE) {
        return Util.isNullOrEmpty(encodedSignature);
    } else if (SignatureAlgorithmFamily.HMAC.equals(signatureAlgorithm.getFamily())) {
        String expectedSignature = sign(signingInput, null, sharedSecret, signatureAlgorithm);
        return expectedSignature.equals(encodedSignature);
    } else { // EC or RSA
        PublicKey publicKey = null;

        try {/*from ww  w  .j a va 2 s . c  o  m*/
            if (jwks == null) {
                publicKey = getPublicKey(alias);
            } else {
                publicKey = getPublicKey(alias, jwks);
            }
            if (publicKey == null) {
                return false;
            }

            byte[] signature = Base64Util.base64urldecode(encodedSignature);

            Signature verifier = Signature.getInstance(signatureAlgorithm.getAlgorithm(), "BC");
            //Signature verifier = Signature.getInstance(signatureAlgorithm.getAlgorithm());
            verifier.initVerify(publicKey);
            verifier.update(signingInput.getBytes());
            verified = verifier.verify(signature);
        } catch (NoSuchAlgorithmException e) {
            LOG.error(e.getMessage(), e);
            verified = false;
        } catch (SignatureException e) {
            LOG.error(e.getMessage(), e);
            verified = false;
        } catch (InvalidKeyException e) {
            LOG.error(e.getMessage(), e);
            verified = false;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            verified = false;
        }
    }

    return verified;
}

From source file:be.fedict.eid.applet.service.impl.handler.SignCertificatesDataMessageHandler.java

private void verifySignature(String signatureAlgoName, byte[] signatureData, PublicKey publicKey,
        HttpServletRequest request, byte[]... data) throws ServletException {
    Signature signature;
    try {/* w w  w.  ja  v a  2s.c o  m*/
        signature = Signature.getInstance(signatureAlgoName);
    } catch (NoSuchAlgorithmException e) {
        throw new ServletException("algo error: " + e.getMessage(), e);
    }
    try {
        signature.initVerify(publicKey);
    } catch (InvalidKeyException e) {
        throw new ServletException("key error: " + e.getMessage(), e);
    }
    try {
        for (byte[] dataItem : data) {
            signature.update(dataItem);
        }
        boolean result = signature.verify(signatureData);
        if (false == result) {
            AuditService auditService = this.auditServiceLocator.locateService();
            if (null != auditService) {
                String remoteAddress = request.getRemoteAddr();
                auditService.identityIntegrityError(remoteAddress);
            }
            throw new ServletException("signature incorrect");
        }
    } catch (SignatureException e) {
        throw new ServletException("signature error: " + e.getMessage(), e);
    }
}

From source file:test.integ.be.fedict.hsm.jca.HSMProxySignatureTest.java

private void signAndVerify(X509Certificate certificate, PrivateKey privateKey, String signatureAlgo)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    Signature signature = Signature.getInstance(signatureAlgo);
    signature.initSign(privateKey);//from  w  ww . java  2 s  .  c om

    byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();

    assertNotNull(signatureValue);

    signature = Signature.getInstance(signatureAlgo);
    signature.initVerify(certificate.getPublicKey());
    signature.update(toBeSigned);
    assertTrue(signature.verify(signatureValue));
}

From source file:be.e_contract.eid.applet.service.impl.handler.IdentityDataMessageHandler.java

private void verifySignature(BeIDContextQualifier contextQualifier, String signAlgo, byte[] signatureData,
        X509Certificate certificate, HttpServletRequest request, byte[]... data) throws ServletException {
    Signature signature;
    try {/*from   w  w  w  .j a  v  a 2  s. c  o  m*/
        signature = Signature.getInstance(signAlgo);
    } catch (NoSuchAlgorithmException e) {
        throw new ServletException("algo error: " + e.getMessage(), e);
    }
    PublicKey publicKey = certificate.getPublicKey();
    try {
        signature.initVerify(publicKey);
    } catch (InvalidKeyException e) {
        throw new ServletException("key error: " + e.getMessage(), e);
    }
    try {
        for (byte[] dataItem : data) {
            signature.update(dataItem);
        }
        boolean result = signature.verify(signatureData);
        if (false == result) {
            SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.DATA_INTEGRITY, certificate,
                    signatureData);
            this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent);
            throw new ServletException("signature incorrect");
        }
    } catch (SignatureException e) {
        SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.DATA_INTEGRITY, certificate,
                signatureData);
        this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent);
        throw new ServletException("signature error: " + e.getMessage(), e);
    }
}