java的公钥跟私钥使用不一样的文档格式。公钥使用pem格式,去掉文档的头尾说明。编码用X509而不是pkcs8。
JAVA RSA使用的私钥不是pem格式,如果是openssl生成的通用文件,请执行下面命令转换成der文件。
openssl pkcs8 -topk8 -inform PEM -outform DER -in private.pem -out private.der-nocrypt
下面是完整的加密类。
import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import org.apache.commons.codec.binary.Base64; import javax.crypto.Cipher; public class RSAUtil { private PrivateKey privateKey; public RSAUtil() throws Exception{ getPrivateKey(); } private void getPrivateKey() throws Exception{ File file = new File(getClass().getClassLoader().getResource("pkcs8_private.der").getFile()); FileInputStream fileInputStream = new FileInputStream(file); DataInputStream dataInputStream = new DataInputStream(fileInputStream); byte[] keyBytes = new byte[(int)file.length()]; dataInputStream.readFully(keyBytes); dataInputStream.close(); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); this.privateKey = keyFactory.generatePrivate(keySpec); } public String decryptString(String cipherTextString) throws Exception{ Base64 base64 = new Base64(); byte[] cipherText = base64.decode(cipherTextString); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, this.privateKey); byte[] plainText = cipher.doFinal(cipherText); String plainTextString = new String(plainText); return plainTextString; } }