import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AES128Test {

    public static void main(String[] args) {
        aes128("123456789ABCDEFG", "1234567891234567");
    }


    public static byte[] aes128(String text, String key) {
        if (key == null || text == null || key.getBytes().length != 16 || text.getBytes().length != 16) {
            System.out.println("encrypt: key or text error");
            return null;
        }
        try {
            //AES128(calculate with key and text)
            Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            encCipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"));
            byte[] encrypted = encCipher.doFinal(text.getBytes());
            for (int i = 0; i < encrypted.length; i++) {
                System.out.println( "result: " + encrypted[i]);
            }
            System.out.println(bytesToHex(encrypted));
            return encrypted;
        } catch (Exception e) {
            System.out.println(e.toString());
            return null;
        }
    }

    final protected static char[] hexArray = "0123456789abcdef".toCharArray();
    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for ( int j = 0; j < bytes.length; j++ ) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }
}

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐