Java Implementation of AES ECP PKCS5Padding Encryption and Decryption Tool Class

Keywords: Programming Java Lombok encoding github

Java implements an AES/ECB/PKCS5Padding encryption and decryption algorithm tool class

  • Encryption algorithm: AES
  • Mode: ECB
  • Complement method: PKCS5Padding

<!-- more -->

1. Tool Classes

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Base64Utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;

/**
 * Created by @author yihui in 19:12 20/1/2.
 */
@Slf4j
public class EncryptUtil {
    private static final String KEY_ALGORITHM = "AES";
    /**
     * Algorithm/mode/complement mode
     */
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
    private static final String CODE = "utf-8";

    @Setter
    @Getter
    public static String encryptKey;

    public static String encrypt(String content) {
        return encrypt(content, encryptKey);
    }

    /**
     * encryption
     *
     * @param content
     * @param key
     * @return
     * @throws Exception
     */
    public static String encrypt(String content, String key) {
        try {
            byte[] encrypted = encrypt2bytes(content, key);
            return Base64Utils.encodeToString(encrypted);
        } catch (Exception e) {
            log.error("failed to encrypt: {} of {}", content, e);
            return null;
        }
    }

    public static byte[] encrypt2bytes(String content, String key) {
        try {
            byte[] raw = key.getBytes(CODE);
            SecretKeySpec secretKeySpec = new SecretKeySpec(raw, KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            return cipher.doFinal(content.getBytes(CODE));
        } catch (Exception e) {
            log.error("failed to encrypt: {} of {}", content, e);
            return null;
        }
    }

    public static String decrypt(String content) {
        try {
            return decrypt(content, encryptKey);
        } catch (Exception e) {
            log.error("failed to decrypt: {}, e: {}", content, e);
            return null;
        }
    }

    /**
     * Decrypt
     *
     * @param content
     * @param key
     * @return
     * @throws Exception
     */
    public static String decrypt(String content, String key) throws Exception {
        return decrypt(Base64Utils.decodeFromString(content), key);
    }

    public static String decrypt(byte[] content, String key) throws Exception {
        if (key == null) {
            log.error("AES key should not be null");
            return null;
        }

        byte[] raw = key.getBytes(CODE);
        SecretKeySpec keySpec = new SecretKeySpec(raw, KEY_ALGORITHM);
        Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        try {
            byte[] original = cipher.doFinal(content);
            return new String(original, CqODE);
        } catch (Exception e) {
            log.error("failed to decrypt content: {}/ key: {}, e: {}", content, key, e);
            return null;
        }
    }
}

Notice the implementation above, which provides two ways

  • One is to use base64 encoding output after AES encryption, corresponding to decrypting base64 encoding data
  • One is to return the byte array directly after AES encryption; the other is to decode the byte array directly

2. Test case

We provide two encrypted files for decryption use;

base64 encryption and decryption

@Test
public void testEncrypt() throws Exception {
    String abc = "Hello, One Gray Blog!";
    String key = "JC66fRd3wj85k8Hr";
    String out = EncryptUtil.encrypt(abc, key);
    System.out.println(out);

    System.out.println(EncryptUtil.decrypt(out, key));
}

Output results such as:

TKrN7VKrqsAQ4JqygeHOlG21Sd3IRJ3Y11k4kOdOG4s=
Hello, One Gray Blog!

Byte Array Encryption and Decryption

@Test
public void testEncryptByte() throws Exception {
    String abc = "Hello, One Gray Blog!";
    String key = "JC66fRd3wj85k8Hr";
    byte[] out = EncryptUtil.encrypt2bytes(abc, key);
    System.out.println(new String(out));

    System.out.println(EncryptUtil.decrypt(out, key));
}

Output results such as:

// Encrypted byte array, just garbled... you're right.
L���R��������Δm�I��D���Y8��N�
Hello, One Gray Blog!

Why are there two differences?

If we take an encrypted byte array, get a string directly from the new String(), and decrypt the string, we will find that decryption fails.

Simply modify the test case above

@Test
public void testEncryptByte() throws Exception {
    String abc = "Hello, One Gray Blog!";
    String key = "JC66fRd3wj85k8Hr";
    byte[] out = EncryptUtil.encrypt2bytes(abc, key);
    String enc = new String(out, "utf-8");
    System.out.println(enc);

    System.out.println(EncryptUtil.decrypt(enc.getBytes("utf-8"), key));
}

After execution, decryption failed

Why is this happening?

  • Enc = new String (out,'utf-8') and enc.getBytes ('utf-8') byte array to string; string to byte array these two processes will result in the final generated byte array, which is inconsistent with the original!!!

case for decrypting remote resources

Last case to decrypt remotely encrypted binary files

private void binKey(String uri, String key) throws Exception {
    // This file is a direct upload binary without base64 encoding
    URL url = new URL(uri);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    InputStream stream = connection.getInputStream();
    int lenth = connection.getContentLength();
    byte[] out = new byte[lenth];
    stream.read(out);
    stream.close();
    String ans = decrypt(out, key);
    System.out.println(ans);
}

public void testDe() throws Exception {
    String key = "5JRHMJn8xHnMDRXa";
    binKey("http://q8rnsprw0.bkt.clouddn.com/mwzz/b0001", key);
}

II. Other

1. A grey Blog: https://liuyueyi.github.io/hexblog

Grey personal blog, record all the blogs in study and work, welcome to browse

2. Declaration

Unlike letters, the above are purely family statements. Due to limited personal abilities, there are unavoidable omissions and errors. If bug s are found or there are better suggestions, you are welcome to criticize and correct them with gratitude.

3. Scan attention

A grey blog

Posted by sundawg on Sat, 02 May 2020 22:16:45 -0700