Website front-End JS Encryption method RAS encryption can be PHP decryption

Source: Internet
Author: User
Tags begin rsa private key modulus openssl rsa



For data encryption and decryption problems, there are many ways to encrypt the clock. Here I'll talk about two of the methods I've used recently.



First, the first is the RAS encryption form, I use this encryption form the most fancy his 16 binary encryption form similar to the form of MD5, confidential after the string no special characters



1, first we look at the HTML section, we must first import the required encryption JS file


<script src = "{_ TEMP_PUBLIC _} / rasEncrypt / jsbn.js" type = "text / javascript"> </ script>
<script src = "{_ TEMP_PUBLIC _} / rasEncrypt / prng4.js" type = "text / javascript"> </ script>
<script src = "{_ TEMP_PUBLIC _} / rasEncrypt / rng.js" type = "text / javascript"> </ script>
<script src = "{_ TEMP_PUBLIC _} / rasEncrypt / rsa.js" type = "text / javascript"> </ script>
<div class = "portlet light">
    <div class = "portlet-title">
        <div class = "caption"> Test encrypted information </ div>
    </ div> <!-portlet-title->
    <div class = "portlet-body form">
        <form action = "/ test / testData" method = "post" class = "form-horizontal form-row-seperated" id = "three-from" novalidate = "novalidate" name = "three-from">
            <div class = "form-body clearfix">
                <div class = "form-group form-md-line-input">
                    <label class = "col-xs-2 control-label" for = "password"> Encrypted string </ label>
                    <div class = "col-xs-10">
                        <input class = "form-control" type = "password" name = "password" value = "01234567893265316259" placeholder = "Please enter encrypted string" id = "password">
                        <div class = "form-control-focus"> </ div>
                    </ div> <!-col-xs-10->
                </ div>
                <div class = "form-actions">
                    <div class = "row">
                        <div class = "col-md-offset-2 col-md-10">
                            <button type = "submit" class = "btn blue" id = "subForm"> <i class = "fa fa-check"> </ i> Submit </ button>
                        </ div>
                    </ div>
                </ div>
            </ div>
        </ form>
    </ div>
    <!-form-body clearfix->
</ div>
<script type = "text / javascript">
    function subForm () {// The suggestion is to de-encrypt at the moment of form submission. The following is written as long as the password is encrypted
        // If this encryption method is a function, it will be encrypted. This is to prevent the files you wrote before without encryption to ensure that the file will not report an error.
        if (typeof (RSAKey) == ‘function’) {
            $ ("input [type =‘ password ’]"). each (function (i, e) {
                var rsa = new RSAKey ();
                var pwd = $ (e) .val ();
                var res = rsa.encrypt (pwd);
                $ (e) .val (res) .data (‘rpwd’, pwd);
            });
        }
    }

</ script>


2, then we will notice that JS loaded one of the files configured


// Depends on jsbn.js and rng.js

// Version 1.1: support utf-8 encoding in pkcs1pad2

// convert a (hex) string to a bignum object
function parseBigInt (str, r) {
  return new BigInteger (str, r);
}

function linebrk (s, n) {
  var ret = "";
  var i = 0;
  while (i + n <s.length) {
    ret + = s.substring (i, i + n) + "\ n";
    i + = n;
  }
  return ret + s.substring (i, s.length);
}

function byte2Hex (b) {
  if (b <0x10)
    return "0" + b.toString (16);
  else
    return b.toString (16);
}

// PKCS # 1 (type 2, random) pad input string s to n bytes, and return a bigint
function pkcs1pad2 (s, n) {
  if (n <s.length + 11) {// TODO: fix for utf-8
    alert ("Message too long for RSA");
    return null;
  }
  var ba = new Array ();
  var i = s.length-1;
  while (i> = 0 && n> 0) {
    var c = s.charCodeAt (i--);
    if (c <128) {// encode using utf-8
      ba [-n] = c;
    }
    else if ((c> 127) && (c <2048)) {
      ba [-n] = (c & 63) | 128;
      ba [-n] = (c >> 6) | 192;
    }
    else {
      ba [-n] = (c & 63) | 128;
      ba [-n] = ((c >> 6) & 63) | 128;
      ba [-n] = (c >> 12) | 224;
    }
  }
  ba [-n] = 0;
  var rng = new SecureRandom ();
  var x = new Array ();
  while (n> 2) {// random non-zero pad
    x [0] = 0;
    while (x [0] == 0) rng.nextBytes (x);
    ba [-n] = x [0];
  }
  ba [-n] = 2;
  ba [-n] = 0;
  return new BigInteger (ba);
}

// "empty" RSA key constructor
function RSAKey () {
  // Make sure that the public key configuration here must be a pair with the key. I will introduce the method of generating the modulation below
  var N = "DB1EA572B55F5D9C8ADF092F5DCC3559CFEA8CE8BB54E3A71DA9B1AFBD7D17CF80ADB224FE4EA5379BC782F41C137748D8F1B5A36AD62A127EF5E87EFB25C209A66BCEE9925CE09631BF2271E81123E93438646625080FF04F4F2CF532B077E3E390486DF40E7586F0AE522C873F33170222F46BDB6084F55DE6B7031E55DBE7";
  this.n = parseBigInt (N, 16);
// Note that we are using 10001 in hexadecimal
  this.e = parseInt ("10001", 16);
  this.d = null;
  this.p = null;
  this.q = null;
  this.dmp1 = null;
  this.dmq1 = null;
  this.coeff = null;
}

// Set the public key fields N and e from hex strings
function RSASetPublic (N, E) {
  if (N! = null && E! = null && N.length> 0 && E.length> 0) {
    this.n = parseBigInt (N, 16);
    this.e = parseInt (E, 16);
  }
  else
    alert ("Invalid RSA public key");
}


// Perform raw public operation on "x": return x ^ e (mod n)
function RSADoPublic (x) {
  return x.modPowInt (this.e, this.n);
}

// Return the PKCS # 1 RSA encryption of "text" as an even-length hex string
function RSAEncrypt (text) {
  var m = pkcs1pad2 (text, (this.n.bitLength () + 7) >> 3);
  if (m == null) return null;
  var c = this.doPublic (m);
  if (c == null) return null;
  var h = c.toString (16);
  if ((h.length & 1) == 0) return h; else return "0" + h;
}

// Return the PKCS # 1 RSA encryption of "text" as a Base64-encoded string
// function RSAEncryptB64 (text) {
// var h = this.encrypt (text);
// if (h) return hex2b64 (h); else return null;
//}

// protected
RSAKey.prototype.doPublic = RSADoPublic;

// public
RSAKey.prototype.setPublic = RSASetPublic;
RSAKey.prototype.encrypt = RSAEncrypt;
//RSAKey.prototype.encrypt_b64 = RSAEncryptB64;


3, the last is our PHP file secret code


/ * It is better to define a constant if used in multiple places * /
        define ("RASKEY", "----- BEGIN RSA PRIVATE KEY -----
MIICXQIBAAKBgQDbHqVytV9dnIrfCS9dzDVZz + qM6LtU46cdqbGvvX0Xz4CtsiT +
TqU3m8eC9BwTd0jY8bWjatYqEn716H77JcIJpmvO6ZJc4JYxvyJx6BEj6TQ4ZGYl
CA / wT08s9TKwd + PjkEht9A51hvCuUiyHPzMXAiL0a9tghPVd5rcDHlXb5wIDAQAB
AoGBANhrD2wZWYSi7cJWVxMkc3kuUvIzl3rDkrZIeXgjBp9y0hw8fC80zBf9Y3Oi
2Owc / 7VOHmG2TqqlNAJ7TJePdnGvEG5yzHuMH6 / uRPS4A + gDndM8U / sZBUYaZjbr
5M8vg6wL3yQ2awAbXu7pwLEvxVmuvhv + 0jOFnqLpTRlki3ZpAkEA + Y00pTwikCEt
N + dkFGbhzZfH6bFNIkUOCrkDMgru1IargO / ggllk4fVLe7WBMWwh / 0X9oTeTjLi7
Es856QMdpQJBAODIIeu7 / cL3wp6Bigg7V25OSD + 7uSjlCpoPSUNZIjZ6HJQsFCnU
RHsEDeD1f88g7i9AGI0htYiJXCgwd6GE9ZsCQGoCUhrfMM + JSGw3H4yLJ + DuWT4s
01d7fjuP3IulmU8u5iwfun + k + fYC / c3PjNIx3T9TvCqAMW3WC6Ix5afWawECQA6p
n2TUL3pvVPen9YwR6uMcIiReJ3becfGYu6uz / cJV9tVHhs0vtoPbwNgCy6KEQGU +
phtWrpPIegV5G + SiWq8CQQCoH + ic1j9b1DzENUb206w7KpcIhm629iUWUgBTrnlC
LzOA6xwY78V7cAUdzhTycAxhmWq / 1FBlCCKtuZHVHnE /
----- END RSA PRIVATE KEY ----- ");
        / * Form parameters received * /
        $ password = trim ($ this-> options [‘password’]);
        / * The judgment here is to prevent decryption without encryption or passwords that are not in this encrypted form * /
        if (strlen ($ password) == 256) {
            $ encrypt_data = pack ("H *", $ password); // Convert the hexadecimal data
            / * openssl hex decryption * /
            if (openssl_private_decrypt ($ encrypt_data, $ decrypt_data, RASKEY)) {
                $ password = $ decrypt_data;
            }
        }


4. Methods for generating conventions and private keys


Second, the RSA key generation command

   1.Generate RSA private key
   openssl> openssl genrsa -out rsa_private_key.pem 1024
     Get exponent: 10001

   Generate a modulus:
   openssl> openssl rsa -in rsa_private_key.pem -noout -modulus

   3.Generate RSA public key
   openssl> openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem

   4. Convert RSA private key to PKCS8 format (=========== java use ============)
   openssl> openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt

   Note: The command after the ">" symbol is required.


Second, based on CRYPTO-JS encryption and PHP decryption of this encryption and the same encryption method, this encryption disadvantage is encrypted ciphertext existence of special characters



1, formalities I look at the HTML file


<div class = "portlet light">
    <div class = "portlet-title">
        <div class = "caption"> Test encrypted information </ div>
    </ div> <!-portlet-title->
    <div class = "portlet-body form">
        <form action = "/ test / testData" method = "post" class = "form-horizontal form-row-seperated" id = "three-from" novalidate = "novalidate" name = "three-from">
            <div class = "form-body clearfix">
                <div class = "form-group form-md-line-input">
                    <label class = "col-xs-2 control-label" for = "password"> Encrypted string </ label>
                    <div class = "col-xs-10">
                        <input class = "form-control" type = "password" name = "password" value = "01234567893265316259" placeholder = "Please enter encrypted string" id = "password">
                        <div class = "form-control-focus"> </ div>
                    </ div> <!-col-xs-10->
                </ div>
                <div class = "form-actions">
                    <div class = "row">
                        <div class = "col-md-offset-2 col-md-10">
                            <button type = "submit" class = "btn blue" id = "subForm"> <i class = "fa fa-check"> </ i> Submit </ button>
                        </ div>
                    </ div>
                </ div>
            </ div>
        </ form>
    </ div>
    <!-form-body clearfix->
</ div>
<script src = "http://cdn.bootcss.com/crypto-js/3.1.9/crypto-js.js"> </ script>
<script>
var data = "en2JprK0nMyYgbd6dQO0O0OO0O0O" // string to be encrypted
var key_base = "contentWindowHig"; // base value of the encryption key
var iv_base = "contentDocuments"; // iv base value required for encryption
/ **
 * Define encryption function
 * @param {[type]} a [formal parameter, value to be encrypted]
 * @return {[type]} [encrypted value]
 * /
var get = function (a) {

    var key = CryptoJS.enc.Utf8.parse (key_hash);
    var iv = CryptoJS.enc.Utf8.parse (iv_base);
    var res = CryptoJS.AES.encrypt (a, key, {iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.ZeroPadding});
    return res.toString ()
}
</ script>


2, PHP decryption method


// define variables
$ pass = "en2JprK0nMyYgbd6dQO0O0OO0O0O";
$ key_base = "contentWindowHig";
$ iv_base = "contentDocuments";
// decrypt
$ pass = str_replace (‘‘, ’+’, $ pass);
$ encryptedData = base64_decode ($ pass);
$ decrypted = mcrypt_decrypt (MCRYPT_RIJNDAEL_128, $ key_base, $ encryptedData, MCRYPT_MODE_CBC, $ iv_base);
$ decrypted = trim ($ decrypted); 


























Website front-End JS Encryption method RAS encryption can be PHP decryption


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.