网上搜了一圈没有合意的读取.pem文件代码,根据搜集资料整理了一份,如下代码所示。
生成.pem,这里使用2048位长度:
openssl genrsa -out private_key.pem 2048
将.pem转为.der:
openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key.pem -out private_key.der -nocrypt openssl rsa -in private_key.pem -pubout -outform DER -out public_key.der
读取public_key.der:
import java.nio.file.Files; import java.nio.file.Paths; import java.security.KeyFactory; import java.security.PublicKey; import java.security.spec.X509EncodedKeySpec; 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); } }
读取private_key.der:
import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.spec.PKCS8EncodedKeySpec; 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); } }
测试:
import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.security.PrivateKey; import java.security.PublicKey; public class RSAReadKeyTest { public static void main(String[] args) throws Exception { String text = "When and where\n" + "Join us on June 25, 2020 10:00 Pacific Daylight Time. The workshops will be livestreamed to YouTube via Google Cloud Platform in partnership with AI Huddle.\n" + "\n" + "Is this for me?\n" + "This session is especially geared for professional working data scientists. You should be comfortable with Python to build machine or deep learning models. If you’re curious how accelerators can improve your workflow, this is for you!\n" + "\n" + "Agenda\n" + "Session 1: 10:00-10:30 AM PDT\n" + "Compete in a Kaggle Competition Using TensorFlow GPUs with Chris Deotte \n" + "“Follow along as I make a simple notebook from my team‘s Gold medal solution to Bengali Handwriting Classification competition.”\n" + "\n" + "Session 2: 10:30-11:00 AM PDT \n" + "Approach (Almost) Any Deep Learning Problem Using PyTorch and TPUs with Abhishek Thakur\n" + "“Allow me to show you how to harness the power of TPUs and Pytorch to quickly train almost any model!”"; PublicKey pubKey = PublicKeyReader.get("src/gj/secure/rsa_public_key.der"); byte[] bytes = RSAUtil.encryptByPublicKey(text.getBytes(), pubKey.getEncoded()); String cipherText = toBase64(bytes); System.out.println(cipherText); PrivateKey priKey = PrivateKeyReader.get("src/gj/secure/rsa_private_key.der"); byte[] cipherBytes = fromBase64(cipherText); byte[] result = RSAUtil.decryptByPrivateKey(cipherBytes, priKey.getEncoded()); System.out.println(new String(result, StandardCharsets.UTF_8)); } public static String toBase64(byte[] bytes) { return new BASE64Encoder().encode(bytes); } public static byte[] fromBase64(String b64String) throws IOException { return new BASE64Decoder().decodeBuffer(b64String); } }
附RSAUtil.java代码:
import javax.crypto.Cipher; import java.io.ByteArrayOutputStream; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.Signature; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; /** * @author areful * Date: 2019/2/12 */ @SuppressWarnings("WeakerAccess") public class RSAUtil { public static final String KEY_ALGORITHM_RSA = "RSA"; public static final String KEY_ALGORITHM_RSA_PCKS1PADDING = "RSA/ECB/PKCS1PADDING"; public static final String SIGNATURE_ALGORITHM = "MD5withRSA"; private static final int MAX_ENCRYPT_BLOCK = 117; private static final int MAX_DECRYPT_BLOCK = 128; public static KeyPair genKeyPair() throws Exception { KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM_RSA); keyPairGen.initialize(1024); return keyPairGen.generateKeyPair(); } public static byte[] encryptByPublicKey(byte[] data, byte[] pubKey) throws Exception { Cipher cipher = Cipher.getInstance(KEY_ALGORITHM_RSA_PCKS1PADDING); cipher.init(Cipher.ENCRYPT_MODE, KeyFactory.getInstance(KEY_ALGORITHM_RSA).generatePublic(new X509EncodedKeySpec(pubKey))); return doFinal(cipher, data, data.length, true); } public static byte[] encryptByPrivateKey(byte[] data, byte[] privateKey) throws Exception { KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA); Cipher cipher = Cipher.getInstance(KEY_ALGORITHM_RSA_PCKS1PADDING); cipher.init(Cipher.ENCRYPT_MODE, keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKey))); return doFinal(cipher, data, data.length, true); } public static byte[] decryptByPublicKey(byte[] encryptedData, byte[] publicKey) throws Exception { Cipher cipher = Cipher.getInstance(KEY_ALGORITHM_RSA_PCKS1PADDING); cipher.init(Cipher.DECRYPT_MODE, KeyFactory.getInstance(KEY_ALGORITHM_RSA).generatePublic(new X509EncodedKeySpec(publicKey))); return doFinal(cipher, encryptedData, encryptedData.length, false); } public static byte[] decryptByPrivateKey(byte[] encryptedData, byte[] privateKey) throws Exception { Cipher cipher = Cipher.getInstance(KEY_ALGORITHM_RSA_PCKS1PADDING); cipher.init(Cipher.DECRYPT_MODE, KeyFactory.getInstance(KEY_ALGORITHM_RSA).generatePrivate(new PKCS8EncodedKeySpec(privateKey))); return doFinal(cipher, encryptedData, encryptedData.length, false); } public static byte[] sign(byte[] data, byte[] privateKey) throws Exception { Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initSign(KeyFactory.getInstance(KEY_ALGORITHM_RSA).generatePrivate(new PKCS8EncodedKeySpec(privateKey))); signature.update(data); return signature.sign(); } public static boolean verify(byte[] data, byte[] publicKey, byte[] sign) throws Exception { Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initVerify(KeyFactory.getInstance(KEY_ALGORITHM_RSA).generatePublic(new X509EncodedKeySpec(publicKey))); signature.update(data); return signature.verify(sign); } private static byte[] doFinal(Cipher cipher, byte[] data, int inputLen, boolean isEncryptMode) throws Exception { int maxBlockSize = isEncryptMode ? MAX_ENCRYPT_BLOCK : MAX_DECRYPT_BLOCK; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; while (inputLen - offSet > 0) { if (inputLen - offSet > maxBlockSize) { cache = cipher.doFinal(data, offSet, maxBlockSize); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * maxBlockSize; } byte[] result = out.toByteArray(); out.close(); return result; } }
原文:https://www.cnblogs.com/areful/p/13156412.html