BouncyCastle是一个广泛使用的Java库,提供了大量的加密算法实现,包括RSA公钥和私钥的生成、解析和使用。RSA是一种非对称加密算法,广泛应用于数据加密和数字签名。
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.io.FileInputStream;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.X509EncodedKeySpec;
public class RSAKeyReader {
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
FileInputStream fis = new FileInputStream("path/to/publicKey.pem");
byte[] keyBytes = new byte[fis.available()];
fis.read(keyBytes);
fis.close();
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyBytes);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyInfo.getEncoded());
KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
System.out.println("Public Key: " + publicKey);
}
}
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.X509EncodedKeySpec;
public class RSAKeyReader {
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
String publicKeyString = "-----BEGIN PUBLIC KEY-----\n" +
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...\n" +
"-----END PUBLIC KEY-----";
byte[] keyBytes = publicKeyString.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "")
.replaceAll("\\s", "")
.getBytes();
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyBytes);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyInfo.getEncoded());
KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
System.out.println("Public Key: "": " + publicKey);
}
}
Security.addProvider(new BouncyCastleProvider());
添加提供者。"RSA"
。"BC"
。通过以上步骤,你可以成功从Java/Kotlin文件或字符串中读取RSA公钥。
领取专属 10元无门槛券
手把手带您无忧上云