在Java中,可以使用java.security
包中的PKCS系列类来实现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
函数: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();
}
}
注意:在实际应用中,私钥应该妥善保管,不要直接存储在文件中。这里仅为了演示目的。在实际场景中,可以考虑使用KeyStore来安全地存储和管理私钥。