Example usage for java.security Signature update

List of usage examples for java.security Signature update

Introduction

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

Prototype

public final void update(ByteBuffer data) throws SignatureException 

Source Link

Document

Updates the data to be signed or verified using the specified ByteBuffer.

Usage

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);/*from   ww w.ja  v a 2s . com*/
    sig.update(bytes);
    boolean bool = sig.verify(signature);
    if (!bool) {
        throw new Exception("Invalid signature");
    }
}

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

/**
 * Sign provided data with specified private key and algortihm
 * /*from w  w  w . ja v  a2  s.  c  om*/
 * @param privateKey
 *            the private key
 * @param signatureAlgorithm a valid signature algorithm
 * @param data
 *            the data to sign
 * @return the signature
 */
public static byte[] signData(final PrivateKey privateKey, final String signatureAlgorithm, final byte[] data)
        throws SignatureException, NoSuchAlgorithmException, InvalidKeyException {
    final Signature signer = Signature.getInstance(signatureAlgorithm);
    signer.initSign(privateKey);
    signer.update(data);
    return (signer.sign());
}

From source file:com.cedarsoft.crypt.X509Support.java

/**
 * <p>sign</p>/*from ww w .j  a va  2  s .c o  m*/
 *
 * @param plainText an array of byte.
 * @return a com.cedarsoft.crypt.Signature object.
 *
 * @throws GeneralSecurityException
 *          if any.
 */
@Nonnull
public com.cedarsoft.crypt.Signature sign(@Nonnull byte[] plainText) throws GeneralSecurityException {
    Signature signature = Signature.getInstance(SHA_256_WITH_RSA);
    signature.initSign(getPrivateKey());

    signature.update(plainText);
    return new com.cedarsoft.crypt.Signature(signature.sign());
}

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

/**
 * Verify signed data with specified public key, algorith and signature
 * /*  w ww .j  a v  a 2s .  co  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   w ww  . j ava 2s. 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: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   w  ww.  j a va2  s  .  co m*/
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.adito.security.pki.dsa.SshDssPrivateKey.java

/**
 *
 *
 * @param data//ww w  .  j  av  a  2  s  .c  o m
 *
 * @return
 *
 * @throws InvalidSshKeySignatureException
 */
public byte[] generateSignature(byte[] data) throws InvalidSignatureException {
    try {
        Signature sig = Signature.getInstance("SHA1withDSA");
        sig.initSign(prvkey);

        sig.update(data);

        byte[] signature = sig.sign();
        byte[] decoded = new byte[40];
        SimpleASNReader asn = new SimpleASNReader(signature);
        asn.getByte();
        asn.getLength();
        asn.getByte();

        byte[] r = asn.getData();
        asn.getByte();

        byte[] s = asn.getData();

        if (r.length >= 20) {
            System.arraycopy(r, r.length - 20, decoded, 0, 20);
        } else {
            System.arraycopy(r, 0, decoded, 20 - r.length, r.length);
        }

        if (s.length >= 20) {
            System.arraycopy(s, s.length - 20, decoded, 20, 20);
        } else {
            System.arraycopy(s, 0, decoded, 20 + (20 - s.length), s.length);
        }

        if (log.isDebugEnabled()) {
            log.debug("s length is " + String.valueOf(s.length));
            log.debug("r length is " + String.valueOf(r.length));

            String str = "";

            for (int i = 0; i < signature.length; i++) {
                str += (Integer.toHexString(signature[i] & 0xFF) + " ");
            }

            log.debug("Java signature is " + str);
            str = "";

            for (int i = 0; i < decoded.length; i++) {
                str += (Integer.toHexString(decoded[i] & 0xFF) + " ");
            }

            log.debug("SSH signature is " + str);
        }

        ByteArrayWriter baw = new ByteArrayWriter();
        baw.writeString(getAlgorithmName());
        baw.writeBinaryString(decoded);

        return baw.toByteArray();
    } catch (Exception e) {
        throw new InvalidSignatureException(e);
    }
}

From source file:com.tenduke.example.scribeoauth.JwtLoginServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request//from ww  w  .j  ava2s  . co m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    //
    String idToken = request.getParameter(PARAMETER_NAME_ID_TOKEN);
    //
    // check that parameter is ~OK.
    if (idToken != null && !idToken.isEmpty() && idToken.indexOf(".") > 0) {
        //
        // JWT has 3 elements, which are separated by a "." char.
        String[] jwtElements = idToken.split("\\.");
        if (jwtElements.length == 3) {
            //
            String header = jwtElements[0];
            String body = jwtElements[1];
            byte[] dataBytes = new StringBuilder(header).append(".").append(body).toString().getBytes("UTF-8");
            byte[] signatureBytes = Base64.decodeBase64(jwtElements[2]);
            //
            try {
                //
                java.security.Signature signature = java.security.Signature.getInstance("SHA256withRSA");
                signature.initVerify(publicKey);
                //
                signature.update(dataBytes);
                //
                if (signature.verify(signatureBytes)) {
                    //
                    doLogin(request, response, new String(Base64.decodeBase64(body), "UTF-8"));
                }
            } catch (InvalidKeyException | NoSuchAlgorithmException | SignatureException ex) {
                //
                throw new ServletException(
                        "No way, basic RSA based key handling and signature verification failed...", ex);
            }
        } else {
            //
            throw new ServletException("Unexpected JWT data");
        }
    } else {
        //
        throw new ServletException("Request parameter: " + PARAMETER_NAME_ID_TOKEN + " not given");
    }
}

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 a 2s . 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.p2pvpn.tools.AdvProperties.java

/**
 * Sign this properties with the given key.
 * @param keyName name of the key/*w ww. j  ava2  s . c  o m*/
 * @param privateKey the key used for the signature
 */
public void sign(String keyName, PrivateKey privateKey) {
    try {
        byte[] data = asBytes();
        Signature signature = CryptoUtils.getSignature();
        signature.initSign(privateKey, CryptoUtils.getSecureRandom());
        signature.update(data);
        setPropertyBytes(keyName, signature.sign());
    } catch (Throwable ex) {
        Logger.getLogger("").log(Level.SEVERE, null, ex);
        assert false;
    }
}