Asymmetric technology stack for AES encryption and decryption

Source: Internet
Author: User

Asymmetric technology stack for AES encryption and decryption

As mentioned in a previous article, the SSL layer of the HTTPS protocol is implemented on top of the transport layer, under the application layer, that is, the requests that are seen on the application layer are still plaintext, and for some scenarios, requests for these HTTP request parameters are not readable, This requires the encryption and decryption of information on different technology stacks on the front and back end. Of course, we usually complete this professional function will consider the use of the appropriate framework or library to complete the function, the front-end or Nodejs platform is usually the JavaScript language, JavaScript mainstream encryption and decryption libraries are sjcljs and CRYPTOJS, This article takes Cryptojs as an example to discuss. In addition, the JavaScript ES6 standard has been completed, and now the JavaScript is not the same as the JavaScript, Java has all the JavaScript, JavaScript as a platform, As a serious project to develop the language of the day is not far away, the previous few days to see Thoughtwork has ES6 listed as adopt, although the browser has not fully supported, now use Babel can write ES6 code, right, After ES6 JavaScript has supported class, lambda expressions and so on NB features, now JavaScript is the Java of the year, the future is also a platform for estimation.

The book is the story, as shown in the example, JavaScript needs to now introduce the appropriate encryption library in the browser, then you can invoke the corresponding encryption code, and the other encryption library also supports the Nodejs platform, can also be introduced and invoked as follows. It is necessary to note that the NPM installation package under the Nodejs platform is different from the version we downloaded, and these two versions cannot be mixed.

<script type= "Text/javascript" src= "Path-to/bower_components/crypto-js/crypto-js.js" ></script>< Script type= "Text/javascript" >    var encrypted = Cryptojs.aes (...);     var encrypted = cryptojs.sha256 (...);
var Cryptojs = require ("Crypto-js"); //  var ciphertext = CryptoJS.AES.encrypt (' My message ', ' secret key 123 '); //  var bytes  = CryptoJS.AES.decrypt (ciphertext.tostring (), ' secret key 123 '); var plaintext = bytes.tostring (CryptoJS.enc.Utf8); Console.log (plaintext);

A complete code example is shown below

<script src= "Crypto-js.js" ></script><script>var data = "Hi there"; var key= iv= CryptoJS.enc.Latin1.parse (' Ajq0yq0mvkkc1utr '); // Encrypt var encrypted = CryptoJS.AES.encrypt (data,key,{iv:iv,mode:cryptojs.mode.cbc,padding: CryptoJS.pad.ZeroPadding}); // Decrypt var decrypted = CryptoJS.AES.decrypt (encrypted,key,{iv:iv,padding:cryptojs.pad.zeropadding}); </script>

data transfer to the service side also need encryption decryption can use, otherwise get only garbled, no business meaning, the following are two mainstream service-side language C # and Java to illustrate, service-side code implementation. What needs to be explained is that it is simple to implement an AES encryption algorithm on a platform simply by finding the appropriate function library to complete the call, but if you need to complete a cross-platform, cross-technology stack, such as JavaScript encryption, C # decryption, or C # encryption, Java decryption is somewhat difficult , the implementation of this paper can achieve the purpose of cross-technology stack.

C#

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Security.Cryptography;namespaceuencrypt{classUencrypt {Static voidMain (string[] args) {String EncryptData= Program.encrypt ("Hi There","Ajq0yq0mvkkc1utr","Ajq0yq0mvkkc1utr");             Console.WriteLine (EncryptData); String Decryptdata= Program.decrypt (EncryptData,"Ajq0yq0mvkkc1utr","Ajq0yq0mvkkc1utr");             Console.WriteLine (Decryptdata);        Console.read (); }          Public Static stringEncrypt (stringToencrypt,stringKeystringIV) {byte[] Keyarray =UTF8Encoding.UTF8.GetBytes (key); byte[] Ivarray =UTF8Encoding.UTF8.GetBytes (iv); byte[] Toencryptarray =UTF8Encoding.UTF8.GetBytes (Toencrypt); RijndaelManaged Rdel=Newrijndaelmanaged (); Rdel.key=Keyarray; Rdel.iv=Ivarray; Rdel.mode=CIPHERMODE.CBC; Rdel.padding=Paddingmode.zeros; ICryptoTransform Ctransform=Rdel.createencryptor (); byte[] Resultarray = Ctransform.transformfinalblock (Toencryptarray,0, toencryptarray.length); returnConvert.tobase64string (Resultarray,0, resultarray.length); }          Public Static stringDecrypt (stringTodecrypt,stringKeystringIV) {byte[] Keyarray =UTF8Encoding.UTF8.GetBytes (key); byte[] Ivarray =UTF8Encoding.UTF8.GetBytes (iv); byte[] Toencryptarray =convert.frombase64string (Todecrypt); RijndaelManaged Rdel=Newrijndaelmanaged (); Rdel.key=Keyarray; Rdel.iv=Ivarray; Rdel.mode=CIPHERMODE.CBC; Rdel.padding=Paddingmode.zeros; ICryptoTransform Ctransform=Rdel.createdecryptor (); byte[] Resultarray = Ctransform.transformfinalblock (Toencryptarray,0, toencryptarray.length); returnUTF8Encoding.UTF8.GetString (resultarray); }    }}

Java

 Public classuencrypt{ Public Static voidMain (String args[])throwsException {String data=Encrypt () System.out.println (data);    System.out.println (desencrypt (data)); }      Public StaticString Encrypt ()throwsException {Try{String Data= "Hi There"; String Key= "Ajq0yq0mvkkc1utr"; String IV= "Ajq0yq0mvkkc1utr"; Cipher Cipher= Cipher.getinstance ("aes/cbc/nopadding"); intBlockSize =cipher.getblocksize (); byte[] Databytes =data.getbytes (); intPlaintextlength =databytes.length; if(plaintextlength% BlockSize! = 0) {Plaintextlength= Plaintextlength + (blockSize-(plaintextlength%blockSize)); }             byte[] plaintext =New byte[Plaintextlength]; System.arraycopy (Databytes,0, plaintext, 0, databytes.length); Secretkeyspec Keyspec=NewSecretkeyspec (Key.getbytes (), "AES"); Ivparameterspec Ivspec=NewIvparameterspec (Iv.getbytes ());            Cipher.init (Cipher.encrypt_mode, Keyspec, Ivspec); byte[] encrypted =cipher.dofinal (plaintext); return NewSun.misc.BASE64Encoder (). Encode (encrypted); } Catch(Exception e) {}} Public StaticString Desencrypt (String data)throwsException {Try{String key= "Ajq0yq0mvkkc1utr"; String IV=key; byte[] encrypted1 =NewBase64decoder (). Decodebuffer (data); Cipher Cipher= Cipher.getinstance ("aes/cbc/nopadding"); Secretkeyspec Keyspec=NewSecretkeyspec (Key.getbytes (), "AES"); Ivparameterspec Ivspec=NewIvparameterspec (Iv.getbytes ());            Cipher.init (Cipher.decrypt_mode, Keyspec, Ivspec); byte[] Original =cipher.dofinal (encrypted1); String originalstring=NewString (original); returnoriginalstring; }        Catch(Exception e) {} }}

Summarize

This article summarizes the JavaScript, C #, Java three platform AES encryption and decryption algorithm implementation, the complete implementation of the cross-technology stack encryption and decryption, can be in Nodejs encryption, C # Decryption, hope to help everyone.

Asymmetric technology stack for AES encryption and 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.