test.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. var crypto = require('crypto')
  2. ,fs = require('fs');
  3. function customPadding(str) {
  4. str = new Buffer(str,"utf8").toString("hex");
  5. var bitLength = str.length*8;
  6. if(bitLength < 256) {
  7. for(i=bitLength;i<256;i+=8) {
  8. str += 0x0;
  9. }
  10. } else if(bitLength > 256) {
  11. while((str.length*8)%256 != 0) {
  12. str+= 0x0;
  13. }
  14. }
  15. return new Buffer(str,"hex").toString("utf8");
  16. }
  17. //加密
  18. function cipher(algorithm, key, buf ,cb){
  19. var encrypted = "";
  20. var key = new Buffer(key);
  21. iv = new Buffer(0);
  22. var cip = crypto.createCipheriv(algorithm, key,iv);
  23. //cip.setAutoPadding(false);
  24. // buf = customPadding(buf);
  25. encrypted += cip.update(buf, 'utf8', 'base64');
  26. encrypted += cip.final('base64');
  27. cb(encrypted);
  28. }
  29. //解密
  30. function decipher(algorithm, key, encrypted,cb){
  31. var decrypted = "";
  32. var key = new Buffer(key);
  33. iv = new Buffer(0);
  34. var decipher = crypto.createDecipheriv(algorithm, key, iv);
  35. //decipher.setAutoPadding(false);
  36. decrypted += decipher.update(encrypted, 'base64', 'utf8');
  37. decrypted += decipher.final('utf8');
  38. cb(decrypted);
  39. }
  40. function cipherDecipherFile(data,algorithm, key){
  41. var s1 = new Date();
  42. cipher(algorithm, key,data,function(encrypted){
  43. var s2 = new Date();
  44. //console.log('cipher:'+algorithm+','+(s2-s1) +'ms, '+encrypted);
  45. //console.log(encrypted);
  46. //encrypted = "FJwlN9EDjrCbYgLYf91q1fR4mEFOJVLgUSbSebDTCk0stRV4X7xw3l1hyjS4Xe7qVzV13h0mgMSm+CjN/VPl1klRpcPSYhGPymeCx+mNofsLOKu+Myja9A=="
  47. decipher(algorithm, key,encrypted,function(txt){
  48. var s3 = new Date();
  49. //console.log('decipher:'+algorithm+','+(s3-s2) +'ms, '+txt);
  50. //console.log("原文:",txt,"des:",encrypted,"\n");
  51. });
  52. });
  53. }
  54. //console.log(crypto.getCiphers());
  55. var algs = [
  56. 'des-ecb'
  57. ];
  58. var key="miaomiao";
  59. var filename = "./b.txt";//"package.json";
  60. algs.forEach(function(name){
  61. var data_list = [
  62. {"aavv":new Date().getTime(), "ddsfds ":"sdfjk*===%sdfkjlk"},
  63. {"id":2343,"route":"im/login","data":{"a":"ddddddd"}},
  64. {"key= &&yy":{"aavv":new Date().getTime(), "ddsfds ":"sdfjk*===%sdfkjlk"}},
  65. {"key= &&yy":{"aa=你好=34&vv":new Date().getTime(), "dds234^&%fds ":"sdfjk*===%sdfkjlk"}},
  66. {"key= &&yy":{"aa=ʚ🌝ɞ阿lu=34&vv":new Date().getTime(), "dds234^&%fds ":{"ds7^*&":33333}}},
  67. ];
  68. let s = new Date().getTime();
  69. for (let j = 0; j < 1000;j++) {
  70. for (let i = 0; i < data_list.length; i++) {
  71. cipherDecipherFile(JSON.stringify(data_list[i]),name,key);
  72. }
  73. }
  74. let e = new Date().getTime();
  75. console.log(e - s);
  76. })