当前位置:   article > 正文

web页面登陆,密码加密传输_在我们系统登录页面登录成功后怎么将秘钥返回给第三方系统接收

在我们系统登录页面登录成功后怎么将秘钥返回给第三方系统接收

一、利用RSA算法对传送的密码进行加密。

    rsa是一种非对称加密算法。当客户端向服务器发送请求时,服务端把rsa公钥发送到客户端,同时服务端保存私钥。当用户登录时,客户端用获取到的公钥将密码加密,然后传送到服务端。服务端接收到后,再用私钥将其解密。然后验证。

二、需要的jar。

    commons-lang.jar
    bouncycastle .jar
    commons-codec .jar
    commons-io .jar

三、java代码(RSAUtil.java)

  1. package com.cxhd.util.security;
  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.KeyPair;
  9. import java.security.KeyFactory;
  10. import java.security.KeyPairGenerator;
  11. import java.security.Provider;
  12. import java.security.PublicKey;
  13. import java.security.PrivateKey;
  14. import java.security.SecureRandom;
  15. import java.security.NoSuchAlgorithmException;
  16. import java.security.InvalidParameterException;
  17. import java.security.interfaces.RSAPublicKey;
  18. import java.security.interfaces.RSAPrivateKey;
  19. import java.security.spec.RSAPublicKeySpec;
  20. import java.security.spec.RSAPrivateKeySpec;
  21. import java.security.spec.InvalidKeySpecException;
  22. import javax.crypto.Cipher;
  23. import org.apache.commons.io.IOUtils;
  24. import org.apache.commons.io.FileUtils;
  25. import org.apache.commons.codec.DecoderException;
  26. import org.apache.commons.codec.binary.Hex;
  27. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  28. import org.apache.commons.lang.StringUtils;
  29. /**
  30. * RSA算法加密/解密工具类。
  31. *
  32. * @author fuchun
  33. * @version 1.0.0, 2010-05-05
  34. */
  35. public abstract class RSAUtil {
  36. /**
  37. * 算法名称
  38. */
  39. private static final String ALGORITHOM = "RSA";
  40. /**
  41. * 保存生成的密钥对的文件名称。
  42. */
  43. private static final String RSA_PAIR_FILENAME = "/rsa_pair.txt";
  44. /**
  45. * 密钥大小
  46. */
  47. private static final int KEY_SIZE = 1024;
  48. /**
  49. * 默认的安全服务提供者
  50. */
  51. private static final Provider DEFAULT_PROVIDER = new BouncyCastleProvider();
  52. private static KeyPairGenerator keyPairGen = null;
  53. private static KeyFactory keyFactory = null;
  54. /**
  55. * 缓存的密钥对。
  56. */
  57. private static KeyPair oneKeyPair = null;
  58. private static File rsaPairFile = null;
  59. static {
  60. try {
  61. keyPairGen = KeyPairGenerator.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
  62. keyFactory = KeyFactory.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
  63. } catch (NoSuchAlgorithmException ex) {
  64. ex.printStackTrace();
  65. }
  66. rsaPairFile = new File(getRSAPairFilePath());
  67. }
  68. private RSAUtil() {
  69. }
  70. /**
  71. * 生成并返回RSA密钥对。
  72. */
  73. private static synchronized KeyPair generateKeyPair() {
  74. try {
  75. keyPairGen.initialize(KEY_SIZE, new SecureRandom());
  76. oneKeyPair = keyPairGen.generateKeyPair();
  77. saveKeyPair(oneKeyPair);
  78. return oneKeyPair;
  79. } catch (InvalidParameterException ex) {
  80. ex.printStackTrace();
  81. } catch (NullPointerException ex) {
  82. ex.printStackTrace();
  83. }
  84. return null;
  85. }
  86. /**
  87. * 返回生成/读取的密钥对文件的路径。
  88. */
  89. private static String getRSAPairFilePath() {
  90. String urlPath = RSAUtil.class.getResource("/").getPath();
  91. return (new File(urlPath).getParent() + RSA_PAIR_FILENAME);
  92. }
  93. /**
  94. * 若需要创建新的密钥对文件,则返回 {@code true},否则 {@code false}。
  95. */
  96. private static boolean isCreateKeyPairFile() {
  97. // 是否创建新的密钥对文件
  98. boolean createNewKeyPair = false;
  99. if (!rsaPairFile.exists() || rsaPairFile.isDirectory()) {
  100. createNewKeyPair = true;
  101. }
  102. return createNewKeyPair;
  103. }
  104. /**
  105. * 将指定的RSA密钥对以文件形式保存。
  106. *
  107. * @param keyPair 要保存的密钥对。
  108. */
  109. private static void saveKeyPair(KeyPair keyPair) {
  110. FileOutputStream fos = null;
  111. ObjectOutputStream oos = null;
  112. try {
  113. fos = FileUtils.openOutputStream(rsaPairFile);
  114. oos = new ObjectOutputStream(fos);
  115. oos.writeObject(keyPair);
  116. } catch (Exception ex) {
  117. ex.printStackTrace();
  118. } finally {
  119. IOUtils.closeQuietly(oos);
  120. IOUtils.closeQuietly(fos);
  121. }
  122. }
  123. /**
  124. * 返回RSA密钥对。
  125. */
  126. public static KeyPair getKeyPair() {
  127. // 首先判断是否需要重新生成新的密钥对文件
  128. if (isCreateKeyPairFile()) {
  129. // 直接强制生成密钥对文件,并存入缓存。
  130. return generateKeyPair();
  131. }
  132. if (oneKeyPair != null) {
  133. return oneKeyPair;
  134. }
  135. return readKeyPair();
  136. }
  137. // 同步读出保存的密钥对
  138. private static KeyPair readKeyPair() {
  139. FileInputStream fis = null;
  140. ObjectInputStream ois = null;
  141. try {
  142. fis = FileUtils.openInputStream(rsaPairFile);
  143. ois = new ObjectInputStream(fis);
  144. oneKeyPair = (KeyPair) ois.readObject();
  145. return oneKeyPair;
  146. } catch (Exception ex) {
  147. ex.printStackTrace();
  148. } finally {
  149. IOUtils.closeQuietly(ois);
  150. IOUtils.closeQuietly(fis);
  151. }
  152. return null;
  153. }
  154. /**
  155. * 根据给定的系数和专用指数构造一个RSA专用的公钥对象。
  156. *
  157. * @param modulus 系数。
  158. * @param publicExponent 专用指数。
  159. * @return RSA专用公钥对象。
  160. */
  161. public static RSAPublicKey generateRSAPublicKey(byte[] modulus, byte[] publicExponent) {
  162. RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(new BigInteger(modulus),
  163. new BigInteger(publicExponent));
  164. try {
  165. return (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);
  166. } catch (InvalidKeySpecException ex) {
  167. ex.printStackTrace();
  168. } catch (NullPointerException ex) {
  169. ex.printStackTrace();
  170. }
  171. return null;
  172. }
  173. /**
  174. * 根据给定的系数和专用指数构造一个RSA专用的私钥对象。
  175. *
  176. * @param modulus 系数。
  177. * @param privateExponent 专用指数。
  178. * @return RSA专用私钥对象。
  179. */
  180. public static RSAPrivateKey generateRSAPrivateKey(byte[] modulus, byte[] privateExponent) {
  181. RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(new BigInteger(modulus),
  182. new BigInteger(privateExponent));
  183. try {
  184. return (RSAPrivateKey) keyFactory.generatePrivate(privateKeySpec);
  185. } catch (InvalidKeySpecException ex) {
  186. ex.printStackTrace();
  187. } catch (NullPointerException ex) {
  188. ex.printStackTrace();
  189. }
  190. return null;
  191. }
  192. /**
  193. * 根据给定的16进制系数和专用指数字符串构造一个RSA专用的私钥对象。
  194. *
  195. * @param hexModulus 系数。
  196. * @param hexPrivateExponent 专用指数。
  197. * @return RSA专用私钥对象。
  198. */
  199. public static RSAPrivateKey getRSAPrivateKey(String hexModulus, String hexPrivateExponent) {
  200. if (StringUtils.isBlank(hexModulus) || StringUtils.isBlank(hexPrivateExponent)) {
  201. return null;
  202. }
  203. byte[] modulus = null;
  204. byte[] privateExponent = null;
  205. try {
  206. modulus = Hex.decodeHex(hexModulus.toCharArray());
  207. privateExponent = Hex.decodeHex(hexPrivateExponent.toCharArray());
  208. } catch (DecoderException ex) {
  209. ex.printStackTrace();
  210. }
  211. if (modulus != null && privateExponent != null) {
  212. return generateRSAPrivateKey(modulus, privateExponent);
  213. }
  214. return null;
  215. }
  216. /**
  217. * 根据给定的16进制系数和专用指数字符串构造一个RSA专用的公钥对象。
  218. *
  219. * @param hexModulus 系数。
  220. * @param hexPublicExponent 专用指数。
  221. * @return RSA专用公钥对象。
  222. */
  223. public static RSAPublicKey getRSAPublidKey(String hexModulus, String hexPublicExponent) {
  224. if (StringUtils.isBlank(hexModulus) || StringUtils.isBlank(hexPublicExponent)) {
  225. return null;
  226. }
  227. byte[] modulus = null;
  228. byte[] publicExponent = null;
  229. try {
  230. modulus = Hex.decodeHex(hexModulus.toCharArray());
  231. publicExponent = Hex.decodeHex(hexPublicExponent.toCharArray());
  232. } catch (DecoderException ex) {
  233. ex.printStackTrace();
  234. }
  235. if (modulus != null && publicExponent != null) {
  236. return generateRSAPublicKey(modulus, publicExponent);
  237. }
  238. return null;
  239. }
  240. /**
  241. * 使用指定的公钥加密数据。
  242. *
  243. * @param publicKey 给定的公钥。
  244. * @param data 要加密的数据。
  245. * @return 加密后的数据。
  246. */
  247. public static byte[] encrypt(PublicKey publicKey, byte[] data) throws Exception {
  248. Cipher ci = Cipher.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
  249. ci.init(Cipher.ENCRYPT_MODE, publicKey);
  250. return ci.doFinal(data);
  251. }
  252. /**
  253. * 使用指定的私钥解密数据。
  254. *
  255. * @param privateKey 给定的私钥。
  256. * @param data 要解密的数据。
  257. * @return 原数据。
  258. */
  259. public static byte[] decrypt(PrivateKey privateKey, byte[] data) throws Exception {
  260. Cipher ci = Cipher.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
  261. ci.init(Cipher.DECRYPT_MODE, privateKey);
  262. return ci.doFinal(data);
  263. }
  264. /**
  265. * 使用给定的公钥加密给定的字符串。
  266. * <p />
  267. * 若 {@code publicKey} 为 {@code null},或者 {@code plaintext} 为 {@code null}
  268. * 则返回 {@code
  269. * null}。
  270. *
  271. * @param publicKey 给定的公钥。
  272. * @param plaintext 字符串。
  273. * @return 给定字符串的密文。
  274. */
  275. public static String encryptString(PublicKey publicKey, String plaintext) {
  276. if (publicKey == null || plaintext == null) {
  277. return null;
  278. }
  279. byte[] data = plaintext.getBytes();
  280. try {
  281. byte[] en_data = encrypt(publicKey, data);
  282. return new String(Hex.encodeHex(en_data));
  283. } catch (Exception ex) {
  284. ex.printStackTrace();
  285. }
  286. return null;
  287. }
  288. /**
  289. * 使用默认的公钥加密给定的字符串。
  290. * <p />
  291. * 若{@code plaintext} 为 {@code null} 则返回 {@code null}。
  292. *
  293. * @param plaintext 字符串。
  294. * @return 给定字符串的密文。
  295. */
  296. public static String encryptString(String plaintext) {
  297. if (plaintext == null) {
  298. return null;
  299. }
  300. byte[] data = plaintext.getBytes();
  301. KeyPair keyPair = getKeyPair();
  302. try {
  303. byte[] en_data = encrypt((RSAPublicKey) keyPair.getPublic(), data);
  304. return new String(Hex.encodeHex(en_data));
  305. } catch (NullPointerException ex) {
  306. ex.printStackTrace();
  307. } catch (Exception ex) {
  308. ex.printStackTrace();
  309. }
  310. return null;
  311. }
  312. /**
  313. * 使用给定的私钥解密给定的字符串。
  314. * <p />
  315. * 若私钥为 {@code null},或者 {@code encrypttext} 为 {@code null}或空字符串则返回
  316. * {@code null}。 私钥不匹配时,返回 {@code null}。
  317. *
  318. * @param privateKey 给定的私钥。
  319. * @param encrypttext 密文。
  320. * @return 原文字符串。
  321. */
  322. public static String decryptString(PrivateKey privateKey, String encrypttext) {
  323. if (privateKey == null || StringUtils.isBlank(encrypttext)) {
  324. return null;
  325. }
  326. try {
  327. byte[] en_data = Hex.decodeHex(encrypttext.toCharArray());
  328. byte[] data = decrypt(privateKey, en_data);
  329. return new String(data);
  330. } catch (Exception ex) {
  331. ex.printStackTrace();
  332. }
  333. return null;
  334. }
  335. /**
  336. * 使用默认的私钥解密给定的字符串。
  337. * <p />
  338. * 若{@code encrypttext} 为 {@code null}或空字符串则返回 {@code null}。 私钥不匹配时,返回
  339. * {@code null}。
  340. *
  341. * @param encrypttext 密文。
  342. * @return 原文字符串。
  343. */
  344. public static String decryptString(String encrypttext) {
  345. if (StringUtils.isBlank(encrypttext)) {
  346. return null;
  347. }
  348. KeyPair keyPair = getKeyPair();
  349. try {
  350. byte[] en_data = Hex.decodeHex(encrypttext.toCharArray());
  351. byte[] data = decrypt((RSAPrivateKey) keyPair.getPrivate(), en_data);
  352. return new String(data);
  353. } catch (NullPointerException ex) {
  354. ex.printStackTrace();
  355. } catch (Exception ex) {
  356. ex.printStackTrace();
  357. }
  358. return null;
  359. }
  360. /**
  361. * 使用默认的私钥解密由JS加密(使用此类提供的公钥加密)的字符串。
  362. *
  363. * @param encrypttext 密文。
  364. * @return {@code encrypttext} 的原文字符串。
  365. */
  366. public static String decryptStringByJs(String encrypttext) {
  367. String text = decryptString(encrypttext);
  368. if (text == null) {
  369. return null;
  370. }
  371. return StringUtils.reverse(text);
  372. }
  373. /**
  374. * 返回已初始化的默认的公钥。
  375. */
  376. public static RSAPublicKey getDefaultPublicKey() {
  377. KeyPair keyPair = getKeyPair();
  378. if (keyPair != null) {
  379. return (RSAPublicKey) keyPair.getPublic();
  380. }
  381. return null;
  382. }
  383. /**
  384. * 返回已初始化的默认的私钥。
  385. */
  386. public static RSAPrivateKey getDefaultPrivateKey() {
  387. KeyPair keyPair = getKeyPair();
  388. if (keyPair != null) {
  389. return (RSAPrivateKey) keyPair.getPrivate();
  390. }
  391. return null;
  392. }
  393. public static void main(String[] agrs) {
  394. RSAPublicKey publicKey = RSAUtil.getDefaultPublicKey();
  395. String modulus = new String(Hex.encodeHex(publicKey.getModulus().toByteArray()));
  396. String public_exponent = new String(Hex.encodeHex(publicKey.getPublicExponent().toByteArray()));
  397. RSAPrivateKey privateKey = RSAUtil.getDefaultPrivateKey();
  398. String text = "hello world!";
  399. String mi = RSAUtil.encryptString(text);
  400. String ming = RSAUtil.decryptString(mi);
  401. System.out.println("mi===>"+mi);
  402. System.out.println("ming===>"+ming);
  403. }
  404. }

四、js代码(rsa.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);

五、登陆时的jsp代码(rsademo.jsp)

  1. <%--
  2. Document : rsa
  3. Created on : 2015-4-21, 20:06:56
  4. Author : Administrator
  5. --%>
  6. <%@page import="org.apache.commons.codec.binary.Hex"%>
  7. <%@page import="com.cxhd.util.security.RSAUtil"%>
  8. <%@page import="java.security.interfaces.RSAPublicKey"%>
  9. <%@page contentType="text/html" pageEncoding="UTF-8"%>
  10. <%
  11. RSAPublicKey publicKey = RSAUtil.getDefaultPublicKey();
  12. String modulus = new String(Hex.encodeHex(publicKey.getModulus().toByteArray()));
  13. String public_exponent = new String(Hex.encodeHex(publicKey.getPublicExponent().toByteArray()));
  14. %>
  15. <!DOCTYPE html>
  16. <html>
  17. <head>
  18. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  19. <title>test</title>
  20. <script type="text/javascript" src="js/jquery-1.9.1.js"></script>
  21. <script type="text/javascript" src="js/rsa.js"></script>
  22. <script>
  23. var key = RSAUtils.getKeyPair('<%=public_exponent%>', '', '<%=modulus%>');
  24. var pwd = RSAUtils.encryptedString(key, "123456");
  25. $.post('rsa_action.jsp',{'pwd':pwd},function(data){
  26. alert($.trim(data));
  27. });
  28. </script>
  29. </head>
  30. <body>
  31. <h1>Hello World!</h1>
  32. </body>
  33. </html>

六、验证时的服务端代码(rsa_action.jsp)

<%-- 
    Document   : rsa_action
    Created on : 2015-4-21, 10:04:55
    Author     : liyulin lyl010991@126.com
--%>
<%@page import="org.apache.commons.codec.binary.Hex"%>
<%@page import="com.cxhd.util.security.RSAUtil"%>
<%@page import="java.security.interfaces.RSAPrivateKey"%>
<%@page import="java.security.interfaces.RSAPublicKey"%>
<%@page import="com.cxhd.util.security.RSAUtil"%>
<%@page import="java.util.HashMap"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
    String pwd = request.getParameter("pwd");
    String ming = RSAUtil.decryptStringByJs(pwd);
    out.print(ming);
%>


声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号