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.jinhe.tss.core.common.license.LicenseManager.java

/**
 * ?license??//from  ww w  . jav  a  2  s  . c o 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 = 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:org.jvnet.hudson.update_center.Signing.java

/**
 * Generates a canonicalized JSON format of the given object, and put the signature in it.
 * Because it mutates the signed object itself, validating the signature needs a bit of work,
 * but this enables a signature to be added transparently.
 *//*from  w w  w. j a va 2 s.  co m*/
public void sign(JSONObject o) throws GeneralSecurityException, IOException {
    JSONObject sign = new JSONObject();

    List<X509Certificate> certs = getCertificateChain();
    X509Certificate signer = certs.get(0); // the first one is the signer, and the rest is the chain to a root CA.

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

    // this is for computing a signature
    PrivateKey key = ((KeyPair) new PEMReader(new FileReader(privateKey)).readObject()).getPrivate();
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initSign(key);
    SignatureOutputStream sos = new SignatureOutputStream(sig);

    // this is for verifying that signature validates
    Signature verifier = Signature.getInstance("SHA1withRSA");
    verifier.initVerify(signer.getPublicKey());
    SignatureOutputStream vos = new SignatureOutputStream(verifier);

    o.writeCanonical(new OutputStreamWriter(new TeeOutputStream(new TeeOutputStream(dos, sos), vos), "UTF-8"));

    // digest
    byte[] digest = sha1.digest();
    sign.put("digest", new String(Base64.encodeBase64(digest)));

    // signature
    byte[] s = sig.sign();
    sign.put("signature", new String(Base64.encodeBase64(s)));

    // and certificate chain
    JSONArray a = new JSONArray();
    for (X509Certificate cert : certs)
        a.add(new String(Base64.encodeBase64(cert.getEncoded())));
    sign.put("certificates", a);

    // did the signature validate?
    if (!verifier.verify(s))
        throw new GeneralSecurityException(
                "Signature failed to validate. Either the certificate and the private key weren't matching, or a bug in the program.");

    o.put("signature", sign);
}

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// w w  w  .jav  a  2  s  . c  o  m
 * @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:RGSDigestTools.SignatureTool.java

public boolean verify(String dataToVerify, byte[] signature)
        throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, UnsupportedEncodingException {
    Signature signer = Signature.getInstance(signAlg);
    signer.initVerify(verifyKey);
    signer.update(dataToVerify.getBytes());
    return signer.verify(signature);

}

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

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

From source file:com.titilink.common.app.EncryptDecryptUtil.java

public void testRSA() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        BadPaddingException, IllegalBlockSizeException, SignatureException {
    ////from  w  w w .  j  a v  a2s.  co  m
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();

    //?
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();

    //??
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, privateKey, new SecureRandom());
    byte[] cipherData = cipher
            .doFinal("this is a security text from server".getBytes(Charset.forName("UTF-8")));

    //
    Cipher cipher1 = Cipher.getInstance("RSA");
    cipher1.init(Cipher.DECRYPT_MODE, publicKey, new SecureRandom());
    byte[] plainData = cipher1.doFinal(cipherData);
    System.out.println(new String(plainData, Charset.forName("UTF-8")));

    //???????
    Signature signature = Signature.getInstance("MD5withRSA");
    signature.initSign(privateKey);
    signature.update(cipherData);
    byte[] signData = signature.sign();

    //?????
    Signature signature1 = Signature.getInstance("MD5withRSA");
    signature1.initVerify(publicKey);
    signature1.update(cipherData);
    System.out.println(signature1.verify(signData));

}

From source file:com.POLIS.licensing.common.license.AbstractSerializationBasedLicense.java

@Override
public boolean verifyLicense(PublicKey senderSignatureKey)
        throws BadLicenseException, SystemStateException, OperationException {

    if (signature == null) {
        throw new OperationException("Could not vertify signature. License was never signed");
    }/*w w  w. ja va2 s. c o  m*/
    try {
        Signature instance = Signature.getInstance(signatureEncoding, provider);
        instance.initVerify(senderSignatureKey);
        instance.update(getFieldsAsString().getBytes());
        return instance.verify(signature);
    } catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
        throw new SystemStateException("Could not verify the license. Algorithm not found", ex);
    } catch (InvalidKeyException | SignatureException ex) {
        throw new OperationException("Could not verify the license.", ex);
    }
}

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

/**
 * Verify the signature of the given signature base string. The signature is verified by generating a new request signature octet string, and comparing it
 * to the signature provided by the Consumer, first URL-decoded per Parameter Encoding, then base64-decoded per RFC2045 section 6.8. The signature is
 * generated using the request parameters as provided by the Consumer, and the Consumer Secret and Token Secret as stored by the Service Provider.
 *
 * @param signatureBaseString The signature base string.
 * @param signature           The signature.
 * @throws InvalidSignatureException/*from  ww  w. j a  va 2s  .c  om*/
 *                                       If the signature is invalid for the specified base string.
 * @throws UnsupportedOperationException If there is no public key.
 */
public void verify(String signatureBaseString, String signature) throws InvalidSignatureException {
    if (publicKey == null) {
        throw new UnsupportedOperationException("A public key must be provided to verify signatures.");
    }

    try {
        byte[] signatureBytes = Base64.decodeBase64(signature.getBytes("UTF-8"));
        Signature verifier = Signature.getInstance("SHA1withRSA");
        verifier.initVerify(publicKey);
        verifier.update(signatureBaseString.getBytes("UTF-8"));
        if (!verifier.verify(signatureBytes)) {
            throw new InvalidSignatureException("Invalid signature for signature method " + getName());
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e);
    } catch (InvalidKeyException e) {
        throw new IllegalStateException(e);
    } catch (SignatureException e) {
        throw new IllegalStateException(e);
    }
}

From source file:test.integ.be.fedict.hsm.client.HSMProxyClientTest.java

@Test
public void testSign() throws Exception {
    Security.addProvider(new BeIDProvider());
    KeyStore beidKeyStore = KeyStore.getInstance("BeID");
    beidKeyStore.load(null);//from   ww  w  .  j a  v a2 s .c o  m
    X509Certificate authnCert = (X509Certificate) beidKeyStore.getCertificate("Authentication");
    PrivateKey authnPrivateKey = (PrivateKey) beidKeyStore.getKey("Authentication", null);

    String location = "http://localhost:8080/hsm-proxy-ws/dss";
    // String location = "https://www.e-contract.be/hsm-proxy-ws/dss";
    HSMProxyClient client = new HSMProxyClient(location, authnPrivateKey, authnCert);
    // client.setProxy("proxy.yourict.net", 8080);

    byte[] toBeSigned = "hello world".getBytes();
    MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
    messageDigest.update(toBeSigned);
    byte[] digestValue = messageDigest.digest();

    String keyAlias = "alias";

    byte[] signatureValue = client.sign(digestValue, "SHA1", keyAlias);
    assertNotNull(signatureValue);
    LOG.debug("signature value length: " + signatureValue.length);

    X509Certificate certificate = client.getCertificateChain(keyAlias).get(0);
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initVerify(certificate.getPublicKey());
    signature.update(toBeSigned);
    assertTrue(signature.verify(signatureValue));
}

From source file:com.streamsets.datacollector.publicrestapi.CredentialsDeploymentResource.java

private boolean validateSignature(CredentialsBeanJson credentialsBeanJson)
        throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {
    // getProperty so we can test it
    String publicKey = Preconditions.checkNotNull(System.getProperty(DPM_AGENT_PUBLIC_KEY));

    X509EncodedKeySpec kspec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey));
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey key = kf.generatePublic(kspec);
    Signature sig = Signature.getInstance("SHA256withRSA");
    sig.initVerify(key);
    sig.update(credentialsBeanJson.getToken().getBytes(Charsets.UTF_8));
    LOG.info("Token : {}, Signature {}", credentialsBeanJson.getToken(),
            credentialsBeanJson.getTokenSignature());
    return sig.verify(Base64.getDecoder().decode(credentialsBeanJson.getTokenSignature()));
}