Golang AES algorithm for interoperability with Java (Android)

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Because the Java AES256 Encryption Library is Export-restricted, AES 128 encryption is used only.

Requirements to be met by interoperability

    • Number of encryption bits: Unified mining AES 128
    • Group encryption Condition: cbc/pkcs#5padding
    • Key fills the same way

Because Android's default padding is not the same as the Java default, and in different JDK versions there will be a key fill inconsistency, so you manually fill, go also take the same as Java fill: 16 bit 0. AES two platforms are to implement AES encryption and decryption operations. The encryption results are turned into base64.

The key code is as follows:
Go

Populates the Func Paddingkey (key String) (string) {var buffer bytes. Buffer buffer. WriteString (key) for I:=len (key); i<16;i++{buffer. WriteString ("0")} return buffer. String ()}//cryptographic func En (src string,srckey string) (string) {key: = []byte (Paddingkey (srckey)) result, err: = Aesencrypt ( []byte (SRC), key) if err! = Nil {panic (err)} return base64. Stdencoding.encodetostring (Result)}//decrypt func Unen (src string,srckey string) (string) {key: = []byte (Paddingkey (Srckey) var result []byte var err error result,err=base64. Stdencoding.decodestring (SRC) if err! = Nil {panic (err)} origdata, err: = Aesdecrypt (result, key) if Err! = Nil {panic (Err)} return string (Origdata)}func aesencrypt (Origdata, key []byte,iv []byte] ([]byte, er ROR) {block, err: = AES. Newcipher (key) if err! = Nil {return nil, err} blockSize: = block. BlockSize () Origdata = pkcs5padding (Origdata, BlockSize)//Origdata = ZEropadding (Origdata, block. BlockSize ()) Blockmode: = cipher. Newcbcencrypter (block, iv[:blocksize]) crypted: = Make ([]byte, Len (origdata))//According to the Cryptblocks method, initialize crypted as described below or To//crypted: = Origdata blockmode.cryptblocks (crypted, Origdata) return crypted, Nil}func aesdecrypt (crypted, ke y []byte,iv []byte] ([]byte, error) {block, err: = AES. Newcipher (key) if err! = Nil {return nil, err} blockSize: = block. BlockSize () Blockmode: = cipher. Newcbcdecrypter (Block,iv[:blocksize]) Origdata: = Make ([]byte, Len (crypted))//Origdata: = crypted blockmode.cry Ptblocks (Origdata, crypted) Origdata = pkcs5unpadding (origdata)//Origdata = zerounpadding (origdata) return orig     Data, Nil}func pkcs5padding (ciphertext []byte, blockSize int) []byte {padding: = Blocksize-len (ciphertext)%blocksize Padtext: = bytes. Repeat ([]byte{byte (padding)}, padding) return append (ciphertext, padtext ...)}   Func pkcs5unpadding (Origdata []byte) []byte { Length: = Len (origdata)//Remove Last byte unpadding times unpadding: = Int (origdata[length-1]) return origdata[:(length- unpadding)]}

Java:

public class Aestool {private Ivparameterspec ivspec;    Private Secretkeyspec KeySpec;        Public Aestool (String srckey) {string Key=paddingkey (Srckey);            try {byte[] keybytes = Key.getbytes ();            byte[] buf = new BYTE[16];            for (int i = 0; i < keybytes.length && i < buf.length; i++) {buf[i] = keybytes[i];            } This.keyspec = new Secretkeyspec (buf, "AES");        This.ivspec = new Ivparameterspec (keybytes);        } catch (Exception e) {e.printstacktrace ();            }} public String Encrypt (string src) {try {byte[] origdata=src.getbytes ();            Cipher Cipher = cipher.getinstance ("aes/cbc/pkcs5padding");            Cipher.init (Cipher.encrypt_mode, This.keyspec, This.ivspec);            Byte[] re= cipher.dofinal (origdata);        Return base64.encodetostring (Re,base64.default);   } catch (Exception e) {e.printstacktrace ();     } return null;            public string Decrypt (string src) throws Exception {byte[] Crypted=base64.decode (Src,base64.default);            Cipher Cipher = cipher.getinstance ("aes/cbc/pkcs5padding");            Cipher.init (Cipher.decrypt_mode, This.keyspec, This.ivspec);            BYTE re[] =cipher.dofinal (crypted);    return new String (re);        } private static String Paddingkey (String Liu) {stringbuffer sb=new stringbuffer (Liu);        for (int i=liu.length (); i<16;i++) {Sb.append ("0");    } return sb.tostring (); }}

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.