java SHA256 with RSA 代码
时间: 2024-11-07 20:29:54 浏览: 6
java SHA256withRSA,json数据证书加签验签
5星 · 资源好评率100%
在Java中,SHA256是一种哈希函数用于数据摘要,而RSA是一种公钥加密算法。将SHA256的结果用作RSA加密的内容通常是这样的流程:
首先,你需要生成一个SHA256摘要(hash):
```java
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public byte[] sha256(String input) {
try {
Mac sha256Hmac = Mac.getInstance("HmacSHA256");
SecretKeySpec keySpec = new SecretKeySpec("your-secret-key".getBytes(StandardCharsets.UTF_8), "HmacSHA256");
sha256Hmac.init(keySpec);
return sha256Hmac.doFinal(input.getBytes(StandardCharsets.UTF_8));
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new RuntimeException("Error generating SHA-256", e);
}
}
```
然后,你可以使用RSA加密这个摘要:
```java
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import javax.crypto.Cipher;
public String encryptWithRSA(byte[] hash, PrivateKey privateKey) {
try {
KeyFactory kf = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
PrivateKey privKey = kf.generatePrivate(privKeySpec);
Cipher cipher = Cipher.getInstance("RSA/OAEPWithSHA-256AndMGF1Padding");
cipher.init(Cipher.ENCRYPT_MODE, privKey);
byte[] encryptedHash = cipher.doFinal(hash);
return Base64.getEncoder().encodeToString(encryptedHash);
} catch (Exception e) {
throw new RuntimeException("Error encrypting with RSA", e);
}
}
```
这里的`"your-secret-key"`需要替换为实际的密钥,`privateKey`是一个RSA私钥。
阅读全文