Java实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 |
import org.apache.commons.codec.binary.Base64; import javax.crypto.Cipher; import java.io.ByteArrayOutputStream; import java.security.Key; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; 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; /** * RSA Helper * * @author 冯龙生 */ public class RsaUtil { /** * 加密算法 */ public static final String ALGORITHM = "RSA"; /** * 填充方式 */ public static final String PADDING_FORMAT = "RSA/ECB/PKCS1Padding"; /** * 明文块最大值 */ private static final int MAX_ENCRYPT_BLOCK = 117; /** * 密文块最大值 */ private static final int MAX_DECRYPT_BLOCK = 128; /** * 生成密钥对 */ public static Map<String, String> generateKeyPair() throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM); keyPairGenerator.initialize(1024); KeyPair keyPair = keyPairGenerator.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); Map<String, String> keyMap = new HashMap<>(2); keyMap.put("RSAPublicKey", Base64.encodeBase64String(publicKey.getEncoded())); keyMap.put("RSAPrivateKey", Base64.encodeBase64String(privateKey.getEncoded())); return keyMap; } /** * 公钥加密 * * @param text 明文 * @param publicKey 公钥 * @param charset 字符编码 * @return 加密后的字符串(base64) */ public static String encrypt(String text, String publicKey, String charset) throws Exception { byte[] data = text.getBytes(charset); byte[] keyBytes = Base64.decodeBase64(publicKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM); Key key = keyFactory.generatePublic(x509KeySpec); // 对数据加密 Cipher cipher = Cipher.getInstance(PADDING_FORMAT); cipher.init(Cipher.ENCRYPT_MODE, key); int length = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 对数据分段加密 while (length - offSet > 0) { int len = Math.min(length - offSet, MAX_ENCRYPT_BLOCK); cache = cipher.doFinal(data, offSet, len); out.write(cache, 0, cache.length); i++; offSet = i * MAX_ENCRYPT_BLOCK; } byte[] cipherBytes = out.toByteArray(); out.close(); return Base64.encodeBase64String(cipherBytes); } /** * 私钥解密 * * @param ciphertext 密文(base64) * @param privateKey 私钥 * @param charset 字符编码 */ public static String decrypt(String ciphertext, String privateKey, String charset) throws Exception { byte[] data = Base64.decodeBase64(ciphertext); byte[] keyBytes = Base64.decodeBase64(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM); Key key = keyFactory.generatePrivate(pkcs8KeySpec); Cipher cipher = Cipher.getInstance(PADDING_FORMAT); cipher.init(Cipher.DECRYPT_MODE, key); int length = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; while (length - offSet > 0) { int len = Math.min(length - offSet, MAX_DECRYPT_BLOCK); cache = cipher.doFinal(data, offSet, len); out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } out.close(); return out.toString(charset); } /** * 私钥加密 * * @param text 明文 * @param privateKey 私钥 * @param charset 字符编码 * @return 加密后的字符串(base64) */ public static String encryptWithPrivateKey(String text, String privateKey, String charset) throws Exception { byte[] data = text.getBytes(charset); byte[] keyBytes = Base64.decodeBase64(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM); Key key = keyFactory.generatePrivate(pkcs8KeySpec); // 对数据加密 Cipher cipher = Cipher.getInstance(PADDING_FORMAT); cipher.init(Cipher.ENCRYPT_MODE, key); int length = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 对数据分段加密 while (length - offSet > 0) { int len = Math.min(length - offSet, MAX_ENCRYPT_BLOCK); cache = cipher.doFinal(data, offSet, len); out.write(cache, 0, cache.length); i++; offSet = i * MAX_ENCRYPT_BLOCK; } byte[] cipherBytes = out.toByteArray(); out.close(); return Base64.encodeBase64String(cipherBytes); } /** * 公钥解密 * * @param ciphertext 密文(base64) * @param publicKey 私钥 * @param charset 字符编码 */ public static String decryptWithPublicKey(String ciphertext, String publicKey, String charset) throws Exception { byte[] data = Base64.decodeBase64(ciphertext); byte[] keyBytes = Base64.decodeBase64(publicKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM); Key key = keyFactory.generatePublic(x509KeySpec); Cipher cipher = Cipher.getInstance(PADDING_FORMAT); cipher.init(Cipher.DECRYPT_MODE, key); int length = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; while (length - offSet > 0) { int len = Math.min(length - offSet, MAX_DECRYPT_BLOCK); cache = cipher.doFinal(data, offSet, len); out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } out.close(); return out.toString(charset); } public static void main(String[] args) throws Exception { String charset = "UTF-8"; String text = "123"; String pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCkNHKlskd5VJDRnPRH6vdEvvtvOPX1QsFYoOSOcjttOhueVsUawJ3DTykLEDQx0RJf7UF3t6YZDDxZV7z1cdFotZeHPZrcL8nyol/3Vze1/izaVcCcqOS+eGJ3cmi0mzwQLdRFv+43u/WdCptoP14buJ3kZd2oGO6eMZvaJa7D7QIDAQAB"; String priKey = "MIICeQIBADANBgkqhkiG9w0BAQEFAASCAmMwggJfAgEAAoGBAKQ0cqWyR3lUkNGc9Efq90S++2849fVCwVig5I5yO206G55WxRrAncNPKQsQNDHREl/tQXe3phkMPFlXvPVx0Wi1l4c9mtwvyfKiX/dXN7X+LNpVwJyo5L54YndyaLSbPBAt1EW/7je79Z0Km2g/Xhu4neRl3agY7p4xm9olrsPtAgMBAAECgYEAkDNi7zJV5C4ok3vjZnjotx2EzxLVpJIAG2YH8TRODcj20iFfLPQ0V31gDNApFgqFuWowkQLdQafmI4uSbHWMsJoOhe68Bvy6iwhyqchN7bJ+myTQq/ckB6g1Atv7/l1Y8tE3fsSC2OwwMZ70KTbJNOM3Ad5uur8fh1EcDdL554ECQQD380Hg593ezTO14WjvljOnkGz23nE/ElW6aeFb7fJmdWsdZTwqyM9KMkgM+hV0DuEwfuvEWfyLafcAuJTSGn/NAkEAqYksXyZ3dxZONIhCzRDpQGQ9ovCYfWgkIAIQmMA8aTjIGLOJr+YHp3WrYpEcBDGsMihw17T+eFJmt74qTwn0oQJBALSeIxMuVFUErfKD7Oj6RU5+yqFakKwdMw3EK0HIJ5ezWP/kyttvxHCMCChL1Gzime+1xREXa/wyiJeh3ebfHtECQQCRs00J/SIgm2/cn9phKI59g2ihVwqGhHC/fWbMEDIa7+yvpeTH4fZkCbGgBTvBsvrdJHpON8OWnqKeePUddl3hAkEAxYf67P3iitxmNaQw44zbs9SFWRnLZrGGPCruw4VUSWI83yaKArJdHSaDCH0x6kwUlYl8LBsZwqp+Dzlakc1TRg=="; System.out.println("==================================================公钥加密,私钥解密======================================================"); String ciphertext = encrypt(text, pubKey, charset); System.out.println("明文:" + text); System.out.println("加密:" + ciphertext); System.out.println("解密:" + decrypt(ciphertext, priKey, charset)); System.out.println(); System.out.println("==================================================私钥加密,公钥解密======================================================"); ciphertext = encryptWithPrivateKey(text, priKey, charset); System.out.println("明文:" + text); System.out.println("加密:" + ciphertext); System.out.println("解密:" + decryptWithPublicKey(ciphertext, pubKey, charset)); System.out.println(); Map<String, String> keys = generateKeyPair(); System.out.println("==================================================生成Public Key======================================================"); System.out.println(keys.get("RSAPublicKey")); System.out.println(); System.out.println("==================================================生成Private Key======================================================"); System.out.println(keys.get("RSAPrivateKey")); } } |
C#实现
注意:由于C#未实现私钥加密,需要借助第三方类库来实现。
nuget安装:BouncyCastle.Cryptography
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 |
using System; using System.IO; using System.Text; using System.Collections.Generic; using System.Security.Cryptography; using Org.BouncyCastle.Security; public class RsaUtil { private static readonly string PADDING_FORMAT = "RSA/ECB/PKCS1Padding"; /// <summary> /// 生成密钥对 /// </summary> public static Dictionary<string, string> GenerateKeyPair() { var rsa = new RSACryptoServiceProvider(); var keyDict = new Dictionary<string, string>(); keyDict.Add("RSAPublicKey", rsa.ToXmlString(false)); keyDict.Add("RSAPrivateKey", rsa.ToXmlString(true)); return keyDict; } /// <summary> /// 公钥加密 /// </summary> /// <param name="text">明文</param> /// <param name="publicKey">公钥</param> /// <returns>密文</returns> public static string Encrypt(string text, string publicKey) { // rsa实例 var rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(publicKey); var blockSize = (rsa.KeySize / 8) - 11; // 加密块大小 var bytes = Encoding.UTF8.GetBytes(text); var length = bytes.Length; var offSet = 0; // 游标 var i = 0; byte[] cache; using var ms = new MemoryStream(); while (length - offSet > 0) { var len = length - offSet > blockSize ? blockSize : length - offSet; var temp = new byte[len]; Array.Copy(bytes, offSet, temp, 0, len); cache = rsa.Encrypt(temp, false); ms.Write(cache, 0, cache.Length); i++; offSet = i * blockSize; } var cipherBytes = ms.ToArray(); return Convert.ToBase64String(cipherBytes); } /// <summary> /// 私钥解密 /// </summary> /// <param name="ciphertext">密文</param> /// <param name="privateKey">私钥</param> /// <returns>明文</returns> public static string Decrypt(string ciphertext, string privateKey) { // rsa实例 var rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(privateKey); var blockSize = rsa.KeySize / 8; var bytes = Convert.FromBase64String(ciphertext); var length = bytes.Length; // 分段解密 var offSet = 0; // 游标 var i = 0; byte[] cache; using var ms = new MemoryStream(); while (length - offSet > 0) { var len = length - offSet > blockSize ? blockSize : length - offSet; var temp = new byte[len]; Array.Copy(bytes, offSet, temp, 0, len); cache = rsa.Decrypt(temp, false); ms.Write(cache, 0, cache.Length); i++; offSet = i * blockSize; } var textBytes = ms.ToArray(); return Encoding.UTF8.GetString(textBytes); } /// <summary> /// 私钥加密 /// </summary> /// <param name="text">明文</param> /// <param name="privateKey">私钥</param> /// <returns>密文</returns> public static string EncryptWithPrivateKey(string text, string privateKey) { // rsa实例 var rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(privateKey); var blockSize = (rsa.KeySize / 8) - 11; var bytes = Encoding.UTF8.GetBytes(text); var length = bytes.Length; // 转换密钥 var keyPair = DotNetUtilities.GetKeyPair(rsa); var cipher = CipherUtilities.GetCipher(PADDING_FORMAT); cipher.Init(true, keyPair.Private); // 分段加密 var offSet = 0; // 游标 var i = 0; byte[] cache; using var ms = new MemoryStream(); while (length - offSet > 0) { var len = length - offSet > blockSize ? blockSize : length - offSet; var temp = new byte[len]; Array.Copy(bytes, offSet, temp, 0, len); cache = cipher.DoFinal(temp); ms.Write(cache, 0, cache.Length); i++; offSet = i * blockSize; } var cipherBytes = ms.ToArray(); return Convert.ToBase64String(cipherBytes); } /// <summary> /// 公钥解密 /// </summary> /// <param name="ciphertext">密文</param> /// <param name="privateKey">公钥</param> /// <returns>明文</returns> public static string DecryptWithPublicKey(string ciphertext, string privateKey) { // rsa实例 var rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(privateKey); var exportParameters = rsa.ExportParameters(false); var blockSize = rsa.KeySize / 8; var bytes = Convert.FromBase64String(ciphertext); var length = bytes.Length; // 转换密钥 var rsaPublicKey = DotNetUtilities.GetRsaPublicKey(exportParameters); var cipher = CipherUtilities.GetCipher(PADDING_FORMAT); cipher.Init(false, rsaPublicKey); // 分段解密 var offSet = 0; // 游标 var i = 0; byte[] cache; using var ms = new MemoryStream(); while (length - offSet > 0) { var len = length - offSet > blockSize ? blockSize : length - offSet; var temp = new byte[len]; Array.Copy(bytes, offSet, temp, 0, len); cache = cipher.DoFinal(temp); ms.Write(cache, 0, cache.Length); i++; offSet = i * blockSize; } var textBytes = ms.ToArray(); return Encoding.UTF8.GetString(textBytes); } public static void Main(string[] args) { string text = "123"; string pubKey = "<RSAKeyValue><Modulus>pDRypbJHeVSQ0Zz0R+r3RL77bzj19ULBWKDkjnI7bTobnlbFGsCdw08pCxA0MdESX+1Bd7emGQw8WVe89XHRaLWXhz2a3C/J8qJf91c3tf4s2lXAnKjkvnhid3JotJs8EC3URb/uN7v1nQqbaD9eG7id5GXdqBjunjGb2iWuw+0=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"; string priKey = "<RSAKeyValue><Modulus>pDRypbJHeVSQ0Zz0R+r3RL77bzj19ULBWKDkjnI7bTobnlbFGsCdw08pCxA0MdESX+1Bd7emGQw8WVe89XHRaLWXhz2a3C/J8qJf91c3tf4s2lXAnKjkvnhid3JotJs8EC3URb/uN7v1nQqbaD9eG7id5GXdqBjunjGb2iWuw+0=</Modulus><Exponent>AQAB</Exponent><P>9/NB4Ofd3s0zteFo75Yzp5Bs9t5xPxJVumnhW+3yZnVrHWU8KsjPSjJIDPoVdA7hMH7rxFn8i2n3ALiU0hp/zQ==</P><Q>qYksXyZ3dxZONIhCzRDpQGQ9ovCYfWgkIAIQmMA8aTjIGLOJr+YHp3WrYpEcBDGsMihw17T+eFJmt74qTwn0oQ==</Q><DP>tJ4jEy5UVQSt8oPs6PpFTn7KoVqQrB0zDcQrQcgnl7NY/+TK22/EcIwIKEvUbOKZ77XFERdr/DKIl6Hd5t8e0Q==</DP><DQ>kbNNCf0iIJtv3J/aYSiOfYNooVcKhoRwv31mzBAyGu/sr6Xkx+H2ZAmxoAU7wbL63SR6TjfDlp6innj1HXZd4Q==</DQ><InverseQ>xYf67P3iitxmNaQw44zbs9SFWRnLZrGGPCruw4VUSWI83yaKArJdHSaDCH0x6kwUlYl8LBsZwqp+Dzlakc1TRg==</InverseQ><D>kDNi7zJV5C4ok3vjZnjotx2EzxLVpJIAG2YH8TRODcj20iFfLPQ0V31gDNApFgqFuWowkQLdQafmI4uSbHWMsJoOhe68Bvy6iwhyqchN7bJ+myTQq/ckB6g1Atv7/l1Y8tE3fsSC2OwwMZ70KTbJNOM3Ad5uur8fh1EcDdL554E=</D></RSAKeyValue>"; Console.WriteLine("==================================================公钥加密,私钥解密======================================================"); string ciphertext = Encrypt(text, pubKey); Console.WriteLine("明文:" + text); Console.WriteLine("加密:" + ciphertext); Console.WriteLine("解密:" + Decrypt(ciphertext, priKey)); Console.WriteLine(); Console.WriteLine("==================================================私钥加密,公钥解密======================================================"); ciphertext = EncryptWithPrivateKey(text, priKey); Console.WriteLine("明文:" + text); Console.WriteLine("加密:" + ciphertext); Console.WriteLine("解密:" + DecryptWithPublicKey(ciphertext, pubKey)); Console.WriteLine(); Dictionary<string, string> keys = GenerateKeyPair(); Console.WriteLine("==================================================生成Public Key======================================================"); Console.WriteLine(keys["RSAPublicKey"]); Console.WriteLine(); Console.WriteLine("==================================================生成Private Key======================================================"); Console.WriteLine(keys["RSAPrivateKey"]); } } |