AES加解密 - Postgresql加密,Java解密

使用如下方法实现AES加解密,Postgresql加解密和Java加解密结果完全一致

  • Postgresql使用AES加解密

pg加密模块pgcrypto:http://www.postgres.cn/docs/9.6/pgcrypto.html

-- 内容=abcd1234,密钥=0123456789ABHAEQ
-- 加密
SELECT encode(encrypt('abcd1234', '0123456789ABHAEQ', 'aes-cbc/pad:pkcs'), 'base64'); -- IlBruWclssA3y9oOsgMQpw==

-- 解密
SELECT encode(
 decrypt(decode('IlBruWclssA3y9oOsgMQpw==','base64'), '0123456789ABHAEQ', 'aes-cbc/pad:pkcs') , 'escape'); -- abcd1234
  • 对应JAVA使用AES加解密
// 内容=abcd1234,密钥=0123456789ABHAEQ	
  public static void main(String[] args)  {
		//加密
        System.out.println( encrypt("abcd1234","0123456789ABHAEQ") );// IlBruWclssA3y9oOsgMQpw==
        //解密
        System.out.println( decrypt("IlBruWclssA3y9oOsgMQpw==","0123456789ABHAEQ") ); // abcd1234

    }

    public static String encrypt(String input, String key){
        byte[] crypted = null;
        try{
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skey);
            crypted = cipher.doFinal(input.getBytes());
        }catch(Exception e){
            System.out.println(e.toString());
        }
        return Base64.encode(crypted);
    }

    public static String decrypt(String input, String key){
        byte[] output = null;
        try{
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skey);
            output = cipher.doFinal(Base64.decode(input));
        }catch(Exception e){
            System.out.println(e.toString());
            return null;
        }
        return new String(output);
    }
posted @ 2021-09-10 17:05  JaminX86  阅读(1316)  评论(0编辑  收藏  举报