RSA算法类:
import org.apache.tomcat.util.codec.binary.Base64; import javax.crypto.Cipher; 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; public class RSAEncrypt { private static final int KEY_SIZE = 512; private static final String RSA_ALGORITHM = "RSA"; /** * 随机生成密钥对 * @return 密钥对map */ public static Map<String, String> getKeyPair() { KeyPairGenerator keyPairGenerator = null; try { keyPairGenerator = KeyPairGenerator.getInstance(RSA_ALGORITHM); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } keyPairGenerator.initialize(KEY_SIZE); KeyPair keyPair = keyPairGenerator.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); HashMap<String, String> keyPairMap = new HashMap<>(); keyPairMap.put("publicKey", encodeBase64(publicKey.getEncoded())); keyPairMap.put("privateKey", encodeBase64(privateKey.getEncoded())); return keyPairMap; } /** * RSA加密 * @param str 需要加密的字符串 * @param publicKey 加密的公钥 */ public static String encrypt(String str, String publicKey) { byte[] publicKeyBytes = decodeBase46(publicKey); String outStr = null; try { KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM); PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyBytes)); Cipher cipher = Cipher.getInstance(RSA_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, pubKey); byte[] bytes = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)); outStr = encodeBase64(bytes); } catch (Exception e) { e.printStackTrace(); } return outStr; } /** * * @param str 需要解码的字符串(是经过base64编码的) * @param privateKey 解码用的私钥 * @return */ public static String decrypt(String str, String privateKey) { byte[] bytes = decodeBase46(str); byte[] privateKeyBytes = decodeBase46(privateKey); String outStr = null; try { KeyFactory instance = KeyFactory.getInstance(RSA_ALGORITHM); PrivateKey priKey = instance.generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes)); Cipher cipher = Cipher.getInstance(RSA_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, priKey); outStr = new String(cipher.doFinal(bytes)); } catch (Exception e) { e.printStackTrace(); } return outStr; } /** * base64编码 * @param encoded 需要编码的字节数组 * @return base64字符串 */ private static String encodeBase64(byte[] encoded) { return Base64.encodeBase64String(encoded); } /** * base64解码成字节数组 * @param base64String base64字符串 * @return 解码出的字节数组 */ private static byte[] decodeBase46(String base64String) { return Base64.decodeBase64(base64String); } }
介绍: