网站使用算法生成密钥对" SHA256withECDSA"和曲线" prime192v1"让我下载本地存储在名为" PublicKey.cer"的文件中的公钥。
现在,我尝试读取密钥并对文本进行签名验证。签名由同一网站使用私钥生成。
这是我的代码,试图全部完成。
public class SecurityTest {
private static PublicKey getPublicKeyFromFile() {
try {
FileInputStream fin = new FileInputStream("D:\\PublicKey.cer");
CertificateFactory f = CertificateFactory.getInstance("X.509");
Certificate certificate = f.generateCertificate(fin);
PublicKey pk = certificate.getPublicKey();
return pk;
}
catch (IOException ioe) {
ioe.printStackTrace();
}
catch (CertificateException ce) {
ce.printStackTrace();
}
return null;
}
public static String sign(String plainText, PrivateKey privateKey) throws Exception {
Signature privateSignature = Signature.getInstance("SHA256withECDSA");
privateSignature.initSign(privateKey);
privateSignature.update(plainText.getBytes(UTF_8));
byte[] signature = privateSignature.sign();
return Base64.getEncoder().encodeToString(signature);
}
public static boolean verify(String plainText, String signature, PublicKey publicKey) throws Exception {
Signature publicSignature = Signature.getInstance("SHA256withECDSA");
publicSignature.initVerify(publicKey);
publicSignature.update(plainText.getBytes(UTF_8));
byte[] signatureBytes = Base64.getDecoder().decode(signature);
return publicSignature.verify(signatureBytes);
}
public static void main(String[] args) {
String plainText = "Rakesh";
String signature = "MDUCGQDT+L5yUkMkNzYJG8S582JIOBFoqPRe1GICGHAcbtQW/w43yQP9Aji6Zv0aacNVb9J1ew==";
try {
if (verify(plainText, signature, getPublicKeyFromFile())) {
System.out.println(plainText + " successfully verified!");
}
else {
System.out.println("Verification failed");
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
当我运行代码时,我得到以下异常:
java.security.cert.CertificateParsingException: java.io.IOException: Only named ECParameters supported
at sun.security.x509.X509CertInfo.<init>(Unknown Source)
at sun.security.x509.X509CertImpl.parse(Unknown Source)
at sun.security.x509.X509CertImpl.<init>(Unknown Source)
at sun.security.provider.X509Factory.engineGenerateCertificate(Unknown Source)
at java.security.cert.CertificateFactory.generateCertificate(Unknown Source)
at com.justurshop.test.SecurityTest.getPublicKeyFromFile(SecurityTest.java:19)
at com.justurshop.test.SecurityTest.main(SecurityTest.java:58)
Caused by: java.io.IOException: Only named ECParameters supported
at sun.security.ec.ECParameters.engineInit(ECParameters.java:150)
at java.security.AlgorithmParameters.init(Unknown Source)
at sun.security.x509.AlgorithmId.decodeParams(Unknown Source)
at sun.security.x509.AlgorithmId.<init>(Unknown Source)
at sun.security.x509.AlgorithmId.parse(Unknown Source)
at sun.security.x509.X509Key.parse(Unknown Source)
at sun.security.x509.CertificateX509Key.<init>(Unknown Source)
at sun.security.x509.X509CertInfo.parse(Unknown Source)
... 7 more
有人可以帮忙吗?你能提供从证书文件中读取公钥的代码吗?