Analysis of symmetric encryption and decryption algorithm

Source: Internet
Author: User
Tags decrypt

I. Overview

Cryptosystem cryptography system is divided into private key system and public key system.

Private Key System: The two parties have made the private information agreement beforehand, using the symmetric key algorithm;
Public Key System: refers to the sender with public credentials to encrypt the data transmission, the receiver uses private credentials to decrypt, using asymmetric key algorithm;

Symmetric encryption Classification

Stream encryption (stream cipher), encryption and decryption both sides use the same pseudo-random encrypted data stream, is generally a bitwise XOR or random displacement of data content, common stream encryption algorithm such as RC4.
Packet encryption encryption (block cipher), also called Block encryption, divides the plaintext into multiple equal-length modules (blocks), using a deterministic algorithm and a symmetric key to decrypt each group separately.
Advanced block encryption establishes the ciphertext in an iterative way, each resulting cipher uses a different sub-key, and the child key is generated from the original key.
Grouping in data encryption becomes a grouping mode, such as the ECB; when the length of the data in the encryption is not sufficient to satisfy the grouping, it is used in the same way as the fill algorithm, such as pkcs5padding.

two, symmetric key algorithmDES

Data Encryption standard, encryption standards, IBM Research design.
The key length is 8 bytes, and the valid bit is 56bit, where the packet is 64bit=8 bytes.

3DES

Des like AES transition Encryption standard.
The data is encrypted three times by 3 64bit des keys.
The key length is 24 bytes and the valid bit is 168bit.

AES

Advanced encryption standards, high Encryption standard.
including AES-128; AES-192; AES-256 algorithm, the packet size is 128bit=16 bytes.

Third, the password grouping mode1 ECB

Electronic Code Book, Code mode
The same packet output the same key, simple and conducive to parallel operation, but can not hide the mode, but also easy to incur attacks

2 CBC

Cipher Block Chaining, ciphertext group chain mode
Requires initialization vector IV (the same length as the packet size), the first set of ciphertext and the second set of data XOR is computed and then encrypted to produce a second set of ciphertext
Good security, TLS, IPSec and other standard recommended mode, but not conducive to parallel operation

3 CFB

Cipher Feedback, ciphertext feedback mode

4 OFB

Output Feedback (OFB), input feedback mode

Three, filling algorithm

1 nopadding, no filling algorithm, usually requires data to meet the packet length requirements;
2 zerospadding, all filled to 0;
3 pkcs5padding, padding byte number;
4 others ...

The encryption standard for DES like AES transitions
Three encryption of data by 3 des keys of 64bit
Key length is 24 bytes, valid bit 168bit

Iv. Code Examples
/*** Encryption Tool Class * * <pre> * AES Support 128/192/256, depending on key length (corresponds to number of digits) * Des key length 8 bytes * 3DES Key Length 24 bytes * * Use CBC need to specify initial vector IV, length and grouping size same * des is 8 bytes; AES is 16 bytes * * </pre>*/ Public classCrypto {Static {        //add bouncycastle support for MD4 etc .Security.addprovider (NewBouncycastleprovider ()); }     Public Static enumCrypttype {DES_ECB_PKCS5 ("Des/ecb/pkcs5padding"), DES_CBC_PKCS5 ("Des/cbc/pkcs5padding", 8), DESEDE_ECB_PKCS5 ("Desede/ecb/pkcs5padding"), DESEDE_CBC_PKCS5 ("Desede/cbc/pkcs5padding", 8), AES_ECB_PKCS5 ("Aes/cbc/pkcs5padding", 16), AES_CBC_PKCS5 ("Aes/cbc/pkcs5padding", 16), AES_CBC_PKCS7 ("Aes/cbc/pkcs7padding", 16);  Public FinalString algorithm;  Public FinalString Keyalg;  Public Final intIvlen; PrivateCrypttype (String algorithm,intIvlen) {             This. Algorithm =algorithm;  This. Keyalg = This. algorithm.substring (0, This. Algorithm.indexof ('/'));  This. Ivlen =Ivlen; }        PrivateCrypttype (String algorithm) { This(Algorithm, 0); } @Override PublicString toString () {return  This. Algorithm; }    }    /*** Initialize the key * *@paramtype *@return     */     Public StaticString Initkey (crypttype type) {Try{keygenerator Generator=keygenerator.getinstance (TYPE.KEYALG); Secretkey Secretkey=Generator.generatekey (); byte[] key =secretkey.getencoded (); returncodec.bytetohexstring (key); } Catch(Exception e) {Throw NewRuntimeException (e); }    }    /*** Generate default Ivparam for type * *@return     */     Public Static byte[] Generatedefaultiv (Crypttype type) {byte[] IV =New byte[Type.ivlen];  for(inti = 0; i < iv.length; i++) {Iv[i]= 0x01; }        returnIV; }    /*** Encrypt The value with the encryption standard. *      * @paramValue * Raw String *@paramkey * in hex format *@paramIV * In HEX format if exist *@paramtype *@returnresult in hex format*/     Public Staticstring Encrypt (string value, string key, String IV, Crypttype type) {byte[] dvalue; Try{Dvalue= Value.getbytes ("Utf-8"); } Catch(unsupportedencodingexception e) {Throw NewRuntimeException (e); }        byte[] Dkey =Codec.hexstringtobyte (key); byte[] div =NULL; if(iv! =NULL&& iv.length () > 0) {div=Codec.hexstringtobyte (iv); }        byte[] result =Encrypt (Dvalue, Dkey, Div, type); returncodec.bytetohexstring (Result); }    /*** Encrypt The value with the encryption standard.     * * <pre> * key must has the corresponding length.     * * If use CBC mode which need IV param, the IV must not being NULL, * and IV data length is + for AES, 8 for DES * * </pre> * *@paramValue *@paramKey *@paramIV *@return     */     Public Static byte[] Encrypt (byte[] Value,byte[] Key,byte[] IV, Crypttype type) {        Try{secretkeyspec Skeyspec=NewSecretkeyspec (key, Type.keyalg); Cipher Cipher=cipher.getinstance (Type.algorithm); Ivparameterspec Ivparamspec=NULL; if(iv! =NULL) {Ivparamspec=NewIvparameterspec (iv);            } cipher.init (Cipher.encrypt_mode, Skeyspec, Ivparamspec); returncipher.dofinal (value); } Catch(Exception ex) {Throw NewRuntimeException (ex); }    }    /*** Encrypt The value with the encryption standard. *      * @paramvalue * encoded data in hex format *@paramkey * in hex format *@paramIV * In HEX format if exist *@paramtype *@returnResult Raw String*/     Public Staticstring Decrypt (string value, string key, String IV, Crypttype type) {byte[] Dvalue =Codec.hexstringtobyte (value); byte[] Dkey =Codec.hexstringtobyte (key); byte[] div =NULL; if(iv! =NULL&& iv.length () > 0) {div=Codec.hexstringtobyte (iv); }        byte[] result =Decrypt (Dvalue, Dkey, Div, type); Try {            return NewString (Result, "Utf-8"); } Catch(unsupportedencodingexception e) {Throw NewRuntimeException (e); }    }    /*** Decrypt The value with the encryption standard.     * * <pre> * key must has the corresponding length.     * * If use CBC mode which need IV param, the IV must not being NULL, * and IV data length is + for AES, 8 for DES * * </pre> * *@paramValue *@paramKey *@paramIV *@paramtype *@return     */     Public Static byte[] Decrypt (byte[] Value,byte[] Key,byte[] IV, Crypttype type) {        Try{secretkeyspec Skeyspec=NewSecretkeyspec (key, Type.keyalg); Cipher Cipher=cipher.getinstance (Type.algorithm); Ivparameterspec Ivparamspec=NULL; if(iv! =NULL) {Ivparamspec=NewIvparameterspec (iv);            } cipher.init (Cipher.decrypt_mode, Skeyspec, Ivparamspec); returncipher.dofinal (value); } Catch(Exception ex) {Throw NewRuntimeException (ex); }    }}

Key length constrained issue
inch " Main " java.security.InvalidKeyException:Illegal key size or default parameters

Problem reason: Due to the software publishing policy reasons, the default JDK environment is limited, when the AES encryption key is greater than 128 bits, the above exception occurs;
Workaround: Download the JCE extension and replace to ${java_home}/jre/lib/security
Http://www.oracle.com/technetwork/java/javase/downloads/index.html

v. Reference documents:

http://m.blog.csdn.net/article/details?id=51066799
Http://www.blogjava.net/amigoxie/archive/2014/07/06/415503.html

Analysis of symmetric encryption and decryption algorithm

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.