Example usage for java.security Signature update

List of usage examples for java.security Signature update

Introduction

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

Prototype

public final void update(ByteBuffer data) throws SignatureException 

Source Link

Document

Updates the data to be signed or verified using the specified ByteBuffer.

Usage

From source file:com.vmware.identity.SharedUtils.java

/**
 * Produce a string with signature//from  w  w w .  j  a v  a  2  s .  c  o  m
 *
 * @param privateKey
 * @param relayStateParameter
 * @param samlRequestParameter
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws UnsupportedEncodingException
 * @throws SignatureException
 */
public static String getSamlRequestSignature(PrivateKey privateKey, String relayStateParameter,
        String samlRequestParameter)
        throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, SignatureException {
    // produce signature
    SignatureAlgorithm algo = SignatureAlgorithm.getSignatureAlgorithmForURI(TestConstants.SIGNATURE_ALGORITHM);
    Signature sig = Signature.getInstance(algo.getAlgorithmName());
    sig.initSign(privateKey);

    String messageToSign = Shared.SAML_REQUEST_PARAMETER + "="
            + URLEncoder.encode(samlRequestParameter, "UTF-8") + "&" + Shared.RELAY_STATE_PARAMETER + "="
            + URLEncoder.encode(relayStateParameter, "UTF-8") + "&" + Shared.SIGNATURE_ALGORITHM_PARAMETER + "="
            + URLEncoder.encode(algo.toString(), "UTF-8");

    byte[] messageBytes = messageToSign.getBytes();
    sig.update(messageBytes);

    byte[] sigBytes = sig.sign();
    String signature = Shared.encodeBytes(sigBytes);
    return signature;
}

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  w w  .  j  av  a 2s  .  c  o m*/

    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.vmware.identity.sts.auth.impl.UserCertAuthenticator.java

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

    try {/*from w  ww  .j a v  a  2s. c  o  m*/
        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:com.boubei.tss.modules.license.LicenseManager.java

/**
 * <pre>/*from   w  w w  .  j  a v  a 2 s  . c o 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));
}

From source file:com.jinhe.tss.core.common.license.LicenseManager.java

/**
 * ?license??//from   w ww .j  a v a  2  s. com
 * ?Mac??????
 * ???????
 * 
 * @param license
 * @return
 * @throws Exception
 */
boolean validate(License license) throws Exception {
    String macAddress = license.getMacAddress();
    if (macAddress != null && macAddress.length() > 0) {
        String curMacAddress = MacAddressUtil.getMacAddress();
        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: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 .  co  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:cloud.google.oauth2.MyWayAuthentication.java

/**
 * Get signature from private key// www. j  a  v a 2 s  . co  m
 * */
public byte[] signData(byte[] data, PrivateKey privateKey)
        throws InvalidKeyException, SignatureException, NoSuchAlgorithmException {
    Signature signature = Signature.getInstance("SHA256withRSA");
    signature.initSign(privateKey);
    signature.update(data);
    return signature.sign();
}

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

protected boolean validateSignature(byte[] signingInput, byte[] signature, PublicKey publicKey) {
    try {/*from   w w w .j av  a2 s .co  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:jp.alessandro.android.iab.Security.java

/**
 * Verifies that the signature from the server matches the computed
 * signature on the data.  Returns true if the data is correctly signed.
 *
 * @param logger     the logger to use for printing events
 * @param publicKey  rsa public key generated by Google Play Developer Console
 * @param signedData signed data from server
 * @param signature  server signature//from  w  w  w. j ava2s . c om
 * @return true if the data and signature match
 */
protected boolean verify(Logger logger, PublicKey publicKey, String signedData, String signature)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException,
        InvalidKeyException, SignatureException, IllegalArgumentException {

    byte[] signatureBytes = Base64.decode(signature, Base64.DEFAULT);
    Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);

    sig.initVerify(publicKey);
    sig.update(signedData.getBytes("UTF-8"));
    if (!sig.verify(signatureBytes)) {
        logger.e(Logger.TAG, "Signature verification failed.");
        return false;
    }
    return true;
}

From source file:com.jinhe.tss.framework.license.LicenseManager.java

/**
 * <pre>/*from   w ww . j ava2s  .com*/
 * ?license??
 * ?Mac??????
 * ???????
 * </pre>
 * @param license
 * @return
 * @throws Exception
 */
boolean validate(License license) throws Exception {
    String macAddress = license.macAddress;
    if (!EasyUtils.isNullOrEmpty(macAddress)) {
        String curMacAddress = MacAddress.getMacAddress();
        if (!macAddress.equals(curMacAddress)) {
            return false;
        }
    }

    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.licenseSignature));
}