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:org.wso2.carbon.identity.agent.onprem.userstore.security.JWTSecurityInterceptor.java

private boolean isValid(String jwtToken) {

    String[] jwtTokenValues = jwtToken.split("\\.");
    String jwtAssertion = null;//from   ww  w.j  a  v  a2 s . c  om
    byte[] jwtSignature = null;

    if (jwtTokenValues.length > 0) {
        String value = new String(base64Url.decode(jwtTokenValues[0].getBytes()));
        JSONParser parser = new JSONParser();
        try {
            jsonHeaderObject = (JSONObject) parser.parse(value);
        } catch (ParseException e) {
            log.error("Error occurred while parsing JSON header ", e);
        }
    }

    if (jwtTokenValues.length > 1) {
        jwtAssertion = jwtTokenValues[0] + "." + jwtTokenValues[1];
    }

    if (jwtTokenValues.length > 2) {
        jwtSignature = base64Url.decode(jwtTokenValues[2].getBytes());
    }

    if (jwtAssertion != null && jwtSignature != null) {

        try {
            File publicKeyFile = new File(System.getProperty(CommonConstants.CARBON_HOME),
                    File.separator + PUBLIC_KEY_LOCATION);
            InputStream inStream = new FileInputStream(publicKeyFile);

            DataInputStream dis = new DataInputStream(inStream);
            byte[] keyBytes = new byte[(int) publicKeyFile.length()];
            dis.readFully(keyBytes);
            dis.close();
            String publicKeyPEM = new String(keyBytes);
            BASE64Decoder b64 = new BASE64Decoder();
            byte[] decoded = b64.decodeBuffer(publicKeyPEM);

            X509EncodedKeySpec spec = new X509EncodedKeySpec(decoded);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            PublicKey publicKey = kf.generatePublic(spec);

            Signature signature = Signature.getInstance(getSignatureAlgorithm(jsonHeaderObject));
            signature.initVerify(publicKey);
            signature.update(jwtAssertion.getBytes());
            return signature.verify(jwtSignature);
        } catch (Exception e) {
            log.error("Error occurred while validating signature", e);
        }
    } else {
        log.warn("No signature exist in the request.");
        return false;
    }
    return false;
}

From source file:org.cesecore.keys.util.KeyTools.java

/**
 * Verify signed data with specified public key, algorith and signature
 * /* w  ww . j a  va 2  s.c o  m*/
 * @param publicKey
 *            the public key
 * @param signatureAlgorithm a valid signature algorithm
 * @param data
 *            the data to verify
 * @param signature
 *            the signature
 * @return true if the signature is ok
 */
public static boolean verifyData(final PublicKey publicKey, final String signatureAlgorithm, final byte[] data,
        final byte[] signature) throws SignatureException, NoSuchAlgorithmException, InvalidKeyException {
    final Signature signer = Signature.getInstance(signatureAlgorithm);
    signer.initVerify(publicKey);
    signer.update(data);
    return (signer.verify(signature));

}

From source file:com.floreantpos.license.FiveStarPOSLicenseManager.java

private boolean verify(byte[] message, String signature, PublicKey publicKey) throws LicenseException {
    try {//from ww w .  j  a v a 2 s.  c o  m

        Signature dsa = Signature.getInstance("SHA/DSA");
        dsa.initVerify(publicKey);
        dsa.update(message);

        byte[] decoded = Base64.getDecoder().decode(signature);
        return dsa.verify(decoded);

    } catch (Exception e) {
        throw new LicenseException("Invalid license key! Please contact our support.", e);
    }
}

From source file:mx.bigdata.sat.cfdi.CFDv3.java

public void verificar() throws Exception {
    String certStr = document.getCertificado();
    Base64 b64 = new Base64();
    byte[] cbs = b64.decode(certStr);

    X509Certificate cert = KeyLoaderFactory
            .createInstance(KeyLoaderEnumeration.PUBLIC_KEY_LOADER, new ByteArrayInputStream(cbs)).getKey();

    String sigStr = document.getSello();
    byte[] signature = b64.decode(sigStr);
    byte[] bytes = getOriginalBytes();
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initVerify(cert);
    sig.update(bytes);//from  ww  w .ja v  a 2s . com
    boolean bool = sig.verify(signature);
    if (!bool) {
        throw new Exception("Invalid signature");
    }
}

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 2s .com
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:com.vimukti.accounter.license.LicenseManager.java

private byte[] checkAndGetLicenseText(String licenseContent) {
    byte[] licenseText;
    try {//w w w . j a v a  2  s .com
        byte[] decodedBytes = Base64.decodeBase64(licenseContent.getBytes());
        ByteArrayInputStream in = new ByteArrayInputStream(decodedBytes);
        DataInputStream dIn = new DataInputStream(in);
        int textLength = dIn.readInt();
        licenseText = new byte[textLength];
        dIn.read(licenseText);
        byte[] hash = new byte[dIn.available()];
        dIn.read(hash);
        try {
            Signature signature = Signature.getInstance("SHA1withDSA");
            signature.initVerify(PUBLIC_KEY);
            signature.update(licenseText);
            if (!signature.verify(hash)) {
                throw new LicenseException("Failed to verify the license.");
            }

        } catch (InvalidKeyException e) {
            throw new LicenseException(e);
        } catch (SignatureException e) {
            throw new LicenseException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new LicenseException(e);
        }

    } catch (IOException e) {
        throw new LicenseException(e);
    }

    return licenseText;
}

From source file:org.apli.modelbeans.facturacion.cfdi.CFDv32.java

@Override
public void verificar() throws Exception {
    String certStr = document.getCertificado();
    Base64 b64 = new Base64();
    byte[] cbs = b64.decode(certStr);

    X509Certificate cert = KeyLoaderFactory
            .createInstance(KeyLoaderEnumeration.PUBLIC_KEY_LOADER, new ByteArrayInputStream(cbs)).getKey();

    String sigStr = document.getSello();
    byte[] signature = b64.decode(sigStr);
    byte[] bytes = getOriginalBytes();
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initVerify(cert);
    sig.update(bytes);//from   w w w  . j  a  va 2  s . c om
    boolean bool = sig.verify(signature);
    if (!bool) {
        throw new Exception("Invalid signature");
    }
}

From source file:com.microsoft.azure.oidc.token.impl.SimpleTokenValidator.java

@Override
public Boolean validateSignature(final Token token) {
    if (token == null) {
        throw new PreconditionException("Required parameter is null");
    }//from w  ww  .  j  a  v a  2s  . com
    if (algorithmConfigurationService.get().getAlgorithmClassMap().get(token.getAlgorithm().getName())
            .equals("HMAC")) {
        return Boolean.FALSE;
    }
    final Configuration configuration = configurationCache.load();
    if (configuration == null) {
        throw new GeneralException("Error loading configuration");
    }
    try {
        final TimeStamp now = timeStampFactory.createTimeStamp(System.currentTimeMillis() / 1000);
        if (configuration.getKey(token.getKeyName()).getNotBefore().compareTo(now) > 0) {
            return Boolean.FALSE;
        }
        final Base64 decoder = new Base64();
        final BigInteger exponent = new BigInteger(1,
                decoder.decode(configuration.getKey(token.getKeyName()).getExponent().getValue()));
        final BigInteger modulus = new BigInteger(1,
                decoder.decode(configuration.getKey(token.getKeyName()).getSecret().getValue()));
        final RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus, exponent);
        final KeyFactory keyFactory = KeyFactory.getInstance(
                algorithmConfigurationService.get().getAlgorithmClassMap().get(token.getAlgorithm().getName()));
        final PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
        final Signature sig = Signature.getInstance(
                algorithmConfigurationService.get().getAlgorithmMap().get(token.getAlgorithm().getName()));
        sig.initVerify(pubKey);
        sig.update(token.getPayload().getValue().getBytes());
        return sig.verify(decoder.decode(token.getSignature().getValue()));
    } catch (NoSuchAlgorithmException | InvalidKeySpecException | SignatureException | InvalidKeyException e) {
        LOGGER.error(e.getMessage(), e);
        return Boolean.FALSE;
    }
}

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

/**
 * content??/*ww  w.j a v a 2s. c o  m*/
 * 
 * @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:org.esupportail.papercut.services.PayBoxService.java

public boolean checkPayboxSignature(String queryString, String signature) {

    String sData = queryString.substring(0, queryString.lastIndexOf("&"));

    try {//from w ww . j  a  v  a 2s. c o m
        Signature sig = Signature.getInstance("SHA1WithRSA");
        byte[] sigBytes = Base64.decodeBase64(signature.getBytes());
        sig.initVerify(payboxPublicKey);
        sig.update(sData.getBytes());
        boolean signatureOk = sig.verify(sigBytes);
        if (!signatureOk) {
            log.error("Erreur lors de la vrification de la signature, les donnes ne correspondent pas.");
            log.error(sData);
            log.error(signature);
        }
        return signatureOk;
    } catch (Exception e) {
        log.warn("Pb when checking SSL signature of Paybox", e);
        return false;
    }
}