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.diorite.impl.auth.properties.PropertyImpl.java

@Override
public boolean isSignatureValid(final PublicKey publicKey) {
    try {//from   w  w w  . j ava  2  s  . co m
        final Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initVerify(publicKey);
        signature.update(this.value.getBytes());
        return signature.verify(Base64.decodeBase64(this.signature));
    } catch (final NoSuchAlgorithmException | SignatureException | InvalidKeyException e) {
        e.printStackTrace();
    }
    return false;
}

From source file:com.ss.license.LicenseManager.java

/**
 * license//from   w  ww .j  a v a 2  s  .co  m
 * Mac
 * 
 * 
 * @param license
 * @return
 * @throws Exception
 */
boolean validate(License license) throws Exception {
    String macAddress = license.getMacAddress();
    if (macAddress != null && macAddress.length() > 0) {
        String curMacAddress = "";
        if (!macAddress.equals(curMacAddress))
            return false;
    }
    String publicKey = FileHelper.readFile(new File(LicenseFactory.PUBLIC_KEY_FILE)).trim();

    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(EasyUtils.decodeHex(publicKey));
    KeyFactory keyFactory = KeyFactory.getInstance("DSA");
    java.security.PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

    Signature sig = Signature.getInstance("DSA");
    sig.initVerify(pubKey);
    sig.update(license.getFingerprint());
    return sig.verify(EasyUtils.decodeHex(license.getLicenseSignature()));
}

From source file:test.unit.be.fedict.hsm.entity.KeyStoreSingletonBeanTest.java

@Test
public void testSignature() throws Exception {
    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("test");
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();//from w ww.  j  a v a2 s  . com

    KeyStoreEntity keyStoreEntity = new KeyStoreEntity("test", KeyStoreType.PKCS12,
            KeyStoreSingletonBeanTest.class.getResource("/keystore.p12").toURI().getPath(), "secret");
    entityManager.persist(keyStoreEntity);

    KeyStoreSingletonBean keyStoreSingletonBean = new KeyStoreSingletonBean();

    Field entityManagerField = KeyStoreSingletonBean.class.getDeclaredField("entityManager");
    entityManagerField.setAccessible(true);
    entityManagerField.set(keyStoreSingletonBean, entityManager);

    KeyStoreLoaderBean keyStoreLoaderBean = new KeyStoreLoaderBean();
    Field keyStoreLoaderField = KeyStoreSingletonBean.class.getDeclaredField("keyStoreLoader");
    keyStoreLoaderField.setAccessible(true);
    keyStoreLoaderField.set(keyStoreSingletonBean, keyStoreLoaderBean);

    keyStoreSingletonBean.loadKeys();

    keyStoreSingletonBean.newKeyStore(keyStoreEntity.getId());

    byte[] toBeSigned = "hello world".getBytes();
    MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
    messageDigest.update(toBeSigned);
    byte[] digestValue = messageDigest.digest();
    LOG.debug("digest value: " + new String(Hex.encodeHex(digestValue)));
    byte[] signatureValue = keyStoreSingletonBean.sign(keyStoreEntity.getId(), "alias", "SHA-1", digestValue);

    assertNotNull(signatureValue);
    LOG.debug("signature size: " + signatureValue.length);

    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(KeyStoreSingletonBeanTest.class.getResourceAsStream("/keystore.p12"), "secret".toCharArray());
    RSAPublicKey publicKey = (RSAPublicKey) keyStore.getCertificate("alias").getPublicKey();

    BigInteger signatureValueBigInteger = new BigInteger(signatureValue);
    BigInteger originalBigInteger = signatureValueBigInteger.modPow(publicKey.getPublicExponent(),
            publicKey.getModulus());
    LOG.debug("original message: " + new String(Hex.encodeHex(originalBigInteger.toByteArray())));

    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initVerify(publicKey);
    signature.update(toBeSigned);
    boolean result = signature.verify(signatureValue);
    assertTrue(result);
}

From source file:com.ddubyat.develop.jhawtcode.util.PropertyUtil.java

private boolean validLicense(String email, String licenseCode) throws Exception {

    Resource res = applicationContext.getResource("classpath:jhc-public.der");
    InputStream is = res.getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    byte[] buffer = new byte[4096];
    byte[] pkey;//from   w ww.  j a v a  2 s.  c  o m
    int stream;
    while ((stream = is.read(buffer, 0, buffer.length)) != -1) {
        baos.write(buffer, 0, stream);
    }

    pkey = baos.toByteArray();

    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pkey);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PublicKey mypk = keyFactory.generatePublic(keySpec);

    Signature instance = Signature.getInstance("SHA1withRSA");
    instance.initVerify(mypk);
    instance.update(email.getBytes());

    //BASE64Decoder decoder = new BASE64Decoder();
    //byte[] decodedBytes = decoder.decodeBuffer(licenseCode);

    return instance.verify(DatatypeConverter.parseBase64Binary(licenseCode));
}

From source file:com.vmware.identity.sts.auth.impl.UserCertAuthenticator.java

private boolean verifyUserCertSignature(X509Certificate x509Certificate, String signedInfo,
        byte[] signatureValue) {

    try {/*from   w  ww.j a va  2s .  c om*/
        PublicKey publicKey = x509Certificate.getPublicKey();
        Signature signature = Signature.getInstance("SHA256WithRSA");
        signature.initVerify(publicKey);
        signature.update(signedInfo.getBytes());
        return signature.verify(signatureValue);
    } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
        throw new InvalidCredentialsException("User certificate token signature validation failed.", e);
    }
}

From source file:org.orbeon.oxf.processor.SignatureVerifierProcessor.java

public ProcessorOutput createOutput(String name) {
    final ProcessorOutput output = new ProcessorOutputImpl(SignatureVerifierProcessor.this, name) {
        public void readImpl(PipelineContext context, final XMLReceiver xmlReceiver) {
            try {
                final Document pubDoc = readCacheInputAsDOM4J(context, INPUT_PUBLIC_KEY);
                final String pubString = XPathUtils.selectStringValueNormalize(pubDoc, "/public-key");
                final byte[] pubBytes = Base64.decode(pubString);
                final X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubBytes);
                final KeyFactory keyFactory = KeyFactory.getInstance("DSA");
                final PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

                final Signature dsa = Signature.getInstance("SHA1withDSA");
                dsa.initVerify(pubKey);

                final Document data = readInputAsDOM4J(context, INPUT_DATA);
                final Node sigDataNode = data.selectSingleNode("/signed-data/data/*");
                final String sig = StringUtils
                        .trimToEmpty(XPathUtils.selectStringValue(data, "/signed-data/signature"));

                sigDataNode.detach();//from  w  ww.j  a  v a 2  s.  c o  m
                final Document sigData = new NonLazyUserDataDocument();
                sigData.add(sigDataNode);

                dsa.update(Dom4jUtils.domToString(sigData).getBytes("utf-8"));

                // Verify signature and throw in case of failure
                try {
                    if (!dsa.verify(Base64.decode(sig)))
                        throw new OXFException("Signature verification failed");
                } catch (SignatureException e) {
                    throw e;
                } catch (Exception e) {
                    // A number of things can fail above, including Base64 decoding
                    // NOTE: We don't pas the cause so that we can match on SignatureException as root Exception
                    throw new SignatureException("Signature verification failed");
                }

                // Signature verification passed
                final LocationSAXWriter saw = new LocationSAXWriter();
                saw.setContentHandler(xmlReceiver);
                saw.write(sigData);
            } catch (Exception e) {
                throw new OXFException(e);
            }
        }
    };
    addOutput(name, output);
    return output;
}

From source file:org.codice.ddf.commands.util.DigitalSignature.java

public boolean verifyDigitalSignature(InputStream data, InputStream signature, String certificateAlias)
        throws IOException {
    byte[] sigToVerify = IOUtils.toByteArray(signature);

    Certificate certificate = getCertificate(certificateAlias);

    if (certificate == null) {
        throw new CatalogCommandRuntimeException("Unable to retrieve certificate");
    }//w  w  w. j  a  va2  s  .  c o  m

    try {
        Signature rsa = Signature.getInstance("SHA256withRSA");
        rsa.initVerify(certificate);

        byte[] buffer = new byte[BUFFER_SIZE];
        int len;

        while ((len = data.read(buffer)) >= 0) {
            rsa.update(buffer, OFFSET, len);
        }

        return rsa.verify(sigToVerify);
    } catch (InvalidKeyException | SignatureException | NoSuchAlgorithmException e) {
        String message = "An error occurred while verifying file";
        LOGGER.debug(message, e);
        throw new CatalogCommandRuntimeException(message, e);
    }
}

From source file:se.curity.examples.oauth.jwt.AbstractJwtValidator.java

protected boolean validateSignature(byte[] signingInput, byte[] signature, PublicKey publicKey) {
    try {/*from   w  w w  . ja  v a 2  s.c o  m*/
        Signature verifier = Signature.getInstance("SHA256withRSA");
        verifier.initVerify(publicKey);
        verifier.update(signingInput);
        return verifier.verify(signature);
    } catch (Exception e) {
        throw new RuntimeException("Unable to validate JWT signature", e);
    }
}

From source file:com.yazino.web.payment.googlecheckout.AndroidInAppOrderSecurity.java

/**
 * Verifies that the signature from google play matches the computed signature on {@code orderData}.
 * Returns true if the data is correctly signed.
 *
 * @param gameType  gameType purchases were made from, required to enable retrieval of correct public key
 * @param orderData signed order data from Google Play to verify
 * @param signature signature of {@code orderData} from Google Play
 * @param partnerId/*w w  w. j  ava  2  s  .  c o m*/
 * @return true if the data and signature match
 */
public boolean verify(String gameType, String orderData, String signature, final Partner partnerId) {
    LOG.debug("verifying gametype:{}, orderData:{}, signature:{}, partner:{}");
    validateArgs(gameType, orderData, signature);

    LOG.debug("verifying orderData {} for gameType {} against signature {}", orderData, gameType, signature);

    PublicKey publicKey = generatePublicKey(gameType, partnerId);

    Signature sig;
    try {
        sig = Signature.getInstance(SIGNATURE_ALGORITHM);
        sig.initVerify(publicKey);
        sig.update(orderData.getBytes());
        if (!sig.verify(Base64.decode(signature.getBytes()))) {
            return false;
        }
        return true;
    } catch (Exception e) {
        LOG.error("Signature is invalid. orderData {}, gameType {}, signature {}, partnerId {}", orderData,
                gameType, signature, partnerId, e);
    }
    return false;
}

From source file:com.boubei.tss.modules.license.LicenseManager.java

/**
 * <pre>/* w  w  w  . j av  a  2 s  .co  m*/
 * ?license????????
 * </pre>
 * @param license
 * @return
 * @throws Exception
 */
boolean validate(License license) throws Exception {
    File keyFile = new File(LicenseFactory.PUBLIC_KEY_FILE);
    String publicKey = FileHelper.readFile(keyFile).trim();

    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(EasyUtils.decodeHex(publicKey));
    KeyFactory keyFactory = KeyFactory.getInstance(LicenseFactory.KEY_ALGORITHM);
    java.security.PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

    Signature sig = Signature.getInstance(LicenseFactory.KEY_ALGORITHM);
    sig.initVerify(pubKey);
    sig.update(license.getFingerprint());
    return sig.verify(EasyUtils.decodeHex(license.signature));
}