我是靠谱客的博主 等待灰狼,最近开发中收集的这篇文章主要介绍https理解之RSA加密解密,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

最近复习https的加密原理,一时兴起决定做个RSA加密解密的小例子,以加深理解:

package com.example;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class CreateSecrteKey {
public class Keys {
}
public static final String KEY_ALGORITHM = "RSA";
//public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
private static final String PUBLIC_KEY = "RSAPublicKey";
private static final String PRIVATE_KEY = "RSAPrivateKey";
//获得公钥
public static String getPublicKey(Map<String, Object> keyMap) throws Exception {
//获得map中的公钥对象 转为key对象
Key key = (Key) keyMap.get(PUBLIC_KEY);
//byte[] publicKey = key.getEncoded();
//编码返回字符串
return Base64.encodeBase64String(key.getEncoded());
}
//获得私钥
public static String getPrivateKey(Map<String, Object> keyMap) throws Exception {
//获得map中的私钥对象 转为key对象
Key key = (Key) keyMap.get(PRIVATE_KEY);
//byte[] privateKey = key.getEncoded();
//编码返回字符串
return Base64.encodeBase64String(key.getEncoded());
}
/**
* RSA公钥加密
*
* @param str
*
加密字符串
* @param publicKey
*
公钥
* @return
* @return 密文
* @throws Exception
*
加密过程中的异常信息
*/
public static String encrypt(String str, RSAPublicKey publicKey ) {
//base64编码的公钥
Cipher cipher;
try {
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
return outStr;
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
/**
* RSA私钥解密
*
* @param str
*
加密字符串
* @param privateKey
*
私钥
* @return 铭文
* @throws Exception
*
解密过程中的异常信息
*/
public static String decrypt(String str, Key privateKey) throws Exception{
//64位解码加密后的字符串,解码字符串
byte[] meesageByte = Base64.decodeBase64(str.getBytes("UTF-8"));
//RSA解密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte [] decypted = cipher.doFinal(meesageByte);
String outStr = new String(decypted,"UTF-8");
return outStr;
}
//map对象中存放公私钥
public static Map<String, Object> initKey() throws Exception {
//获得对象 KeyPairGenerator 参数 RSA 1024个字节
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(1024);
//通过对象 KeyPairGenerator 获取对象KeyPair
KeyPair keyPair = keyPairGen.generateKeyPair();
//通过对象 KeyPair 获取RSA公私钥对象RSAPublicKey RSAPrivateKey
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
//公私钥对象存入map中
Map<String, Object> keyMap = new HashMap<String, Object>(2);
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
}
public static void main(String[] args) {
Map<String, Object> keyMap;
try {
keyMap = initKey();
String publicKey = getPublicKey(keyMap);
System.out.println("公钥:");
System.out.println(publicKey);
String privateKey = getPrivateKey(keyMap);
System.out.println("私钥:");
System.out.println(privateKey);
System.out.println("明文:");
String message = "12点发动总攻,请提前作好准备。";
System.out.println(message);
String encodeMessage = encrypt(message, ((RSAPublicKey)keyMap.get(PUBLIC_KEY)));
System.out.println("密文:");
System.out.println(encodeMessage);
String decodeMessage= decrypt(encodeMessage,((RSAPrivateKey)keyMap.get(PRIVATE_KEY)));
System.out.println("解密:");
System.out.println(new String(decodeMessage));
} catch (Exception e) {
e.printStackTrace();
}
}
}
​

运行结果:

公钥:
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCg9LMXCyURFo+nzP2CgQgCyNzzprVQo3fpwlatJuV0V3BPR0hO6i4NLJ5VKEDdstTXS/lLxW262iVbBU1kZZE6tNgfImJ3f4bzYXnCaWs7LjtJCDwPgKJFRLR79JFQUngHDynsghdJN2eJ3luyf0IB6CsILUHLtl++jM4ppX/+RQIDAQAB
私钥:
MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAKD0sxcLJREWj6fM/YKBCALI3POmtVCjd+nCVq0m5XRXcE9HSE7qLg0snlUoQN2y1NdL+UvFbbraJVsFTWRlkTq02B8iYnd/hvNhecJpazsuO0kIPA+AokVEtHv0kVBSeAcPKeyCF0k3Z4neW7J/QgHoKwgtQcu2X76Mzimlf/5FAgMBAAECgYEAlzImRYA/mpTB75PdlEkXOF5tSCgS7KQSUbEv8Mm4A5jbtG02nILZLaD7Pu1oOZny3CfPEAFuuXaQXrdVYvkR+Te9N/YUYmD3i3o3VTi2JwFGeTJL0Y9a3FKtMhbEASBxCnwOQG0mXpgYz96ctxczFKJ0noRJ232REkFjDr/UXKECQQD+IeHtuB4qctDl0QA2fF0P1u6krsyjY+bIUO2SuLJ/80Ytq+fM0d5YvpzSl2pU6AJnwoVxkDblJ3u5f+94ej9JAkEAoiOEdBl4bU0iqbBN3XCvFxrHD03BblOQxC41tKre+1C7nsCBDaY1RV1005fp40sIajOe73jHf1PD2kpQTYk7HQJAZ3zkxCl2H1MiPnQd4hJC03BzPhzwuJi2IlzSYi1Ug0ZODcszWfUc1obI1flTE8BnOlm8fcJ8mFS7zY6LtkQSAQJBAIbil1liqx37EsAqTMzQ5siI3Vts62OWH5QlgUZY9IIMytkp+vLY9+5J7lvtQIV3sXtwkGNWjljt3bxnIGEwrj0CQQDk8X7LbM9JdC8A7Ny2isqT5UsoB6i9W9XV8NTzhBCT3IIPBdGHFU8YDQuTYBnCp9fWdpjZ13WErhskOn3Ifyh+
明文:
12点发动总攻,请提前作好准备。
密文:
VUvpC2L484qhdMmNW7vr5jfXD5PRso+K1/dfM8S81Fr0BwePIG4oJolerMfMKKikkKAk/HncaK4oN+oeCH65DFb1chhpCXxvJIrkMWWgHgqko/s4JLt3wBN7U4pVcLjY5XU4WNhKa1vdUGcZHoaRVa0ziQiIQfSE3pAUN3zTrkk=
解密:
12点发动总攻,请提前作好准备。

上面用到了一个Base64的jar包,下载地址:https://commons.apache.org/proper/commons-codec/download_codec.cgi

 

最后

以上就是等待灰狼为你收集整理的https理解之RSA加密解密的全部内容,希望文章能够帮你解决https理解之RSA加密解密所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(94)

评论列表共有 0 条评论

立即
投稿
返回
顶部