Symmetric encryption (AES) encryption implementation tool class (tutorial)

Keywords: Symmetric encryption (AES) encryption implementation tool class (tutorial)

Java encryption and decryption related terms (concepts) explanation (RSA, AES)
Error: java.security.InvalidKeyException: Illegal key size or default parameters solution

Currently found AES encryption although It can encrypt a large amount of text and the speed is very fast, but the memory consumption is very large. If you need a large amount of text encryption, you need to evaluate it carefully. Later, I will post asymmetric encryption (RSA) encryption, decryption examples, and the conversion of RSA encryption between .net and Java.

Examples of AES decryption and encryption tools

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;

public class AESSecurityUtil {
    /** key algorithm*/
    private static final String KEY_ALGORITHM = "AES";
    private static final int KEY_SIZE = 128;
    /** encryption/decryption algorithm/working mode/padding method */
// public static final String CIPHER_ALGORITHM = "AES/ECB/NoPadding";


    /**
     * Get the key
     * @return
     * @throws Exception
     */
    public static Key getKey() throws Exception{
        //Instantiate
        KeyGenerator kg = KeyGenerator. getInstance(KEY_ALGORITHM);
        //AES requires a key length of 128, 192 or 256 bits
        kg.init(KEY_SIZE);
        //Generate key
        SecretKey secretKey = kg.generateKey();
        return secretKey;
    }

    /**
     * transformation key
     * @param key key
     * @return Key key
     * @throws Exception
     */
    public static Key codeToKey(String key) throws Exception{
        byte[] keyBytes = Base64.decodeBase64(key);
        SecretKey secretKey = new SecretKeySpec(keyBytes,KEY_ALGORITHM);
        return secretKey;
    }

    /**
     * Decryption
     * @param data The data to be decrypted
     * @param key key
     * @return byte[] decrypted data
     * @throws Exception
     */
    private static String decrypt(byte[] data,byte[] key) throws Exception{
        //Restore key
        Key k = new SecretKeySpec(key ,KEY_ALGORITHM);
        /**
         * Instantiate
         * Use PKCS7Padding padding method, as follows
         * Cipher.getInstance(CIPHER_ALGORITHM,"BC");
         */
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        //Initialize, set the decryption mode
        cipher.init(Cipher.DECRYPT_MODE,k);
        //Execute the operation
        return new String( cipher.doFinal(data),"UTF-8");
    }

    /**
     * Decryption
     * @param data data to be decrypted
     * @param key key
     * @return byte[] decrypt data
     * @throws Exception
     */
    public static String decrypt(String data,String key) throws Exception{
        return decrypt(Base64.decodeBase64(data), Base64.decodeBase64(key));
    }

    /**
     * encryption
     * @param data data to be encrypted
     * @param key key
     * @return bytes[] encrypted data
     * @throws Exception
     */
    public static byte[] encrypt(byte[] data,byte[] key) throws Exception{
        //restore Key
        Key k = new SecretKeySpec(key,KEY_ALGORITHM);
        /**
         * Instantiate
         * Use PKCS7Padding padding method, implement as follows
         * Cipher.getInstance(CIPHER_ALGORITHM,"BC");
         */
        Cipher cipher = Cipher.getInstance( KEY_ALGORITHM);
        //Initialize, set to encryption mode
        cipher.init(Cipher.ENCRYPT_MODE,k);
        //Execute the operation
        return cipher.doFinal(data);
    }

    public static String encrypt(String data,String key) throws Exception{
        byte[] dataBytes = data.getBytes("UTF-8");
        byte[] keyBytes = Base64.decodeBase64(key);
        return Base64.encodeBase64String(encrypt(dataBytes, keyBytes));
    }

    /**
     * 初始化密钥
     * @return
     * @throws Exception
     */
    public static String getKeyStr() throws Exception{
        return Base64.encodeBase64String(getKey().getEncoded());
    }

    public static void main(String[] args) throws Exception{
        String key = "VxDksHQiTvQt9MMPtMVXdA==";
        String wenjian = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<mainData>\n" +
                "<config>\n" +
                " <operate>1</operate> <!--0: delete, 1: add, 2: modify-->\n" +
                "< /config>\n" +
                "<dataList type=\"personnel\">\n" +
                " <data id=\"employee master data key\"> <!--default master data code-->\n" +
                " <code></code> <!--code-->\n" +
                " <name></name> <!--name-->\n" +
                " <sex></sex> < !--Gender-->\n" +
                " <birthday></birthday> <!--date of birth-->\n" +
                " <education></education> <!--education-->\n" +
                " <idNumber></idNumber> <!--ID Number-->\n" +
                " <entryDate></entryDate> <!--Job Date-->\n" +
                " <departureDate></departureDate > <!--Resignation Date-->\n" +
                " <address></address> <!--Address-->\n" +
                " <phoneNumber></phoneNumber> <!--Phone--> \n" +
                " <mobilePhoneNumber></mobilePhoneNumber><!--mobile phone-->\n" +
                " <email></email> <!--email-->\n" +
                " < position></position> <!--Position-->\n" +
                " <maritalStatus></maritalStatus> <!--Marital Status-->\n" +
                "       <partyAffiliation></partyAffiliation><!--政治面貌-->\n" +
                "       <username></username>               <!--用户名-->\n" +
                "       <sortNo></sortNo>                   <!--排序号-->\n" +
                "       <status></status>                   <!--状态-->\n" +
                "       <department></department>           <!--所属部门-->\n" +
                "       <company></company>                 <!--所属公司-->\n" +
                "    </data>\n" +
                "</dataList>\n" +
                "</mainData>";
        StringBuffer buffer = new StringBuffer();
        for(int index = 0;index < 20000;index ++){
            buffer.append(wenjian);
        }
        String jimm = buffer.toString();
        
        String mw = AESSecurityUtil.encrypt(jimm,key);
        System.out.println("密文:" + mw);

        String jm = AESSecurityUtil.decrypt(mw,key);
        System.out.println("明文:" + jm);
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326443269&siteId=291194637