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:ai.susi.tools.JsonSignature.java

public static boolean verify(Map<String, byte[]> obj, PublicKey key)
        throws SignatureException, InvalidKeyException {

    if (!obj.containsKey(signatureString))
        throw new SignatureException("No signature supplied");

    Signature signature;
    try {//  ww  w. j a v  a 2s . c om
        signature = Signature.getInstance("SHA256withRSA");
    } catch (NoSuchAlgorithmException e) {
        return false; //does not happen
    }

    byte[] sigString = obj.get(signatureString);
    byte[] sig = Base64.getDecoder().decode(sigString);
    obj.remove(signatureString);

    signature.initVerify(key);
    signature.update(obj.toString().getBytes(StandardCharsets.UTF_8));
    boolean res = signature.verify(sig);

    obj.put(signatureString, sigString);

    return res;
}

From source file:gemlite.core.util.RSAUtils.java

/**
 * <p>/*from  w  w  w. j av a  2  s .co m*/
 * ??
 * </p>
 * 
 * @param data
 *          ?
 * @param publicKey
 *          (BASE64?)
 * @param sign
 *          ??
 * 
 * @return
 * @throws Exception
 * 
 */
public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
    byte[] keyBytes = Base64Utils.decode(publicKey);
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    PublicKey publicK = keyFactory.generatePublic(keySpec);
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initVerify(publicK);
    signature.update(data);
    return signature.verify(Base64Utils.decode(sign));
}

From source file:ai.susi.tools.JsonSignature.java

/**
 * Verfies if the signature of a JSONObject is valid
 * @param obj the JSONObject//from  ww  w . j  a  v a  2s  . com
 * @param key the public key of the signature issuer
 * @return true if the signature is valid
 * @throws SignatureException if the JSONObject does not have a signature or something with the JSONObject is bogus
 * @throws InvalidKeyException if the key is not valid (for example not RSA)
 */
public static boolean verify(JSONObject obj, PublicKey key) throws SignatureException, InvalidKeyException {

    if (!obj.has(signatureString))
        throw new SignatureException("No signature supplied");

    Signature signature;
    try {
        signature = Signature.getInstance("SHA256withRSA");
    } catch (NoSuchAlgorithmException e) {
        return false; //does not happen
    }

    String sigString = obj.getString(signatureString);
    byte[] sig = Base64.getDecoder().decode(sigString);
    obj.remove(signatureString);

    signature.initVerify(key);
    signature.update(obj.toString().getBytes(StandardCharsets.UTF_8));
    boolean res = signature.verify(sig);

    obj.put(signatureString, sigString);

    return res;
}

From source file:Manifest.java

/**
 * This method verifies the digital signature of the named manifest file, if
 * it has one, and if that verification succeeds, it verifies the message
 * digest of each file in filelist that is also named in the manifest. This
 * method can throw a bunch of exceptions
 *//*from w w  w  .ja v a  2 s  .co  m*/
public static void verify(String manifestfile, KeyStore keystore) throws NoSuchAlgorithmException,
        SignatureException, InvalidKeyException, KeyStoreException, IOException {
    Properties manifest = new Properties();
    manifest.load(new FileInputStream(manifestfile));
    String digestAlgorithm = manifest.getProperty("__META.DIGESTALGORITHM");
    String signername = manifest.getProperty("__META.SIGNER");
    String signatureAlgorithm = manifest.getProperty("__META.SIGNATUREALGORITHM");
    String hexsignature = manifest.getProperty("__META.SIGNATURE");

    // Get a list of filenames in the manifest.
    List files = new ArrayList();
    Enumeration names = manifest.propertyNames();
    while (names.hasMoreElements()) {
        String s = (String) names.nextElement();
        if (!s.startsWith("__META"))
            files.add(s);
    }
    int numfiles = files.size();

    // If we've got a signature but no keystore, warn the user
    if (signername != null && keystore == null)
        System.out.println("Can't verify digital signature without " + "a keystore.");

    // If the manifest contained metadata about a digital signature, then
    // verify that signature first
    if (signername != null && keystore != null) {
        System.out.print("Verifying digital signature...");
        System.out.flush();

        // To verify the signature, we must process the files in exactly
        // the same order we did when we created the signature. We
        // guarantee this order by sorting the filenames.
        Collections.sort(files);

        // Create a Signature object to do signature verification with.
        // Initialize it with the signer's public key from the keystore
        Signature signature = Signature.getInstance(signatureAlgorithm);
        PublicKey publickey = keystore.getCertificate(signername).getPublicKey();
        signature.initVerify(publickey);

        // Now loop through these files in their known sorted order For
        // each one, send the bytes of the filename and of the digest to
        // the signature object for use in computing the signature. It is
        // important that this be done in exactly the same order when
        // verifying the signature as it was done when creating the
        // signature.
        for (int i = 0; i < numfiles; i++) {
            String filename = (String) files.get(i);
            signature.update(filename.getBytes());
            signature.update(hexDecode(manifest.getProperty(filename)));
        }

        // Now decode the signature read from the manifest file and pass
        // it to the verify() method of the signature object. If the
        // signature is not verified, print an error message and exit.
        if (!signature.verify(hexDecode(hexsignature))) {
            System.out.println("\nManifest has an invalid signature");
            System.exit(0);
        }

        // Tell the user we're done with this lengthy computation
        System.out.println("verified.");
    }

    // Tell the user we're starting the next phase of verification
    System.out.print("Verifying file message digests");
    System.out.flush();

    // Get a MessageDigest object to compute digests
    MessageDigest md = MessageDigest.getInstance(digestAlgorithm);
    // Loop through all files
    for (int i = 0; i < numfiles; i++) {
        String filename = (String) files.get(i);
        // Look up the encoded digest from the manifest file
        String hexdigest = manifest.getProperty(filename);
        // Compute the digest for the file.
        byte[] digest;
        try {
            digest = getFileDigest(filename, md);
        } catch (IOException e) {
            System.out.println("\nSkipping " + filename + ": " + e);
            continue;
        }

        // Encode the computed digest and compare it to the encoded digest
        // from the manifest. If they are not equal, print an error
        // message.
        if (!hexdigest.equals(hexEncode(digest)))
            System.out.println("\nFile '" + filename + "' failed verification.");

        // Send one dot of output for each file we process. Since
        // computing message digests takes some time, this lets the user
        // know that the program is functioning and making progress
        System.out.print(".");
        System.out.flush();
    }
    // And tell the user we're done with verification.
    System.out.println("done.");
}

From source file:com.github.ibole.infrastructure.security.ECDSA.java

public static void jdkECDSA() {
    try {//from w w w  . j  a  v a 2s.  co  m
        // 1.?
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
        keyPairGenerator.initialize(256);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        ECPublicKey ecPublicKey = (ECPublicKey) keyPair.getPublic();
        ECPrivateKey ecPrivateKey = (ECPrivateKey) keyPair.getPrivate();

        // 2.??
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(ecPrivateKey.getEncoded());

        KeyFactory keyFactory = KeyFactory.getInstance("EC");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        Signature signature = Signature.getInstance("SHA256withECDSA");
        signature.initSign(privateKey);
        signature.update(src.getBytes());
        byte[] res = signature.sign();
        System.out.println("??" + Base64.encodeBase64String(res));

        // 3.???
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(ecPublicKey.getEncoded());
        keyFactory = KeyFactory.getInstance("EC");
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
        signature = Signature.getInstance("SHA256withECDSA");
        signature.initVerify(publicKey);
        signature.update(src.getBytes());
        boolean bool = signature.verify(res);
        System.out.println("?" + bool);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:biz.bokhorst.xprivacy.Util.java

private static boolean verifyData(byte[] data, byte[] signature, PublicKey publicKey) throws Throwable {
    // Verify signature
    Signature verifier = Signature.getInstance("SHA1withRSA");
    verifier.initVerify(publicKey);
    verifier.update(data);/*from ww  w .  j  a  v  a 2 s . c om*/
    return verifier.verify(signature);
}

From source file:org.ejbca.core.protocol.cmp.CmpMessageHelper.java

/** verifies signature protection on CMP PKI messages
 *  //from www. j a v a2 s .c  om
 * @param pKIMessage the CMP message to verify signature on, if protected by signature protection
 * @param pubKey the public key used to verify the signature
 * @return true if verification is ok or false if verification fails
 * @throws NoSuchAlgorithmException message is signed by an unknown algorithm
 * @throws NoSuchProviderException the BouncyCastle (BC) provider is not installed
 * @throws InvalidKeyException pubKey is not valid for signature verification
 * @throws SignatureException if the passed-in signature is improperly encoded or of the wrong type, if this signature algorithm is unable to process the input data provided, etc.
 */
public static boolean verifyCertBasedPKIProtection(PKIMessage pKIMessage, PublicKey pubKey)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException {
    AlgorithmIdentifier sigAlg = pKIMessage.getHeader().getProtectionAlg();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Verifying signature with algorithm: " + sigAlg.getAlgorithm().getId());
    }
    Signature sig = Signature.getInstance(sigAlg.getAlgorithm().getId(), "BC");
    sig.initVerify(pubKey);
    sig.update(CmpMessageHelper.getProtectedBytes(pKIMessage));
    boolean result = sig.verify(pKIMessage.getProtection().getBytes());
    if (LOG.isDebugEnabled()) {
        LOG.debug("Verification result: " + result);
    }
    return result;
}

From source file:com.netscape.cms.servlet.test.DRMTest.java

/**
 * Verify the generated asymmetric key pair.
 *
 * @param keyAlgorithm - Algorithm used to generate keys.
 * @param privateKey - binary data of the private key.
 * @param publicKey - binary data of he public key.
 * @return//from   ww w . j a v  a 2 s  .  c o  m
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws InvalidKeyException
 * @throws SignatureException
 * @throws IOException
 */
public static boolean isKeyPairValid(String keyAlgorithm, byte[] privateKey, byte[] publicKey)
        throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException,
        IOException {
    String algorithm = keyAlgorithm.toUpperCase();
    String signingAlgorithm = "SHA1with" + algorithm;
    KeyFactory factory = KeyFactory.getInstance(algorithm);
    PrivateKey priKey = factory.generatePrivate(new PKCS8EncodedKeySpec(privateKey));
    PublicKey pubKey = factory.generatePublic(new X509EncodedKeySpec(publicKey));
    Signature sig = Signature.getInstance(signingAlgorithm);
    sig.initSign(priKey);
    String s = "Data to test asymmetric keys.";
    sig.update(s.getBytes());

    // Sign the data with the private key.
    byte[] realSig = sig.sign();

    Signature sig2 = Signature.getInstance(signingAlgorithm);
    sig2.initVerify(pubKey);

    sig2.update(s.getBytes());
    // Verify the signature with the public key.
    return sig2.verify(realSig);
}

From source file:com.orange.oidc.secproxy_service.KryptoUtils.java

static public boolean verifyJWS(String s, String algorithm, PublicKey pubKey, PrivateKey privKey) {
    // algorithm = "SHA256withRSA";
    // algorithm = "SHA1withRSA";

    boolean bverify = false;

    String parts[] = s.split("\\.");
    if (parts == null || parts.length != 3)
        return bverify;

    try {/*from w w w.java  2  s . co m*/
        if ("RS256".compareTo(algorithm) == 0)
            algorithm = "SHA256withRSA";
        Signature signature = Signature.getInstance(algorithm, "SC");
        signature.initVerify(pubKey);
        signature.update((parts[0] + "." + parts[1]).getBytes());
        bverify = signature.verify(decodeB64(parts[2]));

        Log.d("verifyJWS", "payload: " + new String(decodeB64(parts[1])));
        /*
        // verify signature
        signature.initSign(privKey);
        signature.update((parts[0]+"."+parts[1]).getBytes());
        byte sig[] = signature.sign();
        String sig64 = encodeB64(sig);
        Log.d("verifyJWS","compute: "+sig64);
        */

    } catch (Exception e) {
        e.printStackTrace();
    }

    return bverify;
}

From source file:org.signserver.server.cryptotokens.CryptoTokenHelper.java

/**
 * Creates a test signature and verifies it.
 *
 * @param privateKey Private key to sign with
 * @param publicKey Public key to verify with
 * @param signatureProvider Name of provider to sign with
 * @throws NoSuchAlgorithmException In case the key or signature algorithm is unknown
 * @throws NoSuchProviderException In case the supplied provider name is unknown or BC is not installed
 * @throws InvalidKeyException If signature verification failed or the key was invalid
 * @throws SignatureException If the signature could not be made or verified correctly
 *///from   www .  j ava  2s.co m
public static void testSignAndVerify(PrivateKey privateKey, PublicKey publicKey, String signatureProvider)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException {
    final byte input[] = "Lillan gick pa vagen ut, motte dar en katt...".getBytes();
    final String sigAlg = suggestSigAlg(publicKey);
    if (sigAlg == null) {
        throw new NoSuchAlgorithmException("Unknown key algorithm: " + publicKey.getAlgorithm());
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Testing keys with algorithm: " + publicKey.getAlgorithm());
        LOG.debug("testSigAlg: " + sigAlg);
        LOG.debug("provider: " + signatureProvider);
        LOG.trace("privateKey: " + privateKey);
        LOG.trace("privateKey class: " + privateKey.getClass().getName());
        LOG.trace("publicKey: " + publicKey);
        LOG.trace("publicKey class: " + publicKey.getClass().getName());
    }
    final Signature signSignature = Signature.getInstance(sigAlg, signatureProvider);
    signSignature.initSign(privateKey);
    signSignature.update(input);
    byte[] signBA = signSignature.sign();
    if (LOG.isTraceEnabled()) {
        LOG.trace("Created signature of size: " + signBA.length);
        LOG.trace("Created signature: " + new String(Hex.encode(signBA)));
    }

    final Signature verifySignature = Signature.getInstance(sigAlg, "BC");
    verifySignature.initVerify(publicKey);
    verifySignature.update(input);
    if (!verifySignature.verify(signBA)) {
        throw new InvalidKeyException("Test signature inconsistent");
    }
}