AES of Java encryption algorithm

Source: Internet
Author: User

The add and decrypt APIs are available in the JCE:

1, first should understand that AES is based on data block encryption, that is, each processing data is a piece (16 bytes), when the data is not a multiple of 16 bytes, this is called the Block cipher (different from the bit-based stream password), 16 bytes is the packet length

AES supports five modes: CBC,CFB,ECB,OFB,PCBC,

The JCE implements three complementary ways: nopadding,pkcs5padding,iso10126padding; ssl3padding is not supported and "NONE" mode is not supported.

ECB: is a basic encryption method, ciphertext is divided into blocks of equal length of the block (not enough), and then individually encrypted, one by one output composed ciphertext.
CBC: is a cyclic mode, the previous group of ciphertext and the current group of plaintext XOR or operation after encryption, the purpose of this is to enhance the difficulty of cracking.
CFB/OFB is actually a feedback model that is designed to enhance the difficulty of cracking.
The encryption results of the ECB and CBC are different, the patterns differ, and CBC adds an initialization vector to the first cipher block operation.

Algorithm/mode/padding 16 bytes After encrypted data length less than 16 bytes after encrypted length

Aes/cbc/nopadding 16 Not supported
Aes/cbc/pkcs5padding 32 16
Aes/cbc/iso10126padding 32 16
Aes/cfb/nopadding 16 Raw data length
Aes/cfb/pkcs5padding 32 16
Aes/cfb/iso10126padding 32 16
Aes/ecb/nopadding 16 Not supported
Aes/ecb/pkcs5padding 32 16
Aes/ecb/iso10126padding 32 16
Aes/ofb/nopadding 16 Raw data length
Aes/ofb/pkcs5padding 32 16
Aes/ofb/iso10126padding 32 16
Aes/pcbc/nopadding 16 Not supported
Aes/pcbc/pkcs5padding 32 16
Aes/pcbc/iso10126padding 32 16
As you can see, if the original data length equals 16*n when the original data length is 16, the data length is equal to 16*n when the nopadding is used, and in other cases the length of the encrypted data is equal to 16* (n+1). In the case of an integral multiple of less than 16, if the original data length equals 16*n+m[where M is less than 16], the length of the encrypted data is equal to 16* (n+1) in any way other than the nopadding fill; The ECB and PCBC three modes are not supported, and in CFB, ofb two modes the length of the encrypted data is equal to the original data length.

Demo:

ImportJavax.crypto.Cipher;ImportJavax.crypto.spec.SecretKeySpec;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory; Public classAescoder {Private Static FinalLogger Log=loggerfactory.getlogger (Aescoder.class); /*** Encryption * HEXSTR and Hexkey must be 16 binary string * To return a 16 binary representation of the string after encryption*/     Public Staticstring Ecbenc (String hexstr, String hexkey) {string rs=NULL; Try {            byte[] Inbytes =hexutil.hextobytes (HEXSTR); byte[] Keybytes =hexutil.hextobytes (Hexkey); Secretkeyspec Skeyspec=NewSecretkeyspec (Keybytes, "AES"); Cipher Cipher= Cipher.getinstance ("aes/ecb/nopadding");//"algorithm/Mode/complement Method"Cipher.init (Cipher.encrypt_mode, Skeyspec); byte[] encrypted =cipher.dofinal (inbytes); RS=Hexutil.bytestohex (encrypted); } Catch(Exception e) {log.error ("Encryption Exception", E); Log.error ("Input parameter is hexstr:{},hexkey:{}", Hexstr,hexkey); }        returnrs; }        /*** decryption * hexstr and Hexkey must be 16 binary * to return 16 binary strings after encryption*/     Public Staticstring Ecbdec (String hexstr,string hexkey) {string rs=NULL; Try {            byte[] Outbytes =hexutil.hextobytes (HEXSTR); byte[] Keybytes =hexutil.hextobytes (Hexkey); Secretkeyspec Skeyspec=NewSecretkeyspec (Keybytes, "AES"); Cipher Cipher= Cipher.getinstance ("aes/ecb/nopadding");//"algorithm/Mode/complement Method"Cipher.init (Cipher.decrypt_mode, Skeyspec); byte[] Decbytes =cipher.dofinal (outbytes); RS=Hexutil.bytestohex (decbytes); } Catch(Exception e) {log.error ("Decryption Exception", E); Log.error ("Input parameter is hexstr:{},hexkey:{}", Hexstr,hexkey); }        returnrs; }}

 Public classHexutil {/*** The normal string is described as "WAZX-B55SY6-S6DT5" with a 16-binary description as: "57415a582d4235355359362d5336445435" **/     Public Staticstring Strtohex (String str) {byte[] bytes =str.getbytes (); returnBytestohex (bytes); }        /**revert a 16-based string to a normal string * such as "57415a582d4235355359362d5336445435" to: "WAZX-B55SY6-S6DT5" **/     Public Staticstring Hextostr (String hex) {byte[] bytes=hextobytes (hex); return NewString (bytes); }            /**16-in-turn byte[]*/     Public Static byte[] hextobytes (String hex) {intLength = Hex.length ()/2; byte[] bytes=New byte[length];  for(inti=0;i<length;i++) {String tempstr=hex.substring (2*i, 2*i+2);//byte:8bit=4bit+4bit= hex bit + hex bitBytes[i]= (byte) Integer.parseint (TEMPSTR, 16); }        returnbytes; }        /**byte[] turn 16 binary*/     Public StaticString Bytestohex (byte[] bytes) {StringBuilder SB=NewStringBuilder ();  for(inti=0;i<bytes.length;i++){            intTempi=bytes[i] & 0xFF;//A byte:8bit,int:32bit; a high.String str =integer.tohexstring (tempi); if(Str.length () <2) {sb.append (0). append (str);//length less than two bits, padded: such as 16 in the D, expressed in 0d. }Else{sb.append (str); }        }        returnsb.tostring (); }}

 Public classAestest {Private StaticString key= "2B7E151628AED2A6ABF7158809CF4F3C"; @Test Public voidTest_all () {String Enori= "000000000000000WAZX-B55SY6-S6DT5"; String Enhex=Hexutil.strtohex (Enori); String ENRs=Aescoder.ecbenc (Enhex,key); System.out.println ("Encrypted result is:" +ENRs); String Dehex= "7312560ccb30ad9b445ee94b426c8a2bdf75d11ded50f053568ec08bf3f9be04"; String DERs=Aescoder.ecbdec (Dehex,key); String Deori=hexutil.hextostr (ders); System.out.println ("The decryption result is:" +Deori); } @Test Public voidTest_enc () {String enstr= "6BC1BEE22E409F96E93D7E117393172A"; String ENRs=Aescoder.ecbenc (Enstr,key);    System.out.println (ENRS); } @Test Public voidTest_dec () {String destr= "3AD77BB40D7A3660A89ECAF32466EF97"; String ENRs=Aescoder.ecbdec (Destr,key);    System.out.println (ENRS); }                /*** and background when using * This function is used to speak 16 binary array to turn to String * If the key is * uint8_t key[] = * {0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, * 0xab, 0xf7, 0x15, 0x88, 0x09, 0XCF, 0x4f, 0x3c} * After formatting is "2B7E151628AED2A6ABF 7158809CF4F3C "**/     Public Staticstring Convertstr (String hexstr) {string[] kstrs= Hexstr.split (","); String[] Keystrs=NewString[kstrs.length];  for(inti = 0; i < kstrs.length; i++) {String str= Kstrs[i].trim (). SUBSTRING (2); Keystrs[i]=str; } stringbuffer SB=NewStringBuffer ();  for(String str:keystrs) {sb.append (str); }        returnsb.tostring (). toUpperCase (); }}

Aestest Running results:

The result of the encryption is: 7312560CCB30AD9B445EE94B426C8A2BDF75D11DED50F053568EC08BF3F9BE04 decryption result: 000000000000000WAZX- B55sy6-s6dt5

AES of Java encryption 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.