Example usage for java.security Signature getInstance

List of usage examples for java.security Signature getInstance

Introduction

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

Prototype

public static Signature getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a Signature object that implements the specified signature algorithm.

Usage

From source file:hudson.cli.Connection.java

/**
 * Verifies that we are talking to a peer that actually owns the private key corresponding to the public key we get.
 *///from   www. j  a  v a 2 s .c om
public PublicKey verifyIdentity(byte[] sharedSecret) throws IOException, GeneralSecurityException {
    try {
        String serverKeyAlgorithm = readUTF();
        PublicKey spk = KeyFactory.getInstance(serverKeyAlgorithm).generatePublic(readKey());

        // verify the identity of the server
        Signature sig = Signature.getInstance("SHA1with" + serverKeyAlgorithm);
        sig.initVerify(spk);
        sig.update(spk.getEncoded());
        sig.update(sharedSecret);
        sig.verify((byte[]) readObject());

        return spk;
    } catch (ClassNotFoundException e) {
        throw new Error(e); // impossible
    }
}

From source file:org.intermine.webservice.server.JWTVerifier.java

private boolean verifySignature(PublicKey key, String algorithm, String signed, byte[] toVerify)
        throws VerificationError {
    Signature signature;//w  ww.  ja  v a  2  s.  c o  m
    try {
        signature = Signature.getInstance(algorithm);
    } catch (NoSuchAlgorithmException e) {
        throw new VerificationError(e.getMessage());
    }
    try {
        signature.initVerify(key);
    } catch (InvalidKeyException e) {
        throw new VerificationError("Key is invalid. " + e.getMessage());
    }

    try {
        signature.update(signed.getBytes());
    } catch (SignatureException e) {
        throw new VerificationError("Error creating signature: " + e.getMessage());
    }

    try {
        return signature.verify(toVerify);
    } catch (SignatureException e) {
        throw new VerificationError("Error during verification: " + e.getMessage());
    }
}

From source file:be.e_contract.eid.applet.service.impl.handler.IdentityDataMessageHandler.java

private void verifySignature(BeIDContextQualifier contextQualifier, String signAlgo, byte[] signatureData,
        X509Certificate certificate, HttpServletRequest request, byte[]... data) throws ServletException {
    Signature signature;/*from  w w w.  j a  v  a 2s . co  m*/
    try {
        signature = Signature.getInstance(signAlgo);
    } catch (NoSuchAlgorithmException e) {
        throw new ServletException("algo error: " + e.getMessage(), e);
    }
    PublicKey publicKey = certificate.getPublicKey();
    try {
        signature.initVerify(publicKey);
    } catch (InvalidKeyException e) {
        throw new ServletException("key error: " + e.getMessage(), e);
    }
    try {
        for (byte[] dataItem : data) {
            signature.update(dataItem);
        }
        boolean result = signature.verify(signatureData);
        if (false == result) {
            SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.DATA_INTEGRITY, certificate,
                    signatureData);
            this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent);
            throw new ServletException("signature incorrect");
        }
    } catch (SignatureException e) {
        SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.DATA_INTEGRITY, certificate,
                signatureData);
        this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent);
        throw new ServletException("signature error: " + e.getMessage(), e);
    }
}

From source file:org.tolven.security.bean.DocProtectionBean.java

/**
 * Verify the document signature belongs to aPublicKey using aDecryptionKey
 * to decrypt the document// w w w.j a v a  2  s  . c o m
 * @param aPublicKey
 * @param aDecryptionKey
 * @return
 */
public boolean verify(DocumentSignature documentSignature, X509Certificate x509Certificate,
        AccountUser activeAccountUser, PrivateKey userPrivateKey) {
    try {
        Signature signature = Signature.getInstance(documentSignature.getSignatureAlgorithm());
        signature.initVerify(x509Certificate.getPublicKey());
        byte[] document = getDecryptedContent(documentSignature.getDocBase(), activeAccountUser,
                userPrivateKey);
        signature.update(document);
        return signature.verify(documentSignature.getSignature());
    } catch (Exception ex) {
        throw new RuntimeException("Could not verify the signature", ex);
    }
}

From source file:org.opensaml.security.crypto.SigningUtil.java

/**
 * Verify the signature value computed over the supplied input against the supplied signature value.
 * //from  w  ww. j a  v a  2 s.c  o  m
 * It is up to the caller to ensure that the specified algorithm ID is consistent with the type of verification key
 * supplied.
 * 
 * @param verificationKey the key with which to compute and verify the signature
 * @param jcaAlgorithmID the Java JCA algorithm ID to use
 * @param signature the computed signature value received from the signer
 * @param input the input over which the signature is computed and verified
 * @return true if the signature value computed over the input using the supplied key and algorithm ID is identical
 *         to the supplied signature value
 * @throws SecurityException thrown if the signature computation or verification process results in an error
 */
public static boolean verify(@Nonnull final PublicKey verificationKey, @Nonnull final String jcaAlgorithmID,
        @Nonnull final byte[] signature, @Nonnull final byte[] input) throws SecurityException {
    Constraint.isNotNull(verificationKey, "Public key cannot be null");
    Constraint.isNotNull(jcaAlgorithmID, "JCA algorithm ID cannot be null");
    Constraint.isNotNull(signature, "Signature data to verify cannot be null");
    Constraint.isNotNull(input, "Input data to verify cannot be null");

    Logger log = getLogger();
    log.debug("Verifying signature over input using public key of type {} and JCA algorithm ID {}",
            verificationKey.getAlgorithm(), jcaAlgorithmID);

    try {
        Signature sig = Signature.getInstance(jcaAlgorithmID);
        sig.initVerify(verificationKey);
        sig.update(input);
        return sig.verify(signature);
    } catch (GeneralSecurityException e) {
        log.error("Error during signature verification", e);
        throw new SecurityException("Error during signature verification", e);
    }
}

From source file:test.integ.be.fedict.hsm.jca.HSMProxySignatureTest.java

private void signAndVerify(X509Certificate certificate, PrivateKey privateKey, String signatureAlgo)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    Signature signature = Signature.getInstance(signatureAlgo);
    signature.initSign(privateKey);//from  ww w  .ja va  2 s .  c om

    byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();

    assertNotNull(signatureValue);

    signature = Signature.getInstance(signatureAlgo);
    signature.initVerify(certificate.getPublicKey());
    signature.update(toBeSigned);
    assertTrue(signature.verify(signatureValue));
}

From source file:in.neoandroid.neoupdate.neoUpdate.java

private boolean checkSignature(String jsonContent, String sign) {
    Log.d(TAG, "JSON: " + jsonContent);

    if (sign == null)
        return false;
    final String publicKeyStr = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq+6EG/fAE+zIdh5Wzqnf"
            + "Fo4nCf7t7eJcKyvk1lqX1MdkIi/fUs8HQ4aQ4jWLCO4M1Gkz1FQiXOnheGLV5MXY"
            + "c9GyaglsofvpA/pU5d16FybX2pCevbTzcm39eU+XlwQWOr8gh23tYD8G6uMX6sIJ"
            + "W+1k1FWdud9errMVm0YUScI+J4AV5xzN0IQ29h9IeNp6oFqZ2ByWog6OBMTUDFIW"
            + "q8oRvH0OuPv3zFR5rKwsbTYb5Da8lhUht04dLBA860Y4zeUu98huvS9jQPu2N4ns"
            + "Hf425FfDJ/wae+7eLdQo7uFb+Wvc+PO9U39e6vXQfa8ZkUoXHD0XZN4jsFcKYuJw" + "OwIDAQAB";
    try {/*w  w  w . j  a v a 2 s .  c  o  m*/
        byte keyBytes[] = Base64.decode(publicKeyStr.getBytes(), Base64.NO_WRAP);

        X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PublicKey publicKey = kf.generatePublic(publicSpec);

        Signature signer = Signature.getInstance("SHA1withRSA");
        signer.initVerify(publicKey);
        signer.update(jsonContent.getBytes(), 0, jsonContent.length());

        return signer.verify(Base64.decode(sign, Base64.NO_WRAP));
    } catch (Exception e) {
    }
    return false;
}

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

@Test
public void testOK() throws Exception {
    com.vmware.identity.sts.idm.Authenticator idmAuth = EasyMock
            .createMock(com.vmware.identity.sts.idm.Authenticator.class);

    final PrincipalId principalIdc13d = new PrincipalId(name, "acme.com");

    EasyMock.expect(idmAuth.authenticate(EasyMock.isA(X509Certificate[].class))).andReturn(principalIdc13d);
    EasyMock.replay(idmAuth);//  ww w  .j  av  a 2s. c  o  m

    final Authenticator authenticator = new UserCertAuthenticator(idmAuth);

    final SecurityHeaderType header = new SecurityHeaderType();
    final UserCertificateTokenType userCertiticateToken = new UserCertificateTokenType();
    BinarySecurityTokenType binarySecurityToken = new BinarySecurityTokenType();
    binarySecurityToken.setValueType(X509_CERTIFICATE_TYPE);
    binarySecurityToken.setEncodingType(ENCODING_TYPE_BASE64);
    // base64 encode the x509 certificate
    binarySecurityToken.setValue(new String(Base64.encodeBase64(x509Certificate.getEncoded())));
    userCertiticateToken.setUserCertificate(binarySecurityToken);

    userCertiticateToken.setSignatureInfo(signedInfo);
    userCertiticateToken.setSignatureAlgorithm(SignatureAlgorithmType.SHA_256_WITH_RSA);

    SignatureValueType signatureValueType = new SignatureValueType();
    Signature dsa = Signature.getInstance("SHA256withRSA");
    dsa.initSign(userPrivateKey);
    dsa.update(signedInfo.getBytes());
    signatureValueType.setValue(dsa.sign());
    userCertiticateToken.setSignatureValue(signatureValueType);

    ObjectFactory objectFactory = new ObjectFactory();
    header.getAny().add(objectFactory.createUserCertificateToken(userCertiticateToken));

    final Result authResult = authenticator.authenticate(newReq(header));
    Assert.assertNotNull(authResult);
    Assert.assertTrue(authResult.completed());
    Assert.assertEquals(principalIdc13d, authResult.getPrincipalId());
    Assert.assertEquals(Result.AuthnMethod.SMARTCARD, authResult.getAuthnMethod());

    EasyMock.verify(idmAuth);
}

From source file:com.aqnote.shared.cryptology.asymmetric.DSA.java

/**
 * content??//from w  ww.jav  a 2 s.c  om
 * 
 * @param content ?
 * @param signature ??
 * @param keyPairName key pair
 * @return ??<code>true</code>
 */
public boolean verify(byte[] content, String signature, String keyPairName) throws RuntimeException {
    KeyPairEntry entry = (KeyPairEntry) keyPairs.get(keyPairName);
    if (entry == null || entry.publicKey == null) {
        return false;
    }

    try {
        byte[] signed = Base64.decodeBase64(signature);

        if (log.isDebugEnabled()) {
            log.debug("Java signature[length=" + signed.length + "]: " + toHexString(signed));
        }

        Signature sign = Signature.getInstance(ALGORITHM);
        sign.initVerify(entry.publicKey);
        sign.update((byte[]) content);

        return sign.verify(signed);
    } catch (InvalidKeyException e) {
        throw new RuntimeException("Could not check content", e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Could not check content", e);
    } catch (SignatureException e) {
        throw new RuntimeException("Could not check content", e);
    }
}

From source file:com.torresbueno.RSAEncryptionDecryptionUtil.java

public boolean verifySignWithSHA1withRSA(byte[] data, byte[] signatureBytes, PublicKey publicKey)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initVerify(publicKey);/*from  ww w.  j  a va2s . c  o m*/
    sig.update(data);
    return sig.verify(signatureBytes);
}