Java 从文件加载RSA公钥

我用以下方法生成了一个私钥:

openssl genrsa [-out file] –des3

在此之后,我生成了一个公共密钥:

openssl rsa –pubout -in private.key [-out file]

我想使用私钥对某些消息进行签名,并使用诸如此类的代码对其他私钥进行验证:

public String sign(String message) throws SignatureException{

try {

Signature sign = Signature.getInstance("SHA1withRSA");

sign.initSign(privateKey);

sign.update(message.getBytes("UTF-8"));

return new String(Base64.encodeBase64(sign.sign()),"UTF-8");

} catch (Exception ex) {

throw new SignatureException(ex);

}

}

public boolean verify(String message, String signature) throws SignatureException{

try {

Signature sign = Signature.getInstance("SHA1withRSA");

sign.initVerify(publicKey);

sign.update(message.getBytes("UTF-8"));

return sign.verify(Base64.decodeBase64(signature.getBytes("UTF-8")));

} catch (Exception ex) {

throw new SignatureException(ex);

}

}

我找到了一种将私钥转换为PKCS8格式并加载它的解决方案。它可以与以下代码一起工作:

public PrivateKey getPrivateKey(String filename) throws Exception {

File f = new File(filename);

FileInputStream fis = new FileInputStream(f);

DataInputStream dis = new DataInputStream(fis);

byte[] keyBytes = new byte[(int) f.length()];

dis.readFully(keyBytes);

dis.close();

PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);

KeyFactory kf =

KeyFactory.getInstance("RSA");

return kf.generatePrivate(spec);

}

最后,我的问题是:如何从文件加载RSA公钥?

我认为也许我需要将我的公共密钥文件转换为x509格式,然后使用X509EncodedKeySpec。但是我该怎么办呢?

回答:

下面是从相关信息的链接,其扎基提供。

生成2048位RSA私钥

$ openssl genrsa -out private_key.pem 2048

将私钥转换为PKCS#8格式(以便Java可以读取)

$ openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key.pem -out private_key.der -nocrypt

以DER格式输出公共密钥部分(以便Java可以读取)

$ openssl rsa -in private_key.pem -pubout -outform DER -out public_key.der

import java.io.*;

import java.nio.*;

import java.security.*;

import java.security.spec.*;

public class PrivateKeyReader {

public static PrivateKey get(String filename)

throws Exception {

byte[] keyBytes = Files.readAllBytes(Paths.get(filename));

PKCS8EncodedKeySpec spec =

new PKCS8EncodedKeySpec(keyBytes);

KeyFactory kf = KeyFactory.getInstance("RSA");

return kf.generatePrivate(spec);

}

}

Public key

import java.io.*;

import java.nio.*;

import java.security.*;

import java.security.spec.*;

public class PublicKeyReader {

public static PublicKey get(String filename)

throws Exception {

byte[] keyBytes = Files.readAllBytes(Paths.get(filename));

X509EncodedKeySpec spec =

new X509EncodedKeySpec(keyBytes);

KeyFactory kf = KeyFactory.getInstance("RSA");

return kf.generatePublic(spec);

}

}

以上是 Java 从文件加载RSA公钥 的全部内容, 来源链接: utcz.com/qa/433903.html

回到顶部