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);
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM