Rsa读取pem公钥和私钥

1.把pem文件用text打开,把开头和结尾的begin和end内容删去,只留下字符串内容;
2.用流读取文件中的字符串;
3.用以下代码生成公钥和私钥对象;

	public static PublicKey string2PublicKey(String pubStr) throws Exception{
		byte[] keyBytes = base642Byte(pubStr);
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		PublicKey publicKey = keyFactory.generatePublic(keySpec);
		return publicKey;
	}
	
	//将Base64编码后的私钥转换成PrivateKey对象
	public static PrivateKey string2PrivateKey(String priStr) throws Exception{
		byte[] keyBytes = base642Byte(priStr);
		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
		return privateKey;
	}

备注:
读取私钥前要加上:
java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
运行服务,不然运行会出现algid parse error, not a sequence错误。

你可能感兴趣的:(后端)