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:org.alfresco.extension.countersign.signature.RepositoryManagedSignatureProvider.java

@Override
public boolean validateSignature(byte[] sig, byte[] hash) {
    String alg = config.getProperty(RepositoryManagedSignatureProviderFactory.SIGNATURE_ALGORITHM);
    String prov = config.getProperty(RepositoryManagedSignatureProviderFactory.JAVA_SIGNATURE_PROVIDER);

    boolean valid = false;

    try {//  w w  w .  ja va  2 s .c o m
        Signature validate = Signature.getInstance(alg, prov);
        validate.initVerify(getPublicKey());
        validate.update(hash);
        valid = validate.verify(sig);
    } catch (NoSuchProviderException nspe) {
        throw new AlfrescoRuntimeException("Provider: " + prov + " was not found: " + nspe.getMessage());
    } catch (NoSuchAlgorithmException nsae) {
        throw new AlfrescoRuntimeException("Algorithm: " + alg + " is not available: " + nsae.getMessage());
    } catch (SignatureException se) {
        valid = false;
    } catch (InvalidKeyException ike) {
        valid = false;
    }

    return valid;
}

From source file:Networking.Client.java

public boolean SignatureVerification() {
    Signature sig = null;
    Boolean result = false;/* w ww.ja  v  a  2 s  .c  o  m*/
    try {
        X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(PubToVerify);
        KeyFactory keyFact = KeyFactory.getInstance("DSA", "SUN");
        PublicKey pubkeyToVerify = keyFact.generatePublic(pubKeySpec);
        confirmIdentity = checkAgainstRT(pubkeyToVerify.hashCode());
        sig = Signature.getInstance("SHA1withDSA", "SUN");
        sig.initVerify(pubkeyToVerify);

        byte[] g_pow_y_sign = this.node.getG_pow_y().toByteArray();
        byte[] g_pow_x_sign = this.node.getG_pow_x().toByteArray();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        outputStream.write(g_pow_x_sign);
        outputStream.write(g_pow_y_sign);
        byte[] c = outputStream.toByteArray();

        sig.update(c);
        result = (sig.verify(sigToVerify));
    } catch (SignatureException | InvalidKeyException | NoSuchAlgorithmException | NoSuchProviderException
            | InvalidKeySpecException | IOException ex) {
        Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result;
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testPSS256() throws Exception {
    Security.addProvider(new BeIDProvider());
    Security.addProvider(new BouncyCastleProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);//from w  ww  .  j av a  2 s .  c o  m
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");
    PublicKey authnPublicKey = authnCertificate.getPublicKey();

    Signature signature = Signature.getInstance("SHA256withRSAandMGF1");
    signature.initSign(authnPrivateKey);

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

    signature.initVerify(authnPublicKey);
    signature.update(toBeSigned);
    boolean result = signature.verify(signatureValue);
    assertTrue(result);
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testPSSPrefix() throws Exception {
    Security.addProvider(new BeIDProvider());
    Security.addProvider(new BouncyCastleProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);/*from  w w  w  . j  a v a 2  s .c  o  m*/
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");
    PublicKey authnPublicKey = authnCertificate.getPublicKey();

    Signature signature = Signature.getInstance("SHA1withRSAandMGF1");
    signature.initSign(authnPrivateKey);

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

    signature.initVerify(authnPublicKey);
    signature.update(toBeSigned);
    boolean result = signature.verify(signatureValue);
    assertTrue(result);

    RSAPublicKey rsaPublicKey = (RSAPublicKey) authnPublicKey;
    BigInteger signatureValueBigInteger = new BigInteger(signatureValue);
    BigInteger messageBigInteger = signatureValueBigInteger.modPow(rsaPublicKey.getPublicExponent(),
            rsaPublicKey.getModulus());
    String paddedMessage = new String(Hex.encodeHex(messageBigInteger.toByteArray()));
    LOG.debug("padded message: " + paddedMessage);
    assertTrue(paddedMessage.endsWith("bc"));
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

/**
 * Integration test for automatic recovery of a {@link PrivateKey} instance.
 * <p/>//from w ww  .ja  va 2s. c o  m
 * Automatic recovery should work on the same eID card.
 * <p/>
 * When inserting another eID card however, the automatic recovery should
 * fail.
 * 
 * @throws Exception
 */
@Test
public void testAutoRecovery() throws Exception {
    Security.addProvider(new BeIDProvider());

    KeyStore keyStore = KeyStore.getInstance("BeID");
    BeIDKeyStoreParameter keyStoreParameter = new BeIDKeyStoreParameter();
    keyStoreParameter.setAutoRecovery(true);
    keyStoreParameter.setCardReaderStickiness(true);
    keyStore.load(keyStoreParameter);

    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    PublicKey authnPublicKey = keyStore.getCertificate("Authentication").getPublicKey();
    final Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(authnPrivateKey);

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

    signature.initVerify(authnPublicKey);
    signature.update(toBeSigned);
    assertTrue(signature.verify(signatureValue));

    JOptionPane.showMessageDialog(null, "Please remove/insert eID card...");

    signature.initSign(authnPrivateKey);
    signature.update(toBeSigned);
    signatureValue = signature.sign();

    signature.initVerify(authnPublicKey);
    signature.update(toBeSigned);
    assertTrue(signature.verify(signatureValue));
}

From source file:org.ejbca.util.keystore.KeyTools.java

/** Testing a key pair to verify that it is possible to first sign and then verify with it.
 * /*from   w w w  .  j a v  a  2 s. c  o m*/
 * @param priv private key to sign a string with
 * @param pub public key to verify the signature with
 * @param provider A provider used for signing with the private key, or null if "BC" should be used.
 * 
 * @throws InvalidKeyException if the public key can not be used to verify a string signed by the private key, because the key is wrong or the signature operation fails for other reasons such as a NoSuchAlgorithmException or SignatureException.
 * @throws NoSuchProviderException if the provider is not installed.
 */
public static void testKey(final PrivateKey priv, final PublicKey pub, final String provider)
        throws InvalidKeyException, NoSuchProviderException {
    final byte input[] = "Lillan gick pa vagen ut, motte dar en katt...".getBytes();
    final byte signBV[];
    final String testSigAlg;
    {
        final Iterator<String> i = AlgorithmTools.getSignatureAlgorithms(pub).iterator();
        final String tmp = i.hasNext() ? i.next() : null;
        testSigAlg = tmp != null ? tmp : "SHA1WithRSA";
    }
    if (log.isDebugEnabled()) {
        log.debug("Testing keys with algorithm: " + pub.getAlgorithm());
        log.debug("testSigAlg: " + testSigAlg);
        log.debug("provider: " + provider);
        log.trace("privateKey: " + priv);
        log.trace("privateKey class: " + priv.getClass().getName());
        log.trace("publicKey: " + pub);
        log.trace("publicKey class: " + pub.getClass().getName());
    }
    try {
        {
            final Provider prov = Security.getProvider(provider != null ? provider : "BC");
            final Signature signature = Signature.getInstance(testSigAlg, prov);
            signature.initSign(priv);
            signature.update(input);
            signBV = signature.sign();
            if (signBV == null) {
                throw new InvalidKeyException("Result from signing is null.");
            }
            if (log.isDebugEnabled()) {
                log.trace("Created signature of size: " + signBV.length);
                log.trace("Created signature: " + new String(Hex.encode(signBV)));
            }
        }
        {
            final Signature signature = Signature.getInstance(testSigAlg, "BC");
            signature.initVerify(pub);
            signature.update(input);
            if (!signature.verify(signBV)) {
                throw new InvalidKeyException("Not possible to sign and then verify with key pair.");
            }
        }
    } catch (NoSuchAlgorithmException e) {
        throw new InvalidKeyException("Exception testing key: " + e.getMessage(), e);
    } catch (SignatureException e) {
        throw new InvalidKeyException("Exception testing key: " + e.getMessage(), e);
    }
}

From source file:com.tremolosecurity.idp.providers.Saml2Idp.java

private void procAuthnReq(HttpServletRequest request, HttpServletResponse response,
        DocumentBuilderFactory factory, String saml, String relayState) throws ParserConfigurationException,
        SAXException, IOException, UnmarshallingException, Exception, UnsupportedEncodingException,
        NoSuchAlgorithmException, InvalidKeyException, SignatureException, ServletException {
    AuthnRequestUnmarshaller marshaller = new AuthnRequestUnmarshaller();
    DocumentBuilder builder = factory.newDocumentBuilder();

    Element root = builder.parse(new InputSource(new StringReader(saml))).getDocumentElement();

    AuthnRequest authn = (AuthnRequest) marshaller.unmarshall(root);

    String issuer = authn.getIssuer().getValue();

    String authnCtx = null;/* w w w . j av a 2  s  .co m*/

    if (authn.getRequestedAuthnContext() == null
            || authn.getRequestedAuthnContext().getAuthnContextClassRefs().size() == 0
            || authn.getRequestedAuthnContext().getAuthnContextClassRefs().get(0)
                    .getAuthnContextClassRef() == null) {
        //no authnCtx information, use default
        authnCtx = null;
    } else {
        authnCtx = authn.getRequestedAuthnContext().getAuthnContextClassRefs().get(0).getAuthnContextClassRef();
    }

    String nameID = null;

    if (authn.getNameIDPolicy() == null) {
        nameID = null;
    } else {
        nameID = authn.getNameIDPolicy().getFormat();
    }

    String binding = authn.getProtocolBinding();
    String url = authn.getAssertionConsumerServiceURL();

    if (logger.isDebugEnabled()) {
        logger.debug("Issuer : '" + issuer + "'");
        logger.debug("Binding : '" + binding + "'");
        logger.debug("URL : '" + url + "'");

        logger.debug("NameID Format : '" + nameID + "'");
        logger.debug("Authn Class Ctx : '" + authnCtx + "'");
    }

    Saml2Trust trust = this.trusts.get(issuer);

    if (trust == null) {
        StringBuffer b = new StringBuffer();
        b.append("Could not find a trust for issuer '").append(issuer).append("'");
        throw new Exception(b.toString());
    }

    String authnSig = request.getParameter("Signature");
    if (authnSig != null) {
        String sigAlg = request.getParameter("SigAlg");
        StringBuffer query = new StringBuffer();
        query.append("SAMLRequest=").append(URLEncoder.encode(request.getParameter("SAMLRequest"), "UTF-8"));
        if (relayState != null) {
            query.append("&RelayState=").append(URLEncoder.encode(relayState, "UTF-8"));
        }
        query.append("&SigAlg=").append(URLEncoder.encode(sigAlg, "UTF-8"));

        String validationCert = trust.spSigCert;
        UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
        java.security.cert.X509Certificate cert = holder.getConfig().getCertificate(validationCert);

        if (!Saml2Idp.xmlDigSigAlgs.containsKey(sigAlg)) {
            throw new Exception("Invalid signature algorithm : " + sigAlg);
        }

        if (!authn.getDestination().equals(request.getRequestURL().toString())) {
            throw new Exception("Invalid destination");
        }

        Signature sigv = Signature.getInstance(Saml2Idp.javaDigSigAlgs.get(sigAlg));

        sigv.initVerify(cert.getPublicKey());
        sigv.update(query.toString().getBytes("UTF-8"));

        if (!sigv.verify(Base64.decodeBase64(authnSig.getBytes("UTF-8")))) {
            throw new Exception("Signature verification failed");
        }

    } else if (this.requireSignedAuthn) {
        throw new Exception("No signature on the authentication request");
    }

    doFederation(request, response, issuer, nameID, authnCtx, url, relayState, trust);
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testSwingParent2() throws Exception {
    Security.addProvider(new BeIDProvider());

    MyFrame myFrame = new MyFrame();

    final KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(myFrame);//from w  ww .j  av a2s  .  co m

    final PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    final Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(authnPrivateKey);

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

    Certificate[] certificateChain = keyStore.getCertificateChain("Authentication");
    signature.initVerify(certificateChain[0]);
    signature.update(toBeSigned);
    assertTrue(signature.verify(signatureValue));
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

private void verifySignatureAlgorithm(final String signatureAlgorithm, final PrivateKey privateKey,
        final PublicKey publicKey) throws Exception {
    Signature signature = Signature.getInstance(signatureAlgorithm);
    signature.initSign(privateKey);/* w ww .j  ava2s .c om*/
    assertTrue(signature.getProvider() instanceof BeIDProvider);

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

    signature.initVerify(publicKey);
    signature.update(toBeSigned);
    final boolean beIDResult = signature.verify(signatureValue);
    assertTrue(beIDResult);

    signature = Signature.getInstance(signatureAlgorithm);
    signature.initVerify(publicKey);
    signature.update(toBeSigned);
    final boolean result = signature.verify(signatureValue);
    assertTrue(result);

    RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
    BigInteger signatureValueBigInteger = new BigInteger(signatureValue);
    BigInteger messageBigInteger = signatureValueBigInteger.modPow(rsaPublicKey.getPublicExponent(),
            rsaPublicKey.getModulus());
    LOG.debug("Padded DigestInfo: " + new String(Hex.encodeHex(messageBigInteger.toByteArray())));
}

From source file:org.structr.util.StructrLicenseManager.java

private boolean verify(final byte[] data, final byte[] signatureData) {

    try {/* w  w  w  .j  a  v  a  2s  .c  o m*/

        final Signature verifier = Signature.getInstance(SignatureAlgorithm);

        verifier.initVerify(certificate);
        verifier.update(data);

        if (verifier.verify(signatureData)) {

            return true;
        }

    } catch (Throwable t) {
        logger.warn("Unable to verify volume license: {}", t.getMessage());
    }

    logger.error("License verification failed, license is not valid.");

    return false;
}