在Java中,可以使用java.security
包中的PKCS系列類來實(shí)現(xiàn)PKCS簽名
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
public static KeyPair generateRSAKeyPair() throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
return keyPairGenerator.generateKeyPair();
}
public static PrivateKey readPrivateKeyFromFile(String privateKeyPath) throws Exception {
byte[] privateKeyBytes = Files.readAllBytes(Paths.get(privateKeyPath));
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePrivate(privateKeySpec);
}
public static String signPKCS(String content, PrivateKey privateKey) throws Exception {
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(privateKey);
signature.update(content.getBytes());
byte[] signedBytes = signature.sign();
return Base64.getEncoder().encodeToString(signedBytes);
}
public static String signAndReturnWithOriginalContent(String filePath, PrivateKey privateKey) throws Exception {
String content = new String(Files.readAllBytes(Paths.get(filePath)));
String signature = signPKCS(content, privateKey);
return content + "\n" + signature;
}
signAndReturnWithOriginalContent
函數(shù):public static void main(String[] args) {
try {
String filePath = "path/to/your/file.txt";
PrivateKey privateKey = readPrivateKeyFromFile("path/to/your/private_key.pem");
String result = signAndReturnWithOriginalContent(filePath, privateKey);
System.out.println("Original content:\n" + result);
} catch (Exception e) {
e.printStackTrace();
}
}
注意:在實(shí)際應(yīng)用中,私鑰應(yīng)該妥善保管,不要直接存儲(chǔ)在文件中。這里僅為了演示目的。在實(shí)際場(chǎng)景中,可以考慮使用KeyStore來安全地存儲(chǔ)和管理私鑰。