赞
踩
RSA是1977年由罗纳德·李维斯特(Ron Rivest)、阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的。所以这个算法取自他们三位的姓名首字母。
RSA是目前最具有影响力的公钥加密算法,它的原理基于一个简单的数论事实:将两个大质数相乘十分简单,但是想要对它们的乘积进行分解却异常困难。这里的乘积一般公开作为密钥。只要密钥的长度足够大(一般1024位,也有2048位),基本上不可能从公钥信息推出私钥信息。
RSA使用“密钥对”对数据进行加密解密,在加密解密前需要先生成公钥(public key)和私钥(private key)
公钥:用于加密数据
私钥:用于解密数据
RSA中加密和加签有什么区别?
加密:公钥放在客户端,使用公钥对数据进行加密,服务端拿到数据后用私钥进行解密。
加签:私钥放在客户端,使用私钥对数据进行加签,服务端拿到数据后用公钥进行验签。
前者完全为了加密。后者主要是为了防止恶意攻击,让服务器辨别哪些是真正的请求,哪些是恶意的请求。
RSA是非对称加密算法,因为加密和解密的密钥不是同一个。
用到的常用字符串提取出来
- private final static String RSA_ALGORITHM = "RSA";
- private final static String SIGNATURE_ALGORITHM = "MD5withRSA";
- private final static String RSA_PUBLIC_KEY = "RSAPublicKey";
- private final static String RSA_PRIVATE_KEY = "RSAPrivateKey";
base64对二进制数据进行编码解码
- public static String encodeBase64(byte[] binaryData) {
- Encoder encoder = Base64.getEncoder();
- return encoder.encodeToString(binaryData);
- }
-
- public static byte[] decodeBase64(String encoded) {
- Decoder decoder = Base64.getDecoder();
- return decoder.decode(encoded);
- }
获取公钥私钥键值对
- public static Map<String,Object> getKey() throws NoSuchAlgorithmException{
- // 因为只存公钥和私钥,所以指明Map的长度是2
- Map<String,Object> keyMap = new HashMap<String,Object>(2);
-
- // 获取RSA算法实例
- KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(RSA_ALGORITHM);
-
- // 1024代表密钥二进制位数
- keyPairGen.initialize(1024);
-
- // 产生KeyPair工厂
- KeyPair keyPair = keyPairGen.generateKeyPair();
- RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
- RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
-
- keyMap.put(RSA_PUBLIC_KEY, publicKey);
- keyMap.put(RSA_PRIVATE_KEY, privateKey);
-
- return keyMap;
- }
加密解密
- /**
- * 使用私钥对数据进行加密
- */
- public static byte[] encryptPrivateKey(byte[] binaryData, String privateKey) throws Exception {
- byte[] keyBytes = decodeBase64(privateKey);
- PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
-
- // 获取RSA算法实例
- KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
- Key priKey = keyFactory.generatePrivate(keySpec);
-
- // 初始化加密器
- Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
- cipher.init(Cipher.ENCRYPT_MODE, priKey);
- return cipher.doFinal(binaryData);
- }
-
- /**
- * 使用公钥对数据进行加密
- */
- public static byte[] encryptPublicKey(byte[] binaryData, String publicKey) throws Exception {
- byte[] keyBytes = decodeBase64(publicKey);
- X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
-
- // 获取RSA算法实例
- KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
- Key pubKey = keyFactory.generatePublic(keySpec);
-
- // 初始化加密器
- Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
- cipher.init(Cipher.ENCRYPT_MODE, pubKey);
- return cipher.doFinal(binaryData);
- }
-
- /**
- * 使用私钥对数据进行解密
- */
- public static byte[] decryptPrivateKey(byte[] binaryData, String privateKey) throws Exception {
- byte[] keyBytes = decodeBase64(privateKey);
- PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
-
- // 获取RSA算法实例
- KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
- Key priKey = keyFactory.generatePrivate(keySpec);
-
- // 初始化加密器
- Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
- cipher.init(Cipher.DECRYPT_MODE, priKey);
- return cipher.doFinal(binaryData);
- }
-
- /**
- * 使用公钥对数据进行解密
- */
- public static byte[] decryptPublicKey(byte[] binaryData, String publicKey) throws Exception {
- byte[] keyBytes = decodeBase64(publicKey);
- X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
-
- // 获取RSA算法实例
- KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
- Key pubKey = keyFactory.generatePublic(x509KeySpec);
-
- // 初始化加密器
- Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
- cipher.init(Cipher.DECRYPT_MODE, pubKey);
- return cipher.doFinal(binaryData);
- }
RSA还可以对指定内容进行加签验签
- /**
- * 使用私钥对数据进行签名
- */
- public static String sign(byte[] binaryData, String privateKey)
- throws Exception {
- byte[] keyBytes = decodeBase64(privateKey);
- PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
-
- // 获取RSA算法实例
- KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
- PrivateKey priKey = keyFactory.generatePrivate(keySpec);
-
- // 获取签名算法
- Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
- signature.initSign(priKey);
- signature.update(binaryData);
- return encodeBase64(signature.sign());
- }
-
-
- /**
- * 使用公钥对数据签名进行验证
- */
- public static boolean verify(byte[] binaryData, String publicKey, String sign)
- throws Exception {
- byte[] keyBytes = decodeBase64(publicKey);
- X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
-
- // 获取RSA算法实例
- KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
- PublicKey pubKey = keyFactory.generatePublic(keySpec);
-
- // 获取签名算法
- Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
- signature.initVerify(pubKey);
- signature.update(binaryData);
- return signature.verify(decodeBase64(sign));
- }
- public static void main(String[] args) throws Exception {
- // 1.获取公钥私钥
- Map<String,Object> map = getKey();
- System.out.println("公钥:"+getPublicKey(map));
- System.out.println("私钥:"+getPrivateKey(map));
-
- String content = "未加密数据";
-
- System.out.println("============ 分隔符 ===========");
- // 2.使用私钥加密
- byte[] encodeContent = encryptPrivateKey(content.getBytes(),getPrivateKey(map));
- System.out.println("私钥加密后的数据:"+new String(encodeContent));
-
- // 3.使用公钥解密
- byte[] decodeContent = decryptPublicKey(encodeContent,getPublicKey(map));
- System.out.println("公钥解密后的数据:"+new String(decodeContent));
-
- System.out.println("============ 分隔符 ===========");
- // 4.使用公钥加密
- byte[] encodeContent2 = encryptPublicKey(content.getBytes(),getPublicKey(map));
- System.out.println("公钥加密后的数据:"+new String(encodeContent2));
-
- // 5.使用私钥解密
- byte[] decodeContent2 = decryptPrivateKey(encodeContent2,getPrivateKey(map));
- System.out.println("私钥解密后的数据:"+new String(decodeContent2));
-
- System.out.println("============ 分隔符 ===========");
- // 6.加签
- String sign = sign(content.getBytes(),getPrivateKey(map));
- System.out.println("加签后的数据:"+sign);
-
- // 7.验签
- boolean result = verify(content.getBytes(),getPublicKey(map),sign);
- System.out.println("验签结果:"+result);
- }
运行结果
- 公钥:MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQChRJmN8gv7te/xvgo55KvYlEGDGoVbDWF0rG6jCgw3pw/zGa/4R
- GGmRwOcBbecSYNZZUlQaqYZkta7m3ti0Z3o8ZhbYYMbtWI3eWs9MbsioCDSIsg/Jf6CHHS3HhjjQboQkKs7Q/1emn
- E01Sa9kYApoGVEXAtSY4kuxNidVjklgwIDAQAB
- 私钥:MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKFEmY3yC/u17/G+Cjnkq9iUQYMahVsNYXSsbqMKD
- DenD/MZr/hEYaZHA5wFt5xJg1llSVBqphmS1rube2LRnejxmFthgxu1Yjd5az0xuyKgINIiyD8l/oIcdLceGONBuh
- CQqztD/V6acTTVJr2RgCmgZURcC1JjiS7E2J1WOSWDAgMBAAECgYBEoH278wH4dr8KH7YYVuBuRQDv+qw/SB1t2ic
- myJLUaAqYiBjjTK5FZTj6/0/YeUwlEb42M3xFq8AnjA3gypUoqXFpHaRDbfZFanryDUQFLQ/C9141exJkX7QmHS5t
- 99WRSnPbVoLzRVc4F8FBu76HEN4uzOVl9akkaQXqbbJ6EQJBAPJFAzLcBnSRsSHXZt5hB9hjanUiTBbMQ4H2YL4Om
- ouX7uQOnMfW2PuGAE0+WMq/V4AgfLu0/yIG8s3XEFjsXosCQQCqaF512kQOW+YjlTpCE3KpXcZ9U7t5+G33r4MmA1
- 7lML5miTwEC+wo0sHDVL2yG0/CPk1itLd7yW2FqGEgGWvpAkEAmwn3JhEQQIEL7jA+sIk/0AavFg7AysYlXYIiHv6
- RgEvWoTOIuYqQiUYT41rGz9jrUh94M1d8/nWb5IaA+6coSQJBAJc3Pnt+UF4dlr+EsMnp0BoTKQwVvYuitJLSoKKe
- 4xqmgo8iwKsmmU4wl9jp3duq+L/54Vnx29BxEktE+8ssQ+ECQFeZ0CzBdPWMs6Hmsujgn5qS/FOlbyu4qckU5lAqN
- 3DGxmtdvWne2NZYzCFCWT9zBlWd0dXKccmq+ehrBWrd+Fc=
- ============ 分隔符 ===========
- 私钥加密后的数据:!�h��^��0�IȕoBa�k(�/��ΜA��ǩ%��u�|
- �R�Z�l���y��<����$|
- ��!M�S��&n�u{���p�E5�WG�����=>�S��U���=��UT��W�Q�6�|D�{
- 公钥解密后的数据:未加密数据
- ============ 分隔符 ===========
- 公钥加密后的数据:}>d��J�)Ԙe_A�G ��kۈ���Js�����R=�����ax�v9���m�[z
- ��b�NT�cѓب_0�薹���UZ����
- IDJ|gI���.A��|�N�x�&$��k�t F
- 私钥解密后的数据:未加密数据
- ============ 分隔符 ===========
- 加签后的数据:ZMxyo9gBoPnauK1uZx8Pb+jH9jn0gIA5D5uWFmimb3S1HuMrWl6DnQuIgv/dwemHJREnkdE2F65sR0qxLNAr0REdW
- GakYPEj0UfbdMUzrduC2rxKIyX5jOTt3RpBIM1bK3sJISSmheK0Tb7msYTrA2VKscNM1gAHqIbnaMNeDwY=
- 验签结果:true
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。