简体   繁体   中英

How to Hash a given data using clients digital signature in java SHA 256 Algorithm

We want to Hash a data using clients digital signature using java sha 256 bit hashing algorithm.

How can we add digital signature while hashing in java.

If I'm understanding correctly, you want to sign some data. Here is a sample method:

    public static String encode(String dataToEncode, String secret) throws InvalidKeyException, NoSuchAlgorithmException {
       byte[] decodedSecret = Base64.getDecoder().decode(secret);
       SecretKeySpec keySpec = new SecretKeySpec(decodedSecret, "HmacSHA256");
       Mac sha256 = Mac.getInstance("HmacSHA256");
       sha256.init(keySpec);
       return Base64.getEncoder().encodeToString(sha256.doFinal(dataToEncode.getBytes()));
}

The secret is the Base64 encoded secret key. The method returns the Base64 encoded hash of the data. The Base64 part is optional, you can remove it if you don't need that encoding. This is a method I use when signing REST API calls to crypto exchanges.

The following solution signs a String by applying an RSA PKCS#8 formatted private key. If your code has read the private key as a text from a pem file that looks like the following example:

-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDRxFWXGYDG8zKw
ihIS+Ydh/nWX9NwkFTKMRjH8BQ78ZEnXrnGJHvd+dI+zEiRo7rLuDXMOjsnhIR/O
....
+wqssDAApq+CiPcBnn0x2Vw=
-----END PRIVATE KEY-----

Then you need to strip out the first and last lines and all the new line characters ('\n'). If your privateKey is read (from a java keystore for example) you can remove the lines of code that convert the String of private key into java.security.PrivateKey object.

    private static String signSHA256RSA(String inputStr, String inputKey) throws Exception {
        String key = inputKey.replaceAll("-----END PRIVATE KEY-----", "")
                .replaceAll("-----BEGIN PRIVATE KEY-----", "")
                .replaceAll("\n", "");
        byte[] keyBytes = Base64.getDecoder().decode(key);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = kf.generatePrivate(spec);
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(privateKey);
        signature.update(inputStr.getBytes("UTF-8"));
        byte[] s = signature.sign();
        return Base64.getEncoder().encodeToString(s);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM