Cookie DES加密 CryptoJS

2017-12-12  本文已影响0人  阿尔法_狗

CryptoJS

import CryptoJS from 'crypto-js'
//cookie 解密常量,更改会导致cookie 取不出来;
const COOKIE_PUBLICKEY = '!+*(h%#c';

公钥,私钥

/**
   !!! 贴出来的公钥私钥是不能用的
**/
//ras公钥
const PublicKey = () => {

  return '-----BEGIN' +
    ' PUBLICKEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDyzMeJ8zG3TUVjYGKM+kuKJLkNZ+zbTixXuyTmvBQsFHh4V8rYiBs8O1xrCHwIDAQAB-----END PUBLIC KEY-----'
};
//Ras 秘钥
const PrivateKey = () => {
  return '-----BEGIN RSA PRIVATE' +
    ' KEY-----MIICWwIBAAKBgQDDyzMeJ8zG3TUVjYGK49LidU26VACHjAr/wDERkmLSCA7YLVE+V+27P6LRsFD1jWXfmyJC6bxcvTe2+W58YtDrfHf3DQZiMQQGo3D0j7+hhOeiLTmgWyGT3z2hUmVAHDM+kuKJLkNZ+zbTixXuyTmvBQsFHh4V8rYiBs8O1xrCHwIDAQABAoGAWiYSOD09BQdO7MiFr8xsCcbW7gbFY6OwYMc+EIglJe194D0lXh4gIIoRTpju/dCH6mfEa9Nzm1+jakAHBvWAIk5FYUMrlYX3gMvFr6pPOpKO8pptFiHcS7Y1ZE0wf2F6L1fNnCEUF495q/reB0LZBMjrw0mj/qUMNyaz7VmmycPIFqArwMs0EGDG6n4+ZcH6uZ0IQJAIDf1smFXTwyY0bND+MN6WVy2T0YERABAsc7vzlG3JAs+SXbYFk2dFgCuOx5gA7KtDWysbQJ58YgGE3uz53k0ag==-----END RSA PRIVATE KEY-----'
};

获取cookie

  //获取cook
const GetCookie = (getName) => {
  let name = getName + "=";
  let ca = document.cookie.split(';');
  for (let i = 0; i < ca.length; i++) {
    let c = ca[i].trim();
    if (c.indexOf(name) == 0) {
      try {
         return DecryptByDES( c.substring(name.length, c.length),COOKIE_PUBLICKEY)
      }catch (err){
        console.log(err);
        return ''
      }
    }
  }
  return "";
};

设置cookie


//保存用户信息
const SetCookie = (saveName, value) => {
  let days = 30;
  let d = new Date();
  let saveValue = EncryptByDES(value,COOKIE_PUBLICKEY);
  d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
  let expires = "expires=" + d.toGMTString();
  document.cookie = saveName + "=" + saveValue + "; " + expires;
};

EDS 解密

//EDS 解密
const DecryptByDES = (ciphertext, key) => {
  let keyHex = CryptoJS.enc.Utf8.parse(key);
  let decrypted = CryptoJS.DES.decrypt({
    ciphertext: CryptoJS.enc.Base64.parse(ciphertext)
  }, keyHex, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return decrypted.toString(CryptoJS.enc.Utf8);
};

EDS加密

//EDS加密
const EncryptByDES = (message, key) => {
  let keyHex = CryptoJS.enc.Utf8.parse(key);
  let encrypted = CryptoJS.DES.encrypt(message, keyHex, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7

  });
  return encrypted.toString();
};
上一篇下一篇

猜你喜欢

热点阅读