The development project needs to cache important data locally so that it is read offline, and if the data is not processed, it can easily cause loss. Therefore, we generally encrypt this kind of data. Here, we mainly introduce two kinds of simple encryption algorithm: Des&aes.
Let's start with a brief introduction to the General encryption Scheme (as shown):
1) PlainText: original information.
2) encryption algorithm: With the key as the parameter, the clear text carries on the various permutation and the transformation the rule and the procedure, transforms the result to be ciphertext.
3) Key: The parameters of the encryption and decryption algorithm directly affect the result of the transformation of the plaintext.
4) Ciphertext: The result of transforming the plaintext.
5) Decryption algorithm: The inverse transformation of the encryption algorithm, with ciphertext as input, key as the parameter, the transformation result is clear text.
There are several mathematical operations commonly used in cryptography:
Shift and cyclic shift
The shift is to shift a piece of digital to the left or right in the entirety of the specified number of digits. Loop right shift is when the right shift, the final digital displacement to the forefront of the digital, the cycle left is the opposite. For example, the result of moving the 1-bit (decimal bit) to the right of the decimal digit 12345678 loop is 81234567, and the result of a loop-left 1-bit is 23456781.
Replacement
is to replace the value of one of the digits with another in accordance with the provisions of the permutation table. It is not as neat and orderly as a shift operation, and looks disorganized. This is exactly what encryption is needed and is often applied.
extended
compress
xor
1⊕1 = 0
0⊕0 = 0 
1⊕0 = 1
0⊕1 = 1
iteration
First, the following DES algorithm is introduced:
1, first look at the Code experiment results (Clear text unchanged, the key before the eight-bit unchanged):
By comparison, it is found that when the same plaintext is encrypted, the resulting ciphertext is the same as long as the first eight bits of the key are the same. It can be seen that DES uses a key length of 64 bits, further understanding can be found that only 56 bits of the 64-bit key can be used, the remaining 8 bits as parity (the 8 bits are the last one after each character is converted to binary). So, this is also the reason des is not commonly used today, now the computer through the poor lift, within 24 hours to get the correct key. But as a research material is still possible.
Next, let's look at the key and how the plaintext produces ciphertext.
After getting the original key (that is, the key we entered), a series of transformations is required to produce a true and clear-text key. The transformation algorithm is not discussed here. The following mathematical operations are used: displacement, 16 iterations. Finally, 16 sets of encryption keys are formed: key[0],key[1],key[2], .... KEY[14],KEY[15]. These 16 sets of keys are really involved in the production of ciphertext.
Of course, you also need to do this after you get the plaintext, and then generate the ciphertext with the key. In this case, the plaintext will also be iterated 16 times, in each iteration, with 16 sets of keys in order to make an XOR operation. After that, the data after the iteration is processed and the ciphertext is finally obtained.
Encryption is done, and naturally it involves decryption. We may think that decryption is the inverse of encryption. Actually, not all of them. Des uses the decryption algorithm, and the encryption algorithm is the same, the difference is the use of the key sequence. in encryption, the key generated by the iteration of the I iterations is used to make the XOR according to the first iteration of the I, while the first iteration of the decryption takes the key and data generated by the 17-i iteration.
The complete code is as follows:
Import Java.security.invalidkeyexception;import Java.security.nosuchalgorithmexception;import Java.security.securerandom;import Java.security.spec.invalidkeyspecexception;import Javax.crypto.badpaddingexception;import Javax.crypto.cipher;import Javax.crypto.illegalblocksizeexception;import Javax.crypto.nosuchpaddingexception;import Javax.crypto.secretkey;import Javax.crypto.secretkeyfactory;import Javax.crypto.spec.deskeyspec;public class des {Private final static String des = "des"; public static void Main (string[] args) {String Str_pass = "12345678FEDCBA"; String content = "a brother who does not shave"; String encryptstring = Encrypt ("a brother who does not shave", str_pass); byte[] key = Str_pass.getbytes (); byte[] src = content.getbytes (); securerandom sr = new SecureRandom (); byte[] result = NULL; Create Deskeyspec object from raw key data Deskeyspec dks;try {dks = new Deskeyspec (key); Secretkeyfactory keyfactory = SEcretkeyfactory.getinstance (DES); Secretkey SecureKey = Keyfactory.generatesecret (DKS); The Cipher object actually completes the cryptographic operation Cipher Cipher = cipher.getinstance (DES); Initialize the Cipher object with a key Cipher.init (Cipher.encrypt_mode, SecureKey, SR); Official execution of cryptographic operations result = cipher.dofinal (src);} catch (InvalidKeyException e) {//TODO auto-generated catch Blocke.printstacktrace ();} Create a key factory and use it to convert Deskeyspec to a Secretkey object catch (NoSuchAlgorithmException e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (Invalidkeyspecexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch ( Nosuchpaddingexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (Illegalblocksizeexception e) { TODO auto-generated catch Blocke.printstacktrace ();} catch (Badpaddingexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} String hs = ""; String stmp = ""; for (int n = 0; n < result.length; n++) {stmp = (Java. lang. Integer.tohexstring (Result[n] & 0XFF)); if (stmp.length () = = 1) HS = HS + "0" + stmp; else HS = hs + stmp; } String encryptstring = Hs.touppercase (); System.out.println ("key:" +str_pass); System.out.println ("Ciphertext:" +encryptstring); } }
Second, AES algorithm
The AES algorithm is based on substitution and substitution. Permutation is the rearrangement of data, instead of replacing one cell data with another. Specific implementation is not introduced here, interested friends can find their own. Specifically, AES is an iterative, symmetric-key grouping of passwords that can use 128, 192, and 256-bit keys, and use 128-bit (16-byte) packets to encrypt and decrypt data.
Let's start with the code.
Import Java.io.unsupportedencodingexception;import Java.security.invalidkeyexception;import Java.security.nosuchalgorithmexception;import Java.security.securerandom;import javax.crypto.BadPaddingException ; Import Javax.crypto.cipher;import Javax.crypto.illegalblocksizeexception;import Javax.crypto.keygenerator;import Javax.crypto.nosuchpaddingexception;import Javax.crypto.secretkey;import Javax.crypto.spec.secretkeyspec;public Class Aes {public static void main (string[] args) {String content = "a brother who does not shave"; String password = "12345678FEDCBA"; try {keygenerator kg = keygenerator.getinstance ("AES"); securerandom sr = new SecureRandom (Password.getbytes ()); Kg.init (128,SR); Secretkey Secretkey = Kg.generatekey (); System.out.println ("SecureRandom:" +sr.tostring ()); System.out.println ("Secretkey:" +secretkey); byte[] Encodeformat = secretkey.getencoded (); Secretkeyspec key = new Secretkeyspec (Encodeformat, "AES"); Cipher Cipher = cipher.getinstance ("AES");//Create cipher byte[] bytecontent = content.getbytes ("utf-8 "); Cipher.init (Cipher.encrypt_mode, key);//Initialize byte[] result = cipher.dofinal (bytecontent); String str_res = byte2string (result); System.out.println ("Ciphertext:" +str_res);} catch (NoSuchAlgorithmException e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch ( Nosuchpaddingexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (Unsupportedencodingexception e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (InvalidKeyException e) {//todo auto-generated catch bl Ocke.printstacktrace ();} catch (Illegalblocksizeexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (Badpaddingexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} public static string byte2string (byte[] b) {string hs = ""; String stmp = ""; for (int n = 0; n < b.length; n++) {stmp = (java.lang.Integer.toHexString (b[n] & 0XFF)); if (Stmp.lenGth () = = 1) HS = HS + "0" + stmp; else HS = hs + stmp; } return Hs.touppercase (); }}
I have a little explanation in the code:
Kg.init (128,new securerandom (Password.getbytes ())); Secretkey Secretkey = Kg.generatekey ();
The number of random numbers in the first line of code may be different, meaning that kg.init may have different effects. However, as long as the password is guaranteed to be the same, the resulting secretkey is the same. (a random number is also used in the DES algorithm, so there are also such problems)
View the reference manual you can see that the init function is used to initialize this key generator with a random source provided by the user, making it a deterministic key size. SecureRandom This class provides a strong cryptographic random number generator. So, although the values are different, they belong to the same category. We use them in a common feature. (Well-fetched, I do not understand what their common characteristic is O (╯-╰) o)
Probably write so much, have time to check the source code of Keygenerator.generatekey (), you can know their common characteristics. and then Add.
Well, come on.
Ps:
1, part of the content from the Internet.
2, next week to really participate in the development of the weekend to familiarize yourself with the business process. O (∩_∩) o~~
Discussion on JAVA encryption algorithm Des&aes