AES Encryption-decryption algorithm in C # and Java

Source: Internet
Author: User
Tags decrypt

One, C # version AES encryption and decryption algorithm

    Public classAescode { Public stringKey {Get;Set; }  Public stringEncrypt (stringval) {            if(string. IsNullOrEmpty (val))return NULL;#ifCspusing(Aescryptoserviceprovider des =NewAescryptoserviceprovider ())#else            using(Aesmanaged des =Newaesmanaged ())#endif            {                byte[] Inputbytearray =Encoding.UTF8.GetBytes (Val); byte[] _key; byte[] _iv; Generalkeyiv ( This. Key, out_key, out_iv); Des. Key=_key; Des.iv=_iv; using(MemoryStream ms =NewMemoryStream ()) {                    using(CryptoStream cs =NewCryptoStream (MS, Des. CreateEncryptor (), cryptostreammode.write)) {cs. Write (Inputbytearray,0, inputbytearray.length); Cs.                        FlushFinalBlock (); byte[] bytes = (byte[]) Ms.                        ToArray (); returnconvert.tobase64string (bytes); }                }            }        }         Public stringDecrypt (stringval) {            if(string. IsNullOrEmpty (val))return NULL;#ifCspusing(Aescryptoserviceprovider des =NewAescryptoserviceprovider ())#else            using(Aesmanaged des =Newaesmanaged ())#endif            {                byte[] Inputbytearray =Convert.frombase64string (Val); byte[] _key; byte[] _iv; Generalkeyiv ( This. Key, out_key, out_iv); Des. Key=_key; Des.iv=_iv; using(MemoryStream ms =NewMemoryStream ()) {                    using(CryptoStream cs =NewCryptoStream (MS, Des. CreateDecryptor (), cryptostreammode.write)) {cs. Write (Inputbytearray,0, inputbytearray.length); Cs.                        FlushFinalBlock (); returnEncoding.UTF8.GetString (Ms.                    ToArray ()); }                }            }        }         Public voidGeneralkeyiv (stringKEYSTR, out byte[] Key, out byte[] iv) {byte[] bytes =Encoding.UTF8.GetBytes (KEYSTR); Key=sha256managed.create ().            ComputeHash (bytes); IV=MD5. Create ().        ComputeHash (bytes); }}

Second, Java version of the algorithm

Importjava.security.MessageDigest;ImportJavax.crypto.Cipher;ImportJavax.crypto.spec.IvParameterSpec;ImportJavax.crypto.spec.SecretKeySpec;Importorg.apache.commons.codec.binary.Base64; Public classAescode {/*** provide key and vector for encryption * *@paramSSRC *@paramKey *@paramIV *@return     * @throwsException*/     Public StaticString Encrypt (String sSrc,byte[] Key,byte[] IV)throwsException {secretkeyspec Skeyspec=NewSecretkeyspec (Key, "AES"); Cipher Cipher= Cipher.getinstance ("aes/cbc/pkcs5padding");//"algorithm/Mode/complement Method"Ivparameterspec _iv =NewIvparameterspec (iv);//using CBC mode, a vector IV is required to increase the strength of the encryption algorithmCipher.init (Cipher.encrypt_mode, Skeyspec, _iv); byte[] encrypted = Cipher.dofinal (Ssrc.getbytes ("Utf-8")); returnBase64.encodebase64string (encrypted);    }    /*** provide key and vector for decryption * *@paramSSRC *@paramKey *@paramIV *@return     * @throwsException*/     Public StaticString Decrypt (String sSrc,byte[] Key,byte[] IV)throwsException {secretkeyspec Skeyspec=NewSecretkeyspec (Key, "AES"); Cipher Cipher= Cipher.getinstance ("aes/cbc/pkcs5padding"); Ivparameterspec _iv=NewIvparameterspec (iv);        Cipher.init (Cipher.decrypt_mode, Skeyspec, _iv); byte[] encrypted = Base64.decodebase64 (SSRC);byte[] Original =cipher.dofinal (encrypted); return NewString (Original, "Utf-8"); }    /*** Use key for encryption * *@paramSSRC *@paramKeystr *@return     * @throwsException*/     Public StaticString Encrypt (String sSrc, String keystr)throwsException {byte[] key =Generalkey (KEYSTR); byte[] IV =Generaliv (KEYSTR); Secretkeyspec Skeyspec=NewSecretkeyspec (Key, "AES"); Cipher Cipher= Cipher.getinstance ("aes/cbc/pkcs5padding");//"algorithm/Mode/complement Method"Ivparameterspec _iv =NewIvparameterspec (iv);Cipher.init (Cipher.encrypt_mode, Skeyspec, _iv); byte[] encrypted = Cipher.dofinal (Ssrc.getbytes ("Utf-8")); returnBase64.encodebase64string (encrypted);    }    /*** Use key to decrypt * *@paramSSRC *@paramKeystr *@return     * @throwsException*/     Public StaticString Decrypt (String sSrc, String keystr)throwsException {byte[] key =Generalkey (KEYSTR); byte[] IV =Generaliv (KEYSTR); Secretkeyspec Skeyspec=NewSecretkeyspec (Key, "AES"); Cipher Cipher= Cipher.getinstance ("aes/cbc/pkcs5padding"); Ivparameterspec _iv=NewIvparameterspec (iv);        Cipher.init (Cipher.decrypt_mode, Skeyspec, _iv); byte[] encrypted = Base64.decodebase64 (SSRC);//first decode with base64        byte[] Original =cipher.dofinal (encrypted); return NewString (Original, "Utf-8"); }    /*** Build Key byte code * *@paramKeystr *@return     * @throwsException*/    Private Static byte[] Generalkey (String keystr)throwsException {byte[] bytes = Keystr.getbytes ("Utf-8"); MessageDigest MD= Messagedigest.getinstance ("SHA-256");        Md.update (bytes); returnmd.digest (); }    /*** Build and decrypt vector byte code * *@paramKeystr *@return     * @throwsException*/    Private Static byte[] Generaliv (String keystr)throwsException {byte[] bytes = Keystr.getbytes ("Utf-8"); MessageDigest MD= Messagedigest.getinstance ("MD5");        Md.update (bytes); returnmd.digest (); }}

Java Edition requires Commons-codec-1.10.jar,local_policy.jar,us_export_policy.jar

AES Encryption-decryption algorithm in C # and Java

Related Article

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.