Java Code Examples for java.security.Signature#initVerify()

The following examples show how to use java.security.Signature#initVerify() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TLSTest.java    From incubator-tuweni with Apache License 2.0 7 votes vote down vote up
private void checkKeyPair(Path key, Path cert) throws Exception {
  PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(readPemFile(key));
  CertificateFactory cf = CertificateFactory.getInstance("X.509");
  Certificate certificate = cf.generateCertificate(new ByteArrayInputStream(Files.readAllBytes(cert)));
  KeyFactory kf = KeyFactory.getInstance("RSA");
  KeyPair keyPair = new KeyPair(certificate.getPublicKey(), kf.generatePrivate(pkcs8KeySpec));

  byte[] challenge = new byte[10000];
  ThreadLocalRandom.current().nextBytes(challenge);

  // sign using the private key
  Signature sig = Signature.getInstance("SHA256withRSA");
  sig.initSign(keyPair.getPrivate());
  sig.update(challenge);
  byte[] signature = sig.sign();

  // verify signature using the public key
  sig.initVerify(keyPair.getPublic());
  sig.update(challenge);

  assertTrue(sig.verify(signature));
}
 
Example 2
Source File: EncodingXMLTest.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testECDSA192() throws Exception {
	Security.addProvider(new BouncyCastleProvider());
	KeyPairGenerator gen = KeyPairGenerator.getInstance("ECDSA");
	gen.initialize(192);
	KeyPair pair = gen.generateKeyPair();

	Signature s = Signature.getInstance("SHA256withECDSA");
	s.initSign(pair.getPrivate());
	s.update(HELLO_WORLD.getBytes());
	byte[] signatureValue = s.sign();

	byte[] convertToXmlDSig = DSSSignatureUtils.convertToXmlDSig(EncryptionAlgorithm.ECDSA, signatureValue);
	assertTrue(Utils.isArrayNotEmpty(convertToXmlDSig));

	byte[] asn1xmlsec = SignatureECDSA.convertXMLDSIGtoASN1(convertToXmlDSig);

	Signature s2 = Signature.getInstance("SHA256withECDSA");
	s2.initVerify(pair.getPublic());
	s2.update(HELLO_WORLD.getBytes());
	assertTrue(s2.verify(asn1xmlsec));
}
 
Example 3
Source File: ECDHServerKeyExchange.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
private static Signature getSignature(String keyAlgorithm,
        Key key) throws NoSuchAlgorithmException, InvalidKeyException {
    Signature signer = null;
    switch (keyAlgorithm) {
        case "EC":
            signer = Signature.getInstance(JsseJce.SIGNATURE_ECDSA);
            break;
        case "RSA":
            signer = RSASignature.getInstance();
            break;
        default:
            throw new NoSuchAlgorithmException(
                "neither an RSA or a EC key : " + keyAlgorithm);
    }

    if (signer != null) {
        if (key instanceof PublicKey) {
            signer.initVerify((PublicKey)(key));
        } else {
            signer.initSign((PrivateKey)key);
        }
    }

    return signer;
}
 
Example 4
Source File: CryptographicUtilities.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
public static boolean verifyStream(InputStream dataStream, PublicKey publicKey, byte[] signatureData, String signatureMethod) throws Exception {
	Security.addProvider(new BouncyCastleProvider());

	try {
		Signature signature = Signature.getInstance(signatureMethod, "BC");
		signature.initVerify(publicKey);
		byte[] buffer = new byte[4096];
		int bytesRead = dataStream.read(buffer);
		while (bytesRead >= 0) {
			signature.update(buffer, 0, bytesRead);
			bytesRead = dataStream.read(buffer);
		}
		return signature.verify(signatureData);
	} catch (Exception e) {
		throw new Exception("Cannot verify signature", e);
	}
}
 
Example 5
Source File: NodeSignatureVerifier.java    From hedera-mirror-node with Apache License 2.0 6 votes vote down vote up
/**
 * check whether the given signature is valid
 *
 * @param fileStreamSignature the data that was signed
 * @return true if the signature is valid
 */
private boolean verifySignature(FileStreamSignature fileStreamSignature) {
    PublicKey publicKey = nodeIDPubKeyMap.get(fileStreamSignature.getNode());
    if (publicKey == null) {
        log.warn("Missing PublicKey for node {}", fileStreamSignature.getNode());
        return false;
    }

    if (fileStreamSignature.getSignature() == null) {
        log.error("Missing signature data: {}", fileStreamSignature);
        return false;
    }

    try {
        log.trace("Verifying signature: {}", fileStreamSignature);
        Signature sig = Signature.getInstance("SHA384withRSA", "SunRsaSign");
        sig.initVerify(publicKey);
        sig.update(fileStreamSignature.getHash());
        return sig.verify(fileStreamSignature.getSignature());
    } catch (Exception e) {
        log.error("Failed to verify signature with public key {}: {}", publicKey, fileStreamSignature, e);
    }
    return false;
}
 
Example 6
Source File: DefaultCertificateClient.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies a digital Signature, given the signature and the certificate of
 * the signer.
 *
 * @param data - Data in byte array.
 * @param signature - Byte Array containing the signature.
 * @param cert - Certificate of the Signer.
 * @return true if verified, false if not.
 */
@Override
public boolean verifySignature(byte[] data, byte[] signature,
    X509Certificate cert) throws CertificateException {
  try {
    Signature sign = Signature.getInstance(securityConfig.getSignatureAlgo(),
        securityConfig.getProvider());
    sign.initVerify(cert);
    sign.update(data);
    return sign.verify(signature);
  } catch (NoSuchAlgorithmException | NoSuchProviderException
      | InvalidKeyException | SignatureException e) {
    getLogger().error("Error while signing the stream", e);
    throw new CertificateException("Error while signing the stream", e,
        CRYPTO_SIGNATURE_VERIFICATION_ERROR);
  }
}
 
Example 7
Source File: JCEUtils.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
public static boolean verifyDigitalSignature(byte[] data, byte[] signatureData, X509Certificate certificate) throws PKIException {
    try {
        Signature signature = Signature.getInstance(SHA256_RSA, BC_PROVIDER); //"SHA256withECDSA"
        signature.initVerify(certificate);
        signature.update(data);
        return signature.verify(signatureData);
    } catch (Exception e) {
        throw new PKIException(e);
    }
}
 
Example 8
Source File: XAdESCanonicalizationTest.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected void onDocumentSigned(byte[] byteArray) {
	super.onDocumentSigned(byteArray);
	saveDocumentAndDelete(byteArray);

	try {
		Document doc = DomUtils.buildDOM(byteArray);

		checkKeyInfo(doc);
		checkSignedProperties(doc);
		checkOriginalDocument(doc);

		// ------------------------------------ SIGNED INFO
		// -----------------------------------------------------
		// Signed info extraction
		NodeList signedInfoNodeList = DomUtils.getNodeList(doc, AbstractPaths.all(XMLDSigElement.SIGNED_INFO));
		assertNotNull(signedInfoNodeList);
		assertEquals(1, signedInfoNodeList.getLength());

		Node signedInfo = signedInfoNodeList.item(0);

		// ------------------------------------ SIGNATURE VERIFICATION
		// -----------------------------------------------------
		Canonicalizer canonicalizer = Canonicalizer.getInstance(canonicalizationSignedInfo);
		String signatureValueBase64 = DomUtils.getValue(doc, "//ds:Signature/ds:SignatureValue");
		assertNotNull(signatureValueBase64);

		byte[] canonicalized = canonicalizer.canonicalizeSubtree(signedInfo);

		byte[] sigValue = Utils.fromBase64(signatureValueBase64);

		Signature signature = Signature.getInstance("SHA256withRSA");
		signature.initVerify(getSigningCert().getPublicKey());
		signature.update(canonicalized);
		boolean verify = signature.verify(sigValue);
		assertTrue(verify);
	} catch (Exception e) {
		fail(e.getMessage());
	}
}
 
Example 9
Source File: cryptoCommon.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static boolean verifySignature(byte[] signature, PublicKey publickey, byte[] signedobject, String algorithm) {
    try {
        Signature sig = Signature.getInstance(algorithm, BC_FIPS_PROVIDER);
        sig.initVerify(publickey);
        sig.update(signedobject);
        return sig.verify(signature);

    } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException ex) {
        logp(Level.FINE, classname, "verifySignature", "CRYPTO-MSG-1000", "ex=" + printStackTrace(ex));
    }
    return false;
}
 
Example 10
Source File: RSAUtil.java    From af-pay with Apache License 2.0 5 votes vote down vote up
public static boolean verifyProduct(byte[] message, byte[] signature)
        throws Exception {
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initVerify(getPublicKeyProduct());
    sig.update(message);
    return sig.verify(signature);
}
 
Example 11
Source File: SM2.java    From littleca with Apache License 2.0 5 votes vote down vote up
@Override
public boolean verifySign(byte[] signData, byte[] content, PublicKey publicKey, String signAlgorithm) throws Exception {
	Signature signature = AsymmetricalUtil.getSignatureInstance(signAlgorithm);
	signature.initVerify(publicKey);
	signature.update(content);
	return signature.verify(signData);
}
 
Example 12
Source File: X509CRLImpl.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Verifies that this CRL was signed using the
 * private key that corresponds to the given public key,
 * and that the signature verification was computed by
 * the given provider. Note that the specified Provider object
 * does not have to be registered in the provider list.
 *
 * @param key the PublicKey used to carry out the verification.
 * @param sigProvider the signature provider.
 *
 * @exception NoSuchAlgorithmException on unsupported signature
 * algorithms.
 * @exception InvalidKeyException on incorrect key.
 * @exception SignatureException on signature errors.
 * @exception CRLException on encoding errors.
 */
public synchronized void verify(PublicKey key, Provider sigProvider)
        throws CRLException, NoSuchAlgorithmException, InvalidKeyException,
        SignatureException {

    if (signedCRL == null) {
        throw new CRLException("Uninitialized CRL");
    }
    Signature sigVerf = null;
    if (sigProvider == null) {
        sigVerf = Signature.getInstance(sigAlgId.getName());
    } else {
        sigVerf = Signature.getInstance(sigAlgId.getName(), sigProvider);
    }
    sigVerf.initVerify(key);

    if (tbsCertList == null) {
        throw new CRLException("Uninitialized CRL");
    }

    sigVerf.update(tbsCertList, 0, tbsCertList.length);

    if (!sigVerf.verify(signature)) {
        throw new SignatureException("Signature does not match.");
    }
    verifiedPublicKey = key;
}
 
Example 13
Source File: RsaMessage.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
/**
* �ù�Կ��֤ǩ�����ȷ��
*
* @param message
* @param signStr
* @return
* @throws Exception
*/
public boolean verifySign(String message, String signStr, PublicKey key)
throws Exception {
if (message == null || signStr == null || key == null) {
return false;
}
Signature signetcheck = Signature.getInstance("MD5withRSA");
signetcheck.initVerify(key);
signetcheck.update(message.getBytes("ISO-8859-1"));
return signetcheck.verify(toBytes(signStr));
}
 
Example 14
Source File: RSAUtilsEN.java    From dk-fitting with Apache License 2.0 5 votes vote down vote up
public static boolean verify(byte[] data, String publicKey, String sign)
        throws Exception {
    byte[] keyBytes = Base64UtilsEN.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(Base64UtilsEN.decode(sign));
}
 
Example 15
Source File: DefaultCryptoMaterialsManagerTest.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void decrypt_testSimpleRoundTrip() throws Exception {
    for (CryptoAlgorithm algorithm : CryptoAlgorithm.values()) {
        EncryptionMaterials encryptMaterials = easyGenMaterials(
                builder -> builder.setRequestedAlgorithm(algorithm)
        );

        DecryptionMaterials decryptMaterials
                = new DefaultCryptoMaterialsManager(mk1).decryptMaterials(decryptReqFromMaterials(encryptMaterials));

        assertArrayEquals(decryptMaterials.getDataKey().getKey().getEncoded(),
                          encryptMaterials.getCleartextDataKey().getEncoded());

        if (encryptMaterials.getTrailingSignatureKey() == null) {
            assertNull(decryptMaterials.getTrailingSignatureKey());
        } else {
            Signature sig = Signature.getInstance(
                    TrailingSignatureAlgorithm.forCryptoAlgorithm(algorithm).getHashAndSignAlgorithm()
            );

            sig.initSign(encryptMaterials.getTrailingSignatureKey());

            byte[] data = "hello world".getBytes(StandardCharsets.UTF_8);

            sig.update(data);
            byte[] signature = sig.sign();

            sig.initVerify(decryptMaterials.getTrailingSignatureKey());

            sig.update(data);
            sig.verify(signature);
        }
    }
}
 
Example 16
Source File: Basic.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
private static int signAlias(int testnum, String alias) throws Exception {

        if (ks == null) {
            ks = KeyStore.getInstance(KS_TYPE, provider);
            ks.load(null, tokenPwd);
        }

        if (alias == null) {
            Enumeration enu = ks.aliases();
            if (enu.hasMoreElements()) {
                alias = (String)enu.nextElement();
            }
        }

        PrivateKey pkey = (PrivateKey)ks.getKey(alias, null);
        if ("RSA".equals(pkey.getAlgorithm())) {
            System.out.println("got [" + alias + "] signing key: " + pkey);
        } else {
            throw new SecurityException
                ("expected RSA, got " + pkey.getAlgorithm());
        }

        Signature s = Signature.getInstance("MD5WithRSA", ks.getProvider());
        s.initSign(pkey);
        System.out.println("initialized signature object with key");
        s.update("hello".getBytes());
        System.out.println("signature object updated with [hello] bytes");

        byte[] signed = s.sign();
        System.out.println("received signature " + signed.length +
                        " bytes in length");

        Signature v = Signature.getInstance("MD5WithRSA", ks.getProvider());
        v.initVerify(ks.getCertificate(alias));
        v.update("hello".getBytes());
        v.verify(signed);
        System.out.println("signature verified");
        System.out.println("test " + testnum++ + " passed");

        return testnum;
    }
 
Example 17
Source File: SignatureLength.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
private static void main0(String keyAlgorithm, int keysize,
        String signatureAlgorithm, Provider generatorProvider,
        Provider signerProvider, Provider verifierProvider,
        boolean mayNotThrow) throws Exception {

    KeyPairGenerator generator;
    Signature signer;
    Signature verifier;

    try {
        generator = KeyPairGenerator.getInstance(keyAlgorithm,
                generatorProvider);
        signer = Signature.getInstance(signatureAlgorithm,
                signerProvider);
        verifier = Signature.getInstance(signatureAlgorithm,
                verifierProvider);
    } catch (NoSuchAlgorithmException nsae) {
        // ignore this set of providers
        return;
    }

    byte[] plaintext = "aaa".getBytes("UTF-8");

    // Generate
    generator.initialize(keysize);
    System.out.println("Generating " + keyAlgorithm + " keypair using " +
        generator.getProvider().getName() + " JCE provider");
    KeyPair keypair = generator.generateKeyPair();

    // Sign
    signer.initSign(keypair.getPrivate());
    signer.update(plaintext);
    System.out.println("Signing using " + signer.getProvider().getName() +
        " JCE provider");
    byte[] signature = signer.sign();

    // Invalidate
    System.out.println("Invalidating signature ...");
    byte[] badSignature = new byte[signature.length + 5];
    System.arraycopy(signature, 0, badSignature, 0, signature.length);
    badSignature[signature.length] = 0x01;
    badSignature[signature.length + 1] = 0x01;
    badSignature[signature.length + 2] = 0x01;
    badSignature[signature.length + 3] = 0x01;
    badSignature[signature.length + 4] = 0x01;

    // Verify
    verifier.initVerify(keypair.getPublic());
    verifier.update(plaintext);
    System.out.println("Verifying using " +
        verifier.getProvider().getName() + " JCE provider");

    try {
        boolean valid = verifier.verify(badSignature);
        System.out.println("Valid? " + valid);
        if (mayNotThrow) {
            if (valid) {
                throw new Exception(
                    "ERROR: expected a SignatureException but none was thrown"
                    + " and invalid signature was verified");
            } else {
                System.out.println("OK: verification failed as expected");
            }
        } else {
            throw new Exception(
                "ERROR: expected a SignatureException but none was thrown");
        }
    } catch (SignatureException e) {
        System.out.println("OK: caught expected exception: " + e);
    }
    System.out.println();
}
 
Example 18
Source File: SignatureLength.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private static void main0(String keyAlgorithm, int keysize,
        String signatureAlgorithm, String provider) throws Exception {
    byte[] plaintext = "aaa".getBytes("UTF-8");

    // Generate
    KeyPairGenerator generator =
        provider == null ?
            (KeyPairGenerator) KeyPairGenerator.getInstance(keyAlgorithm) :
            (KeyPairGenerator) KeyPairGenerator.getInstance(
                                   keyAlgorithm, provider);
    generator.initialize(keysize);
    System.out.println("Generating " + keyAlgorithm + " keypair using " +
        generator.getProvider().getName() + " JCE provider");
    KeyPair keypair = generator.generateKeyPair();

    // Sign
    Signature signer =
        provider == null ?
            Signature.getInstance(signatureAlgorithm) :
            Signature.getInstance(signatureAlgorithm, provider);
    signer.initSign(keypair.getPrivate());
    signer.update(plaintext);
    System.out.println("Signing using " + signer.getProvider().getName() +
        " JCE provider");
    byte[] signature = signer.sign();

    // Invalidate
    System.out.println("Invalidating signature ...");
    byte[] badSignature = new byte[signature.length + 5];
    System.arraycopy(signature, 0, badSignature, 0, signature.length);
    badSignature[signature.length] = 0x01;
    badSignature[signature.length + 1] = 0x01;
    badSignature[signature.length + 2] = 0x01;
    badSignature[signature.length + 3] = 0x01;
    badSignature[signature.length + 4] = 0x01;

    // Verify
    Signature verifier =
        provider == null ?
            Signature.getInstance(signatureAlgorithm) :
            Signature.getInstance(signatureAlgorithm, provider);
    verifier.initVerify(keypair.getPublic());
    verifier.update(plaintext);
    System.out.println("Verifying using " +
        verifier.getProvider().getName() + " JCE provider");

    try {
        System.out.println("Valid? " + verifier.verify(badSignature));
        throw new Exception(
            "ERROR: expected a SignatureException but none was thrown");
    } catch (SignatureException e) {
        System.out.println("OK: caught expected exception: " + e);
    }
    System.out.println();
}
 
Example 19
Source File: SignatureTest.java    From protect with MIT License 4 votes vote down vote up
public static void main(String[] args) throws Exception {
	byte[] data = new byte[20];
	byte[] signature;
	Signature signEng;
	long start, end;

	KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
	kpg.initialize(1024);
	KeyPair kp = kpg.genKeyPair();
	PublicKey publicKey = kp.getPublic();
	PrivateKey privateKey = kp.getPrivate();

	signEng = Signature.getInstance("SHA1withRSA");

	for (int i = 0; i < 1000; i++) {
		signEng = Signature.getInstance("SHA1withRSA");
		signEng.initSign(privateKey);
	}
	start = System.currentTimeMillis();
	for (int i = 0; i < 1000; i++) {
		signEng = Signature.getInstance("SHA1withRSA");
		signEng.initSign(privateKey);
	}
	end = System.currentTimeMillis();
	System.out.println("1000 init sign: " + (end - start) + "ms");

	for (int i = 0; i < 1000; i++) {
		signEng.update(data);
		signature = signEng.sign();
	}
	start = System.currentTimeMillis();
	for (int i = 0; i < 1000; i++) {
		signEng.update(data);
		signature = signEng.sign();
	}
	end = System.currentTimeMillis();
	System.out.println("1000 sign: " + (end - start) + "ms");

	signEng.update(data);
	signature = signEng.sign();

	for (int i = 0; i < 1000; i++) {
		signEng = Signature.getInstance("SHA1withRSA");
		signEng.initVerify(publicKey);
	}
	start = System.currentTimeMillis();
	for (int i = 0; i < 1000; i++) {
		signEng = Signature.getInstance("SHA1withRSA");
		signEng.initVerify(publicKey);
	}
	end = System.currentTimeMillis();
	System.out.println("1000 init verify: " + (end - start) + "ms");

	for (int i = 0; i < 1000; i++) {
		signEng.update(data);
		signEng.verify(signature);
	}
	start = System.currentTimeMillis();
	for (int i = 0; i < 1000; i++) {
		signEng.update(data);
		signEng.verify(signature);
	}
	end = System.currentTimeMillis();
	System.out.println("1000 verify: " + (end - start) + "ms");
}
 
Example 20
Source File: EncodeDecodeTest.java    From Bitcoin with Apache License 2.0 4 votes vote down vote up
@Test
public void test2() {
    byte[] data = "hello.".getBytes();

    /* Test generating and verifying a DSA signature */
    try {
        /* generate a key pair */
        final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
        keyGen.initialize(1024, new SecureRandom());
        final KeyPair pair = keyGen.generateKeyPair();

        /* create a Signature object to use
         * for signing and verifying */
        final Signature dsa = Signature.getInstance("SHA/DSA"); 

        /* initialize the Signature object for signing */
        final PrivateKey priv = pair.getPrivate();
        dsa.initSign(priv);

        /* Update and sign the data */
        dsa.update(data);

        /* Now that all the data to be signed has been read in, sign it */
        final byte[] sig = dsa.sign();

        /* Verify the signature */

        /* Initialize the Signature object for verification */
        final PublicKey pub = pair.getPublic();
        /* Encode the public key into a byte array */
        final byte[] encoded = pub.getEncoded();
        /* Get the public key from the encoded byte array */
        final PublicKey fromEncoded = KeyFactory.getInstance("DSA", "SUN").generatePublic(new X509EncodedKeySpec(encoded));
        dsa.initVerify(fromEncoded);

        /* Update and verify the data */
        dsa.update(data);

        final boolean verified = dsa.verify(sig);
        Assert.assertTrue(verified);
    } catch (Exception e) {
        System.err.println("Caught exception " + e.toString());
    }
}