使用javascript加密json中的值

时间:2015-01-17 15:17:49

标签: javascript json encryption jsonpath

我有不同类型的请求如下:

    {  
       "RequestA":{  
          "CreditCard":"1234567812345678",
          "expdate":"0919",
          "pin":[  
             "1792"     ]
       }
    }
and
    {  
       "RequestB":{  
          "CreditCard":"1234567812345678",
          "expdate":"0917",
          "pin":[  
             "1789"     ]
       }
    }

两个请求中的起始对象名称都不同。

我需要写一个javascript, 因此,无论何时有CreditCard / expdate / pin,我都需要对它们进行加密。

所以javascript的结果应该如下:

{  
   "RequestA":{  
      "CreditCard":"encryptedvalue",
      "expdate":"encryptedvalue",
      "pin":[  
         "encryptedvalue"     ]
   }
}
and
{  
   "RequestB":{  
      "CreditCard":"encryptedvalue",
      "expdate":"encryptedvalue",
      "pin":[  
         "encryptedvalue"     ]
   }
}

调用这些库 aes.js:http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js

json.js:https://raw.githubusercontent.com/douglascrockford/JSON-js/master/json.js

jsonpath.js:https://code.google.com/p/jsonpath/downloads/detail?name=jsonpath-0.8.0.js.txt&can=2&q=

我使用的Javascript如下,它不加密

<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js"></script>
<script type="text/javascript" src="/json.js"></script>
<script type="text/javascript" src="/jsonpath.js"></script>
<script>

function findAndReplace(object, value, replacevalue){
  for(var x in object){
    if(typeof object[x] == typeof {}){
      findAndReplace(object[x], value, replacevalue);
    }
    if(object[x] == value){ 
      object["name"] = replacevalue;
      // break; // uncomment to stop after first replacement
    }
  }
}

function encrypt(value,key)
{
    result = "";
    var result = CryptoJS.AES.encrypt(value, key);
    return result;
}



    var req = request.body.asJSON;      

        var cc = jsonPath(req, "$..CreditCard");


    if(cc){

        var enccc = encrypt(cc, "secret");
        findAndReplace(req,cc,encc);
    }

    request.body=JSON.stringify(req);
</script>

0 个答案:

没有答案