package com.moon.server.helper; import org.apache.commons.codec.binary.Base64; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.io.ClassPathResource; import javax.crypto.Cipher; import java.io.*; import java.nio.charset.StandardCharsets; import java.security.*; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.HashMap; import java.util.Map; @SuppressWarnings("ALL") public class RsaHelper { private static String privateKey; private static String publicKey; private static final String KEY_ALGORITHM = "RSA"; private static final int DEFAULT_RSA_KEY_SIZE = 1024; private final static Log log = LogFactory.getLog(RsaHelper.class); public static void generate() { Map result = generateRsaKey(DEFAULT_RSA_KEY_SIZE); System.out.println("公钥为:" + result.get("publicKey")); System.out.println("私钥为:" + result.get("privateKey")); } public static String getPrivateKey() throws IOException { if (privateKey == null) { InputStream inPrivate = new ClassPathResource("config" + File.separator + "rsa_private_key.txt").getInputStream(); privateKey = inputStream2String(inPrivate); inPrivate.close(); } return privateKey; } public static String getPublicKey() throws IOException { if (publicKey == null) { InputStream inPrivate = new ClassPathResource("config" + File.separator + "rsa_public_key.txt").getInputStream(); publicKey = inputStream2String(inPrivate); inPrivate.close(); } return publicKey; } public static String readFile(String fileName) throws IOException { File file = new File(fileName); BufferedReader br = new BufferedReader(new FileReader(file)); StringBuilder result = new StringBuilder(); String line = null; while ((line = br.readLine()) != null) { result.append(System.lineSeparator() + line); } br.close(); return result.toString(); } private static String inputStream2String(InputStream is) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int i = -1; while ((i = is.read()) != -1) { baos.write(i); } String str = baos.toString(); baos.close(); return str; } public static Map generateRsaKey(int keySize) { Map result = new HashMap<>(2); try { KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); keyPairGen.initialize(keySize, new SecureRandom()); KeyPair keyPair = keyPairGen.generateKeyPair(); String pub = new String(Base64.encodeBase64(keyPair.getPublic().getEncoded())); result.put("publicKey", pub); String pri = new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded())); result.put("privateKey", pri); } catch (Exception ex) { log.error(ex.getMessage(), ex); } return result; } public static String decrypt(String str) throws Exception { byte[] inputByte = Base64.decodeBase64(str.getBytes(StandardCharsets.UTF_8)); byte[] decoded = Base64.decodeBase64(getPrivateKey()); RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded)); // RSA/ECB/NoPadding Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, priKey); String outStr = new String(cipher.doFinal(inputByte)); return outStr; } public static String encrypt(String str) throws Exception { byte[] decoded = Base64.decodeBase64(getPublicKey()); RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded)); // RSA/ECB/NoPadding Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, pubKey); String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes(StandardCharsets.UTF_8))); return outStr; } }