• 前后端加密解密工具类(前端rsa加密,后端进行解密)


    前端代码中传入后端工具类返回的两个加密串信息进行加密

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>什么是对象以及对象属性title>
    8. head>
    9. <body>
    10. <script type="text/javascript" charset="utf-8" src="../03-code/14-学成在线/RSA.js">script>
    11. <script>
    12. // 对象也是一种数据类型,保存数据同时可以更直观的描述事物
    13. // 1. 定义对象属性
    14. RSAUtils.setMaxDigits(200);
    15. var key = new RSAUtils.getKeyPair('010001', "", '00951e7a698c4dc31fe292a67c12c94a56f1ba409945b6175470d696b167a073e4fe099f52fbaa041e5be0a473dfe5818ea6a2f9c1b4db5e66fa26d6a31575deb488fda96128e143b9e3a4131972ebb2d8e6e092a464725dfaa441268b787820b5fe915ee1676ef139ae001aa8235d3325689445963f32789087927f6194c5a6f9');
    16. console.log(key)
    17. var wad= RSAUtils.encryptedString(key,"123456".split("").reverse().join(""))
    18. console.log(wad)
    19. let pig = {
    20. sex: '女',
    21. age: 4,
    22. uname: '佩奇',
    23. weight: 12.6
    24. }
    25. // 2. 访问对象属性 对象.属性
    26. console.log(pig.age) // 4
    27. console.log(pig.weight) // 12.6
    28. script>
    29. body>
    30. html>

    附录工具类

    1. package com.atguigu.yygh.cmn.Rsa;
    2. import java.io.File;
    3. import java.io.FileInputStream;
    4. import java.io.FileOutputStream;
    5. import java.io.ObjectInputStream;
    6. import java.io.ObjectOutputStream;
    7. import java.math.BigInteger;
    8. import java.security.InvalidParameterException;
    9. import java.security.KeyFactory;
    10. import java.security.KeyPair;
    11. import java.security.KeyPairGenerator;
    12. import java.security.NoSuchAlgorithmException;
    13. import java.security.PrivateKey;
    14. import java.security.Provider;
    15. import java.security.PublicKey;
    16. import java.security.SecureRandom;
    17. import java.security.interfaces.RSAPrivateKey;
    18. import java.security.interfaces.RSAPublicKey;
    19. import java.security.spec.InvalidKeySpecException;
    20. import java.security.spec.RSAPrivateKeySpec;
    21. import java.security.spec.RSAPublicKeySpec;
    22. import java.util.Date;
    23. import java.util.HashMap;
    24. import javax.crypto.Cipher;
    25. import org.apache.commons.codec.DecoderException;
    26. import org.apache.commons.codec.binary.Hex;
    27. import org.apache.commons.io.FileUtils;
    28. import org.apache.commons.io.IOUtils;
    29. import org.apache.commons.lang.StringUtils;
    30. import org.apache.commons.lang.time.DateFormatUtils;
    31. import org.bouncycastle.jce.provider.BouncyCastleProvider;
    32. import org.slf4j.Logger;
    33. import org.slf4j.LoggerFactory;
    34. /**
    35. *
    36. * RSA?
    37. * @author Administrator
    38. *
    39. */
    40. public class RSAUtils {
    41. public static void main(String[] args) {
    42. HashMap map = new HashMap<>();
    43. map.put("path","9065336912");
    44. //todo 这块是重载方法 可以传一个map,也可以不穿,最后返回的是两个字符串,前端用该字符串加密密码,后端解密就行
    45. PublicKeyMap publicKeyMap = RSAUtils.getPublicKeyMap();
    46. System.out.println(publicKeyMap);
    47. System.out.println(RSAUtils.decryptStringByJs("2e5ea42abd7a3c06d07e6cc1d08a824455994bc30cb9d34541b7878e1bcd01c4a168ce3c98216a29b13eadab84889134ee4f52bdaabd68ec1171a29a021058854e659bf00c808a24c04fab85b4e08e6ff5da32c9abc47501b212ee98f7f09f2164d9d19ca7abce8763d6ae7ec608752af7d3a92517ff535f53afb54a78ce7143"));
    48. }
    49. private static final Logger LOGGER = LoggerFactory.getLogger(RSAUtils.class);
    50. /** ?????? */
    51. private static final String ALGORITHOM = "RSA";
    52. /**??????????????????????? */
    53. private static final String RSA_PAIR_FILENAME = "/__RSA_PAIR.txt";
    54. /** ?????С */
    55. private static final int KEY_SIZE = 1024;
    56. /** ?????????????? */
    57. private static final Provider DEFAULT_PROVIDER = new BouncyCastleProvider();
    58. private static KeyPairGenerator keyPairGen = null;
    59. private static KeyFactory keyFactory = null;
    60. /** ??????????? */
    61. private static KeyPair oneKeyPair = null;
    62. private static File rsaPairFile = null;
    63. static {
    64. try {
    65. keyPairGen = KeyPairGenerator.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
    66. keyFactory = KeyFactory.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
    67. } catch (NoSuchAlgorithmException ex) {
    68. LOGGER.error(ex.getMessage());
    69. }
    70. rsaPairFile = new File(getRSAPairFilePath());
    71. }
    72. private RSAUtils() {
    73. }
    74. /**
    75. * ?????????RSA??????
    76. */
    77. private static synchronized KeyPair generateKeyPair() {
    78. try {
    79. keyPairGen.initialize(KEY_SIZE, new SecureRandom(DateFormatUtils.format(new Date(),"yyyyMMdd").getBytes()));
    80. oneKeyPair = keyPairGen.generateKeyPair();
    81. saveKeyPair(oneKeyPair);
    82. return oneKeyPair;
    83. } catch (InvalidParameterException ex) {
    84. LOGGER.error("KeyPairGenerator does not support a key length of " + KEY_SIZE + ".", ex);
    85. } catch (NullPointerException ex) {
    86. LOGGER.error("RSAUtils#KEY_PAIR_GEN is null, can not generate KeyPairGenerator instance.",ex);
    87. }
    88. return null;
    89. }
    90. /**
    91. * ????????/???????????????·????
    92. */
    93. private static String getRSAPairFilePath() {
    94. String urlPath = RSAUtils.class.getResource("/").getPath();
    95. return (new File(urlPath).getParent() + RSA_PAIR_FILENAME);
    96. }
    97. /**
    98. * ????????????????????????? {@code true}?????? {@code false}??
    99. */
    100. private static boolean isCreateKeyPairFile() {
    101. // ???????????????
    102. boolean createNewKeyPair = false;
    103. if (!rsaPairFile.exists() || rsaPairFile.isDirectory()) {
    104. createNewKeyPair = true;
    105. }
    106. return createNewKeyPair;
    107. }
    108. /**
    109. * ???????RSA????????????????档
    110. *
    111. * @param keyPair ????????????
    112. */
    113. private static void saveKeyPair(KeyPair keyPair) {
    114. FileOutputStream fos = null;
    115. ObjectOutputStream oos = null;
    116. try {
    117. fos = FileUtils.openOutputStream(rsaPairFile);
    118. oos = new ObjectOutputStream(fos);
    119. oos.writeObject(keyPair);
    120. } catch (Exception ex) {
    121. ex.printStackTrace();
    122. } finally {
    123. IOUtils.closeQuietly(oos);
    124. IOUtils.closeQuietly(fos);
    125. }
    126. }
    127. /**
    128. * ????RSA??????
    129. */
    130. public static KeyPair getKeyPair() {
    131. // ?????ж??????????????????????????
    132. if (isCreateKeyPairFile()) {
    133. // ???????????????????????????档
    134. return generateKeyPair();
    135. }
    136. if (oneKeyPair != null) {
    137. return oneKeyPair;
    138. }
    139. return readKeyPair();
    140. }
    141. // ?????????????????
    142. private static KeyPair readKeyPair() {
    143. FileInputStream fis = null;
    144. ObjectInputStream ois = null;
    145. try {
    146. fis = FileUtils.openInputStream(rsaPairFile);
    147. ois = new ObjectInputStream(fis);
    148. oneKeyPair = (KeyPair) ois.readObject();
    149. return oneKeyPair;
    150. } catch (Exception ex) {
    151. ex.printStackTrace();
    152. } finally {
    153. IOUtils.closeQuietly(ois);
    154. IOUtils.closeQuietly(fis);
    155. }
    156. return null;
    157. }
    158. /**
    159. * ???????????????????????????RSA??????????
    160. *
    161. * @param modulus ?????
    162. * @param publicExponent ????????
    163. * @return RSA??ù??????
    164. */
    165. public static RSAPublicKey generateRSAPublicKey(byte[] modulus, byte[] publicExponent) {
    166. RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(new BigInteger(modulus),
    167. new BigInteger(publicExponent));
    168. try {
    169. return (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);
    170. } catch (InvalidKeySpecException ex) {
    171. LOGGER.error("RSAPublicKeySpec is unavailable.", ex);
    172. } catch (NullPointerException ex) {
    173. LOGGER.error("RSAUtils#KEY_FACTORY is null, can not generate KeyFactory instance.", ex);
    174. }
    175. return null;
    176. }
    177. /**
    178. * ???????????????????????????RSA??????????
    179. *
    180. * @param modulus ?????
    181. * @param privateExponent ????????
    182. * @return RSA?????????
    183. */
    184. public static RSAPrivateKey generateRSAPrivateKey(byte[] modulus, byte[] privateExponent) {
    185. RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(new BigInteger(modulus),
    186. new BigInteger(privateExponent));
    187. try {
    188. return (RSAPrivateKey) keyFactory.generatePrivate(privateKeySpec);
    189. } catch (InvalidKeySpecException ex) {
    190. LOGGER.error("RSAPrivateKeySpec is unavailable.", ex);
    191. } catch (NullPointerException ex) {
    192. LOGGER.error("RSAUtils#KEY_FACTORY is null, can not generate KeyFactory instance.", ex);
    193. }
    194. return null;
    195. }
    196. /**
    197. * ?????????16???????????????????????????RSA??????????
    198. *
    199. * @param modulus ?????
    200. * @param privateExponent ????????
    201. * @return RSA?????????
    202. */
    203. public static RSAPrivateKey getRSAPrivateKey(String hexModulus, String hexPrivateExponent) {
    204. if(StringUtils.isBlank(hexModulus) || StringUtils.isBlank(hexPrivateExponent)) {
    205. if(LOGGER.isDebugEnabled()) {
    206. LOGGER.debug("hexModulus and hexPrivateExponent cannot be empty. RSAPrivateKey value is null to return.");
    207. }
    208. return null;
    209. }
    210. byte[] modulus = null;
    211. byte[] privateExponent = null;
    212. try {
    213. modulus = Hex.decodeHex(hexModulus.toCharArray());
    214. privateExponent = Hex.decodeHex(hexPrivateExponent.toCharArray());
    215. } catch(DecoderException ex) {
    216. LOGGER.error("hexModulus or hexPrivateExponent value is invalid. return null(RSAPrivateKey).");
    217. }
    218. if(modulus != null && privateExponent != null) {
    219. return generateRSAPrivateKey(modulus, privateExponent);
    220. }
    221. return null;
    222. }
    223. /**
    224. * ?????????16???????????????????????????RSA??????????
    225. *
    226. * @param modulus ?????
    227. * @param publicExponent ????????
    228. * @return RSA??ù??????
    229. */
    230. public static RSAPublicKey getRSAPublidKey(String hexModulus, String hexPublicExponent) {
    231. if(StringUtils.isBlank(hexModulus) || StringUtils.isBlank(hexPublicExponent)) {
    232. if(LOGGER.isDebugEnabled()) {
    233. LOGGER.debug("hexModulus and hexPublicExponent cannot be empty. return null(RSAPublicKey).");
    234. }
    235. return null;
    236. }
    237. byte[] modulus = null;
    238. byte[] publicExponent = null;
    239. try {
    240. modulus = Hex.decodeHex(hexModulus.toCharArray());
    241. publicExponent = Hex.decodeHex(hexPublicExponent.toCharArray());
    242. } catch(DecoderException ex) {
    243. LOGGER.error("hexModulus or hexPublicExponent value is invalid. return null(RSAPublicKey).");
    244. }
    245. if(modulus != null && publicExponent != null) {
    246. return generateRSAPublicKey(modulus, publicExponent);
    247. }
    248. return null;
    249. }
    250. /**
    251. * ???????????????????
    252. *
    253. * @param publicKey ??????????
    254. * @param data ???????????
    255. * @return ???????????
    256. */
    257. public static byte[] encrypt(PublicKey publicKey, byte[] data) throws Exception {
    258. Cipher ci = Cipher.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
    259. ci.init(Cipher.ENCRYPT_MODE, publicKey);
    260. return ci.doFinal(data);
    261. }
    262. /**
    263. * ???????????????????
    264. *
    265. * @param privateKey ??????????
    266. * @param data ???????????
    267. * @return ??????
    268. */
    269. public static byte[] decrypt(PrivateKey privateKey, byte[] data) throws Exception {
    270. Cipher ci = Cipher.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
    271. ci.init(Cipher.DECRYPT_MODE, privateKey);
    272. return ci.doFinal(data);
    273. }
    274. /**
    275. * ??????????????????????????
    276. *

    277. * ?? {@code publicKey} ? {@code null}?????? {@code plaintext} ? {@code null} ??? {@code
    278. * null}??
    279. *
    280. * @param publicKey ??????????
    281. * @param plaintext ???????
    282. * @return ????????????????
    283. */
    284. public static String encryptString(PublicKey publicKey, String plaintext) {
    285. if (publicKey == null || plaintext == null) {
    286. return null;
    287. }
    288. byte[] data = plaintext.getBytes();
    289. try {
    290. byte[] en_data = encrypt(publicKey, data);
    291. return new String(Hex.encodeHex(en_data));
    292. } catch (Exception ex) {
    293. LOGGER.error(ex.getCause().getMessage());
    294. }
    295. return null;
    296. }
    297. /**
    298. * ?????????????????????????
    299. *

    300. * ??{@code plaintext} ? {@code null} ??? {@code null}??
    301. *
    302. * @param plaintext ???????
    303. * @return ????????????????
    304. */
    305. public static String encryptString(String plaintext) {
    306. if(plaintext == null) {
    307. return null;
    308. }
    309. byte[] data = plaintext.getBytes();
    310. KeyPair keyPair = getKeyPair();
    311. try {
    312. byte[] en_data = encrypt((RSAPublicKey)keyPair.getPublic(), data);
    313. return new String(Hex.encodeHex(en_data));
    314. } catch(NullPointerException ex) {
    315. LOGGER.error("keyPair cannot be null.");
    316. } catch(Exception ex) {
    317. LOGGER.error(ex.getCause().getMessage());
    318. }
    319. return null;
    320. }
    321. /**
    322. * ??????????????????????????
    323. *

    324. * ????? {@code null}?????? {@code encrypttext} ? {@code null}??????????? {@code null}??
    325. * ?????????????? {@code null}??
    326. *
    327. * @param privateKey ??????????
    328. * @param encrypttext ?????
    329. * @return ??????????
    330. */
    331. public static String decryptString(PrivateKey privateKey, String encrypttext) {
    332. if (privateKey == null || StringUtils.isBlank(encrypttext)) {
    333. return null;
    334. }
    335. try {
    336. byte[] en_data = Hex.decodeHex(encrypttext.toCharArray());
    337. byte[] data = decrypt(privateKey, en_data);
    338. return new String(data);
    339. } catch (Exception ex) {
    340. LOGGER.error(String.format("\"%s\" Decryption failed. Cause: %s", encrypttext, ex.getCause().getMessage()));
    341. }
    342. return null;
    343. }
    344. /**
    345. * ?????????????????????????
    346. *

    347. * ??{@code encrypttext} ? {@code null}??????????? {@code null}??
    348. * ?????????????? {@code null}??
    349. *
    350. * @param encrypttext ?????
    351. * @return ??????????
    352. */
    353. public static String decryptString(String encrypttext) {
    354. if(StringUtils.isBlank(encrypttext)) {
    355. return null;
    356. }
    357. KeyPair keyPair = getKeyPair();
    358. try {
    359. byte[] en_data = Hex.decodeHex(encrypttext.toCharArray());
    360. byte[] data = decrypt((RSAPrivateKey)keyPair.getPrivate(), en_data);
    361. return new String(data);
    362. } catch(NullPointerException ex) {
    363. LOGGER.error("keyPair cannot be null.");
    364. } catch (Exception ex) {
    365. LOGGER.error(String.format("\"%s\" Decryption failed. Cause: %s", encrypttext, ex.getMessage()));
    366. }
    367. return null;
    368. }
    369. /**
    370. * ???????????????JS???????????????????????????????
    371. *
    372. * @param encrypttext ?????
    373. * @return {@code encrypttext} ????????????
    374. */
    375. public static String decryptStringByJs(String encrypttext) {
    376. String text = decryptString(encrypttext);
    377. if(text == null) {
    378. return null;
    379. }
    380. return text;
    381. }
    382. /** ????????????????????*/
    383. public static RSAPublicKey getDefaultPublicKey() {
    384. KeyPair keyPair = getKeyPair();
    385. if(keyPair != null) {
    386. return (RSAPublicKey)keyPair.getPublic();
    387. }
    388. return null;
    389. }
    390. /** ????????????????????*/
    391. public static RSAPrivateKey getDefaultPrivateKey() {
    392. KeyPair keyPair = getKeyPair();
    393. if(keyPair != null) {
    394. return (RSAPrivateKey)keyPair.getPrivate();
    395. }
    396. return null;
    397. }
    398. /** ????public key ??*/
    399. public static PublicKeyMap getPublicKeyMap() {
    400. PublicKeyMap publicKeyMap = new PublicKeyMap();
    401. RSAPublicKey rsaPublicKey = getDefaultPublicKey();
    402. publicKeyMap.setModulus(new String(Hex.encodeHex(rsaPublicKey.getModulus().toByteArray())));
    403. publicKeyMap.setExponent(new String(Hex.encodeHex(rsaPublicKey.getPublicExponent().toByteArray())));
    404. return publicKeyMap;
    405. }
    406. /**
    407. * ??publickey ?????map??
    408. * @param map
    409. */
    410. @SuppressWarnings({ "rawtypes", "unused", "unchecked" })
    411. public static void getPublicKeyMap(HashMap map) {
    412. PublicKeyMap publicKeyMap = new PublicKeyMap();
    413. RSAPublicKey rsaPublicKey = getDefaultPublicKey();
    414. map.put("publicKeyExponent", new String(Hex.encodeHex(rsaPublicKey.getPublicExponent().toByteArray())));
    415. map.put("publicKeyModulus", new String(Hex.encodeHex(rsaPublicKey.getModulus().toByteArray())));
    416. }
    417. }
    1. package com.atguigu.yygh.cmn.Rsa;
    2. public class PublicKeyMap {
    3. private String modulus;
    4. private String exponent;
    5. public String getModulus() {
    6. return modulus;
    7. }
    8. public void setModulus(String modulus) {
    9. this.modulus = modulus;
    10. }
    11. public String getExponent() {
    12. return exponent;
    13. }
    14. public void setExponent(String exponent) {
    15. this.exponent = exponent;
    16. }
    17. @Override
    18. public String toString() {
    19. return "PublicKeyMap [modulus=" + modulus + ", exponent=" + exponent
    20. + "]";
    21. }
    22. }

    ras.js

    1. /*
    2. * RSA, a suite of routines for performing RSA public-key computations in JavaScript.
    3. * Copyright 1998-2005 David Shapiro.
    4. * Dave Shapiro
    5. * dave@ohdave.com
    6. * changed by Fuchun, 2010-05-06
    7. * fcrpg2005@gmail.com
    8. */
    9. (function($w) {
    10. if(typeof $w.RSAUtils === 'undefined')
    11. var RSAUtils = $w.RSAUtils = {};
    12. var biRadixBase = 2;
    13. var biRadixBits = 16;
    14. var bitsPerDigit = biRadixBits;
    15. var biRadix = 1 << 16; // = 2^16 = 65536
    16. var biHalfRadix = biRadix >>> 1;
    17. var biRadixSquared = biRadix * biRadix;
    18. var maxDigitVal = biRadix - 1;
    19. var maxInteger = 9999999999999998;
    20. //maxDigits:
    21. //Change this to accommodate your largest number size. Use setMaxDigits()
    22. //to change it!
    23. //
    24. //In general, if you're working with numbers of size N bits, you'll need 2*N
    25. //bits of storage. Each digit holds 16 bits. So, a 1024-bit key will need
    26. //
    27. //1024 * 2 / 16 = 128 digits of storage.
    28. //
    29. var maxDigits;
    30. var ZERO_ARRAY;
    31. var bigZero, bigOne;
    32. var BigInt = $w.BigInt = function(flag) {
    33. if (typeof flag == "boolean" && flag == true) {
    34. this.digits = null;
    35. } else {
    36. this.digits = ZERO_ARRAY.slice(0);
    37. }
    38. this.isNeg = false;
    39. };
    40. RSAUtils.setMaxDigits = function(value) {
    41. maxDigits = value;
    42. ZERO_ARRAY = new Array(maxDigits);
    43. for (var iza = 0; iza < ZERO_ARRAY.length; iza++) ZERO_ARRAY[iza] = 0;
    44. bigZero = new BigInt();
    45. bigOne = new BigInt();
    46. bigOne.digits[0] = 1;
    47. };
    48. RSAUtils.setMaxDigits(20);
    49. //The maximum number of digits in base 10 you can convert to an
    50. //integer without JavaScript throwing up on you.
    51. var dpl10 = 15;
    52. RSAUtils.biFromNumber = function(i) {
    53. var result = new BigInt();
    54. result.isNeg = i < 0;
    55. i = Math.abs(i);
    56. var j = 0;
    57. while (i > 0) {
    58. result.digits[j++] = i & maxDigitVal;
    59. i = Math.floor(i / biRadix);
    60. }
    61. return result;
    62. };
    63. //lr10 = 10 ^ dpl10
    64. var lr10 = RSAUtils.biFromNumber(1000000000000000);
    65. RSAUtils.biFromDecimal = function(s) {
    66. var isNeg = s.charAt(0) == '-';
    67. var i = isNeg ? 1 : 0;
    68. var result;
    69. // Skip leading zeros.
    70. while (i < s.length && s.charAt(i) == '0') ++i;
    71. if (i == s.length) {
    72. result = new BigInt();
    73. }
    74. else {
    75. var digitCount = s.length - i;
    76. var fgl = digitCount % dpl10;
    77. if (fgl == 0) fgl = dpl10;
    78. result = RSAUtils.biFromNumber(Number(s.substr(i, fgl)));
    79. i += fgl;
    80. while (i < s.length) {
    81. result = RSAUtils.biAdd(RSAUtils.biMultiply(result, lr10),
    82. RSAUtils.biFromNumber(Number(s.substr(i, dpl10))));
    83. i += dpl10;
    84. }
    85. result.isNeg = isNeg;
    86. }
    87. return result;
    88. };
    89. RSAUtils.biCopy = function(bi) {
    90. var result = new BigInt(true);
    91. result.digits = bi.digits.slice(0);
    92. result.isNeg = bi.isNeg;
    93. return result;
    94. };
    95. RSAUtils.reverseStr = function(s) {
    96. var result = "";
    97. for (var i = s.length - 1; i > -1; --i) {
    98. result += s.charAt(i);
    99. }
    100. return result;
    101. };
    102. var hexatrigesimalToChar = [
    103. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    104. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
    105. 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
    106. 'u', 'v', 'w', 'x', 'y', 'z'
    107. ];
    108. RSAUtils.biToString = function(x, radix) { // 2 <= radix <= 36
    109. var b = new BigInt();
    110. b.digits[0] = radix;
    111. var qr = RSAUtils.biDivideModulo(x, b);
    112. var result = hexatrigesimalToChar[qr[1].digits[0]];
    113. while (RSAUtils.biCompare(qr[0], bigZero) == 1) {
    114. qr = RSAUtils.biDivideModulo(qr[0], b);
    115. digit = qr[1].digits[0];
    116. result += hexatrigesimalToChar[qr[1].digits[0]];
    117. }
    118. return (x.isNeg ? "-" : "") + RSAUtils.reverseStr(result);
    119. };
    120. RSAUtils.biToDecimal = function(x) {
    121. var b = new BigInt();
    122. b.digits[0] = 10;
    123. var qr = RSAUtils.biDivideModulo(x, b);
    124. var result = String(qr[1].digits[0]);
    125. while (RSAUtils.biCompare(qr[0], bigZero) == 1) {
    126. qr = RSAUtils.biDivideModulo(qr[0], b);
    127. result += String(qr[1].digits[0]);
    128. }
    129. return (x.isNeg ? "-" : "") + RSAUtils.reverseStr(result);
    130. };
    131. var hexToChar = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    132. 'a', 'b', 'c', 'd', 'e', 'f'];
    133. RSAUtils.digitToHex = function(n) {
    134. var mask = 0xf;
    135. var result = "";
    136. for (i = 0; i < 4; ++i) {
    137. result += hexToChar[n & mask];
    138. n >>>= 4;
    139. }
    140. return RSAUtils.reverseStr(result);
    141. };
    142. RSAUtils.biToHex = function(x) {
    143. var result = "";
    144. var n = RSAUtils.biHighIndex(x);
    145. for (var i = RSAUtils.biHighIndex(x); i > -1; --i) {
    146. result += RSAUtils.digitToHex(x.digits[i]);
    147. }
    148. return result;
    149. };
    150. RSAUtils.charToHex = function(c) {
    151. var ZERO = 48;
    152. var NINE = ZERO + 9;
    153. var littleA = 97;
    154. var littleZ = littleA + 25;
    155. var bigA = 65;
    156. var bigZ = 65 + 25;
    157. var result;
    158. if (c >= ZERO && c <= NINE) {
    159. result = c - ZERO;
    160. } else if (c >= bigA && c <= bigZ) {
    161. result = 10 + c - bigA;
    162. } else if (c >= littleA && c <= littleZ) {
    163. result = 10 + c - littleA;
    164. } else {
    165. result = 0;
    166. }
    167. return result;
    168. };
    169. RSAUtils.hexToDigit = function(s) {
    170. var result = 0;
    171. var sl = Math.min(s.length, 4);
    172. for (var i = 0; i < sl; ++i) {
    173. result <<= 4;
    174. result |= RSAUtils.charToHex(s.charCodeAt(i));
    175. }
    176. return result;
    177. };
    178. RSAUtils.biFromHex = function(s) {
    179. var result = new BigInt();
    180. var sl = s.length;
    181. for (var i = sl, j = 0; i > 0; i -= 4, ++j) {
    182. result.digits[j] = RSAUtils.hexToDigit(s.substr(Math.max(i - 4, 0), Math.min(i, 4)));
    183. }
    184. return result;
    185. };
    186. RSAUtils.biFromString = function(s, radix) {
    187. var isNeg = s.charAt(0) == '-';
    188. var istop = isNeg ? 1 : 0;
    189. var result = new BigInt();
    190. var place = new BigInt();
    191. place.digits[0] = 1; // radix^0
    192. for (var i = s.length - 1; i >= istop; i--) {
    193. var c = s.charCodeAt(i);
    194. var digit = RSAUtils.charToHex(c);
    195. var biDigit = RSAUtils.biMultiplyDigit(place, digit);
    196. result = RSAUtils.biAdd(result, biDigit);
    197. place = RSAUtils.biMultiplyDigit(place, radix);
    198. }
    199. result.isNeg = isNeg;
    200. return result;
    201. };
    202. RSAUtils.biDump = function(b) {
    203. return (b.isNeg ? "-" : "") + b.digits.join(" ");
    204. };
    205. RSAUtils.biAdd = function(x, y) {
    206. var result;
    207. if (x.isNeg != y.isNeg) {
    208. y.isNeg = !y.isNeg;
    209. result = RSAUtils.biSubtract(x, y);
    210. y.isNeg = !y.isNeg;
    211. }
    212. else {
    213. result = new BigInt();
    214. var c = 0;
    215. var n;
    216. for (var i = 0; i < x.digits.length; ++i) {
    217. n = x.digits[i] + y.digits[i] + c;
    218. result.digits[i] = n % biRadix;
    219. c = Number(n >= biRadix);
    220. }
    221. result.isNeg = x.isNeg;
    222. }
    223. return result;
    224. };
    225. RSAUtils.biSubtract = function(x, y) {
    226. var result;
    227. if (x.isNeg != y.isNeg) {
    228. y.isNeg = !y.isNeg;
    229. result = RSAUtils.biAdd(x, y);
    230. y.isNeg = !y.isNeg;
    231. } else {
    232. result = new BigInt();
    233. var n, c;
    234. c = 0;
    235. for (var i = 0; i < x.digits.length; ++i) {
    236. n = x.digits[i] - y.digits[i] + c;
    237. result.digits[i] = n % biRadix;
    238. // Stupid non-conforming modulus operation.
    239. if (result.digits[i] < 0) result.digits[i] += biRadix;
    240. c = 0 - Number(n < 0);
    241. }
    242. // Fix up the negative sign, if any.
    243. if (c == -1) {
    244. c = 0;
    245. for (var i = 0; i < x.digits.length; ++i) {
    246. n = 0 - result.digits[i] + c;
    247. result.digits[i] = n % biRadix;
    248. // Stupid non-conforming modulus operation.
    249. if (result.digits[i] < 0) result.digits[i] += biRadix;
    250. c = 0 - Number(n < 0);
    251. }
    252. // Result is opposite sign of arguments.
    253. result.isNeg = !x.isNeg;
    254. } else {
    255. // Result is same sign.
    256. result.isNeg = x.isNeg;
    257. }
    258. }
    259. return result;
    260. };
    261. RSAUtils.biHighIndex = function(x) {
    262. var result = x.digits.length - 1;
    263. while (result > 0 && x.digits[result] == 0) --result;
    264. return result;
    265. };
    266. RSAUtils.biNumBits = function(x) {
    267. var n = RSAUtils.biHighIndex(x);
    268. var d = x.digits[n];
    269. var m = (n + 1) * bitsPerDigit;
    270. var result;
    271. for (result = m; result > m - bitsPerDigit; --result) {
    272. if ((d & 0x8000) != 0) break;
    273. d <<= 1;
    274. }
    275. return result;
    276. };
    277. RSAUtils.biMultiply = function(x, y) {
    278. var result = new BigInt();
    279. var c;
    280. var n = RSAUtils.biHighIndex(x);
    281. var t = RSAUtils.biHighIndex(y);
    282. var u, uv, k;
    283. for (var i = 0; i <= t; ++i) {
    284. c = 0;
    285. k = i;
    286. for (j = 0; j <= n; ++j, ++k) {
    287. uv = result.digits[k] + x.digits[j] * y.digits[i] + c;
    288. result.digits[k] = uv & maxDigitVal;
    289. c = uv >>> biRadixBits;
    290. //c = Math.floor(uv / biRadix);
    291. }
    292. result.digits[i + n + 1] = c;
    293. }
    294. // Someone give me a logical xor, please.
    295. result.isNeg = x.isNeg != y.isNeg;
    296. return result;
    297. };
    298. RSAUtils.biMultiplyDigit = function(x, y) {
    299. var n, c, uv;
    300. result = new BigInt();
    301. n = RSAUtils.biHighIndex(x);
    302. c = 0;
    303. for (var j = 0; j <= n; ++j) {
    304. uv = result.digits[j] + x.digits[j] * y + c;
    305. result.digits[j] = uv & maxDigitVal;
    306. c = uv >>> biRadixBits;
    307. //c = Math.floor(uv / biRadix);
    308. }
    309. result.digits[1 + n] = c;
    310. return result;
    311. };
    312. RSAUtils.arrayCopy = function(src, srcStart, dest, destStart, n) {
    313. var m = Math.min(srcStart + n, src.length);
    314. for (var i = srcStart, j = destStart; i < m; ++i, ++j) {
    315. dest[j] = src[i];
    316. }
    317. };
    318. var highBitMasks = [0x0000, 0x8000, 0xC000, 0xE000, 0xF000, 0xF800,
    319. 0xFC00, 0xFE00, 0xFF00, 0xFF80, 0xFFC0, 0xFFE0,
    320. 0xFFF0, 0xFFF8, 0xFFFC, 0xFFFE, 0xFFFF];
    321. RSAUtils.biShiftLeft = function(x, n) {
    322. var digitCount = Math.floor(n / bitsPerDigit);
    323. var result = new BigInt();
    324. RSAUtils.arrayCopy(x.digits, 0, result.digits, digitCount,
    325. result.digits.length - digitCount);
    326. var bits = n % bitsPerDigit;
    327. var rightBits = bitsPerDigit - bits;
    328. for (var i = result.digits.length - 1, i1 = i - 1; i > 0; --i, --i1) {
    329. result.digits[i] = ((result.digits[i] << bits) & maxDigitVal) |
    330. ((result.digits[i1] & highBitMasks[bits]) >>>
    331. (rightBits));
    332. }
    333. result.digits[0] = ((result.digits[i] << bits) & maxDigitVal);
    334. result.isNeg = x.isNeg;
    335. return result;
    336. };
    337. var lowBitMasks = [0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F,
    338. 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF,
    339. 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF];
    340. RSAUtils.biShiftRight = function(x, n) {
    341. var digitCount = Math.floor(n / bitsPerDigit);
    342. var result = new BigInt();
    343. RSAUtils.arrayCopy(x.digits, digitCount, result.digits, 0,
    344. x.digits.length - digitCount);
    345. var bits = n % bitsPerDigit;
    346. var leftBits = bitsPerDigit - bits;
    347. for (var i = 0, i1 = i + 1; i < result.digits.length - 1; ++i, ++i1) {
    348. result.digits[i] = (result.digits[i] >>> bits) |
    349. ((result.digits[i1] & lowBitMasks[bits]) << leftBits);
    350. }
    351. result.digits[result.digits.length - 1] >>>= bits;
    352. result.isNeg = x.isNeg;
    353. return result;
    354. };
    355. RSAUtils.biMultiplyByRadixPower = function(x, n) {
    356. var result = new BigInt();
    357. RSAUtils.arrayCopy(x.digits, 0, result.digits, n, result.digits.length - n);
    358. return result;
    359. };
    360. RSAUtils.biDivideByRadixPower = function(x, n) {
    361. var result = new BigInt();
    362. RSAUtils.arrayCopy(x.digits, n, result.digits, 0, result.digits.length - n);
    363. return result;
    364. };
    365. RSAUtils.biModuloByRadixPower = function(x, n) {
    366. var result = new BigInt();
    367. RSAUtils.arrayCopy(x.digits, 0, result.digits, 0, n);
    368. return result;
    369. };
    370. RSAUtils.biCompare = function(x, y) {
    371. if (x.isNeg != y.isNeg) {
    372. return 1 - 2 * Number(x.isNeg);
    373. }
    374. for (var i = x.digits.length - 1; i >= 0; --i) {
    375. if (x.digits[i] != y.digits[i]) {
    376. if (x.isNeg) {
    377. return 1 - 2 * Number(x.digits[i] > y.digits[i]);
    378. } else {
    379. return 1 - 2 * Number(x.digits[i] < y.digits[i]);
    380. }
    381. }
    382. }
    383. return 0;
    384. };
    385. RSAUtils.biDivideModulo = function(x, y) {
    386. var nb = RSAUtils.biNumBits(x);
    387. var tb = RSAUtils.biNumBits(y);
    388. var origYIsNeg = y.isNeg;
    389. var q, r;
    390. if (nb < tb) {
    391. // |x| < |y|
    392. if (x.isNeg) {
    393. q = RSAUtils.biCopy(bigOne);
    394. q.isNeg = !y.isNeg;
    395. x.isNeg = false;
    396. y.isNeg = false;
    397. r = biSubtract(y, x);
    398. // Restore signs, 'cause they're references.
    399. x.isNeg = true;
    400. y.isNeg = origYIsNeg;
    401. } else {
    402. q = new BigInt();
    403. r = RSAUtils.biCopy(x);
    404. }
    405. return [q, r];
    406. }
    407. q = new BigInt();
    408. r = x;
    409. // Normalize Y.
    410. var t = Math.ceil(tb / bitsPerDigit) - 1;
    411. var lambda = 0;
    412. while (y.digits[t] < biHalfRadix) {
    413. y = RSAUtils.biShiftLeft(y, 1);
    414. ++lambda;
    415. ++tb;
    416. t = Math.ceil(tb / bitsPerDigit) - 1;
    417. }
    418. // Shift r over to keep the quotient constant. We'll shift the
    419. // remainder back at the end.
    420. r = RSAUtils.biShiftLeft(r, lambda);
    421. nb += lambda; // Update the bit count for x.
    422. var n = Math.ceil(nb / bitsPerDigit) - 1;
    423. var b = RSAUtils.biMultiplyByRadixPower(y, n - t);
    424. while (RSAUtils.biCompare(r, b) != -1) {
    425. ++q.digits[n - t];
    426. r = RSAUtils.biSubtract(r, b);
    427. }
    428. for (var i = n; i > t; --i) {
    429. var ri = (i >= r.digits.length) ? 0 : r.digits[i];
    430. var ri1 = (i - 1 >= r.digits.length) ? 0 : r.digits[i - 1];
    431. var ri2 = (i - 2 >= r.digits.length) ? 0 : r.digits[i - 2];
    432. var yt = (t >= y.digits.length) ? 0 : y.digits[t];
    433. var yt1 = (t - 1 >= y.digits.length) ? 0 : y.digits[t - 1];
    434. if (ri == yt) {
    435. q.digits[i - t - 1] = maxDigitVal;
    436. } else {
    437. q.digits[i - t - 1] = Math.floor((ri * biRadix + ri1) / yt);
    438. }
    439. var c1 = q.digits[i - t - 1] * ((yt * biRadix) + yt1);
    440. var c2 = (ri * biRadixSquared) + ((ri1 * biRadix) + ri2);
    441. while (c1 > c2) {
    442. --q.digits[i - t - 1];
    443. c1 = q.digits[i - t - 1] * ((yt * biRadix) | yt1);
    444. c2 = (ri * biRadix * biRadix) + ((ri1 * biRadix) + ri2);
    445. }
    446. b = RSAUtils.biMultiplyByRadixPower(y, i - t - 1);
    447. r = RSAUtils.biSubtract(r, RSAUtils.biMultiplyDigit(b, q.digits[i - t - 1]));
    448. if (r.isNeg) {
    449. r = RSAUtils.biAdd(r, b);
    450. --q.digits[i - t - 1];
    451. }
    452. }
    453. r = RSAUtils.biShiftRight(r, lambda);
    454. // Fiddle with the signs and stuff to make sure that 0 <= r < y.
    455. q.isNeg = x.isNeg != origYIsNeg;
    456. if (x.isNeg) {
    457. if (origYIsNeg) {
    458. q = RSAUtils.biAdd(q, bigOne);
    459. } else {
    460. q = RSAUtils.biSubtract(q, bigOne);
    461. }
    462. y = RSAUtils.biShiftRight(y, lambda);
    463. r = RSAUtils.biSubtract(y, r);
    464. }
    465. // Check for the unbelievably stupid degenerate case of r == -0.
    466. if (r.digits[0] == 0 && RSAUtils.biHighIndex(r) == 0) r.isNeg = false;
    467. return [q, r];
    468. };
    469. RSAUtils.biDivide = function(x, y) {
    470. return RSAUtils.biDivideModulo(x, y)[0];
    471. };
    472. RSAUtils.biModulo = function(x, y) {
    473. return RSAUtils.biDivideModulo(x, y)[1];
    474. };
    475. RSAUtils.biMultiplyMod = function(x, y, m) {
    476. return RSAUtils.biModulo(RSAUtils.biMultiply(x, y), m);
    477. };
    478. RSAUtils.biPow = function(x, y) {
    479. var result = bigOne;
    480. var a = x;
    481. while (true) {
    482. if ((y & 1) != 0) result = RSAUtils.biMultiply(result, a);
    483. y >>= 1;
    484. if (y == 0) break;
    485. a = RSAUtils.biMultiply(a, a);
    486. }
    487. return result;
    488. };
    489. RSAUtils.biPowMod = function(x, y, m) {
    490. var result = bigOne;
    491. var a = x;
    492. var k = y;
    493. while (true) {
    494. if ((k.digits[0] & 1) != 0) result = RSAUtils.biMultiplyMod(result, a, m);
    495. k = RSAUtils.biShiftRight(k, 1);
    496. if (k.digits[0] == 0 && RSAUtils.biHighIndex(k) == 0) break;
    497. a = RSAUtils.biMultiplyMod(a, a, m);
    498. }
    499. return result;
    500. };
    501. $w.BarrettMu = function(m) {
    502. this.modulus = RSAUtils.biCopy(m);
    503. this.k = RSAUtils.biHighIndex(this.modulus) + 1;
    504. var b2k = new BigInt();
    505. b2k.digits[2 * this.k] = 1; // b2k = b^(2k)
    506. this.mu = RSAUtils.biDivide(b2k, this.modulus);
    507. this.bkplus1 = new BigInt();
    508. this.bkplus1.digits[this.k + 1] = 1; // bkplus1 = b^(k+1)
    509. this.modulo = BarrettMu_modulo;
    510. this.multiplyMod = BarrettMu_multiplyMod;
    511. this.powMod = BarrettMu_powMod;
    512. };
    513. function BarrettMu_modulo(x) {
    514. var $dmath = RSAUtils;
    515. var q1 = $dmath.biDivideByRadixPower(x, this.k - 1);
    516. var q2 = $dmath.biMultiply(q1, this.mu);
    517. var q3 = $dmath.biDivideByRadixPower(q2, this.k + 1);
    518. var r1 = $dmath.biModuloByRadixPower(x, this.k + 1);
    519. var r2term = $dmath.biMultiply(q3, this.modulus);
    520. var r2 = $dmath.biModuloByRadixPower(r2term, this.k + 1);
    521. var r = $dmath.biSubtract(r1, r2);
    522. if (r.isNeg) {
    523. r = $dmath.biAdd(r, this.bkplus1);
    524. }
    525. var rgtem = $dmath.biCompare(r, this.modulus) >= 0;
    526. while (rgtem) {
    527. r = $dmath.biSubtract(r, this.modulus);
    528. rgtem = $dmath.biCompare(r, this.modulus) >= 0;
    529. }
    530. return r;
    531. }
    532. function BarrettMu_multiplyMod(x, y) {
    533. /*
    534. x = this.modulo(x);
    535. y = this.modulo(y);
    536. */
    537. var xy = RSAUtils.biMultiply(x, y);
    538. return this.modulo(xy);
    539. }
    540. function BarrettMu_powMod(x, y) {
    541. var result = new BigInt();
    542. result.digits[0] = 1;
    543. var a = x;
    544. var k = y;
    545. while (true) {
    546. if ((k.digits[0] & 1) != 0) result = this.multiplyMod(result, a);
    547. k = RSAUtils.biShiftRight(k, 1);
    548. if (k.digits[0] == 0 && RSAUtils.biHighIndex(k) == 0) break;
    549. a = this.multiplyMod(a, a);
    550. }
    551. return result;
    552. }
    553. var RSAKeyPair = function(encryptionExponent, decryptionExponent, modulus) {
    554. var $dmath = RSAUtils;
    555. this.e = $dmath.biFromHex(encryptionExponent);
    556. this.d = $dmath.biFromHex(decryptionExponent);
    557. this.m = $dmath.biFromHex(modulus);
    558. // We can do two bytes per digit, so
    559. // chunkSize = 2 * (number of digits in modulus - 1).
    560. // Since biHighIndex returns the high index, not the number of digits, 1 has
    561. // already been subtracted.
    562. this.chunkSize = 2 * $dmath.biHighIndex(this.m);
    563. this.radix = 16;
    564. this.barrett = new $w.BarrettMu(this.m);
    565. };
    566. RSAUtils.getKeyPair = function(encryptionExponent, decryptionExponent, modulus) {
    567. return new RSAKeyPair(encryptionExponent, decryptionExponent, modulus);
    568. };
    569. if(typeof $w.twoDigit === 'undefined') {
    570. $w.twoDigit = function(n) {
    571. return (n < 10 ? "0" : "") + String(n);
    572. };
    573. }
    574. // Altered by Rob Saunders (rob@robsaunders.net). New routine pads the
    575. // string after it has been converted to an array. This fixes an
    576. // incompatibility with Flash MX's ActionScript.
    577. RSAUtils.encryptedString = function(key, s) {
    578. var a = [];
    579. var sl = s.length;
    580. var i = 0;
    581. while (i < sl) {
    582. a[i] = s.charCodeAt(i);
    583. i++;
    584. }
    585. while (a.length % key.chunkSize != 0) {
    586. a[i++] = 0;
    587. }
    588. var al = a.length;
    589. var result = "";
    590. var j, k, block;
    591. for (i = 0; i < al; i += key.chunkSize) {
    592. block = new BigInt();
    593. j = 0;
    594. for (k = i; k < i + key.chunkSize; ++j) {
    595. block.digits[j] = a[k++];
    596. block.digits[j] += a[k++] << 8;
    597. }
    598. var crypt = key.barrett.powMod(block, key.e);
    599. var text = key.radix == 16 ? RSAUtils.biToHex(crypt) : RSAUtils.biToString(crypt, key.radix);
    600. result += text + " ";
    601. }
    602. return result.substring(0, result.length - 1); // Remove last space.
    603. };
    604. RSAUtils.decryptedString = function(key, s) {
    605. var blocks = s.split(" ");
    606. var result = "";
    607. var i, j, block;
    608. for (i = 0; i < blocks.length; ++i) {
    609. var bi;
    610. if (key.radix == 16) {
    611. bi = RSAUtils.biFromHex(blocks[i]);
    612. }
    613. else {
    614. bi = RSAUtils.biFromString(blocks[i], key.radix);
    615. }
    616. block = key.barrett.powMod(bi, key.d);
    617. for (j = 0; j <= RSAUtils.biHighIndex(block); ++j) {
    618. result += String.fromCharCode(block.digits[j] & 255,
    619. block.digits[j] >> 8);
    620. }
    621. }
    622. // Remove trailing null, if any.
    623. if (result.charCodeAt(result.length - 1) == 0) {
    624. result = result.substring(0, result.length - 1);
    625. }
    626. return result;
    627. };
    628. RSAUtils.setMaxDigits(130);
    629. })(window);

     

  • 相关阅读:
    软考高级系统架构设计师系列之:信息系统基础知识
    Vue生命周期
    ASEMI整流桥KBJ410参数,KBJ410压降,KBJ410热阻
    java毕业生设计-学生考勤管理系统-计算机源码+系统+mysql+调试部署+lw
    maven入门
    Vue框架--理解MVVM
    Secure Boot(安全启动)
    自动驾驶中的SLAM
    IODAY2
    动态内存管理
  • 原文地址:https://blog.csdn.net/weixin_61503139/article/details/138194058