如何用java代码实现 openssl dgst -sha256 -sign
时间: 2024-03-05 15:54:53 浏览: 151
使用Java代码实现相当于使用Java的加密库进行签名,可以使用Java Security API中的Signature类。下面是一个示例代码:
```java
import java.io.*;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
public class Signer {
public static void main(String[] args) throws Exception {
String data = "Hello World";
String privateKeyPath = "/path/to/private.key";
byte[] privateKeyBytes = readAllBytes(new FileInputStream(privateKeyPath));
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(privateKey);
signature.update(data.getBytes());
byte[] signatureBytes = signature.sign();
System.out.println("Signature: " + bytesToHex(signatureBytes));
}
private static byte[] readAllBytes(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
int n;
while ((n = input.read(buffer)) != -1) {
output.write(buffer, 0, n);
}
return output.toByteArray();
}
private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
private static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int i = 0; i < bytes.length; i++) {
int v = bytes[i] & 0xFF;
hexChars[i * 2] = HEX_ARRAY[v >>> 4];
hexChars[i * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
}
}
```
这个示例代码使用RSA算法进行签名,并使用SHA256算法对数据进行哈希。其中,data是待签名的数据,privateKeyPath是私钥文件的路径。签名结果会以十六进制字符串形式输出。
阅读全文