[英]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.我们希望 Hash 使用 java sha 256 位散列算法使用客户端数字签名的数据。
How can we add digital signature while hashing in java.我们如何在 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.秘密是 Base64 编码的密钥。 The method returns the Base64 encoded hash of the data.
该方法返回Base64编码的hash数据。 The Base64 part is optional, you can remove it if you don't need that encoding.
Base64 部分是可选的,如果您不需要该编码,可以将其删除。 This is a method I use when signing REST API calls to crypto exchanges.
这是我在签署 REST API 调用加密交换时使用的方法。
The following solution signs a String by applying an RSA PKCS#8 formatted private key.以下解决方案通过应用 RSA PKCS#8 格式的私钥对字符串进行签名。 If your code has read the private key as a text from a pem file that looks like the following example:
如果您的代码已将私钥作为文本从 pem 文件中读取,如下例所示:
-----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').然后你需要去掉第一行和最后一行以及所有的换行符('\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.如果您的 privateKey 被读取(例如从 java 密钥库),您可以删除将私钥字符串转换为
java.security.PrivateKey
ZA8CFDE6331BD59EB2AC96F8911ZB4 的代码行。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.