欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

加密解密 - 用php实现java中的aes加密

程序员文章站 2022-03-31 17:37:52
...
java中的aes加密算法如下:
    public static byte[] decrypt(byte[] data, byte[] key)
            throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        Security.addProvider(new BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
        cipher.init(2, new SecretKeySpec(key, "AES"));
        return cipher.doFinal(data);
    }

    public static byte[] encrypt(byte[] data, byte[] key)
            throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        Security.addProvider(new BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
        cipher.init(1, new SecretKeySpec(key, "AES"));
        return cipher.doFinal(data);
    }

请问如何用php来实现
我测试了很多网上的例子都不能得到相同的密文

回复内容:

java中的aes加密算法如下:

    public static byte[] decrypt(byte[] data, byte[] key)
            throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        Security.addProvider(new BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
        cipher.init(2, new SecretKeySpec(key, "AES"));
        return cipher.doFinal(data);
    }

    public static byte[] encrypt(byte[] data, byte[] key)
            throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        Security.addProvider(new BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
        cipher.init(1, new SecretKeySpec(key, "AES"));
        return cipher.doFinal(data);
    }

请问如何用php来实现
我测试了很多网上的例子都不能得到相同的密文

可能是编码的问题,java默认是GBK编码;
php编码类型与页面的保存编码有关。