JAVA中使用AES加密解密

來源:互聯網
上載者:User

標籤:content   ext   ati   ring   form   instance   exce   stat   decode   

技術交流群: 233513714

 

    /**     * AES加密測試     *     * @param str 加密參數     */    public void aesTest(String str) {        log.info("[rsaTest擷取請求:{}]", str);        try {            String encryptResult = AESUtil.encrypt(str, "123456");            log.info("[AES加密後的參數為:{}]", encryptResult);            String decryptResult = AESUtil.decrypt(encryptResult, "123456");            log.info("[AES解密後的參數為:{}]", decryptResult);        } catch (Exception e) {            log.info("[AES加密解密出現異常:{}]", e);        }    }    /**     * AES加密     *     * @param content  需要加密的內容     * @param password 加密密碼     * @return     */    public static String encrypt(String content, String password) {        try {            KeyGenerator kgen = KeyGenerator.getInstance("AES");            kgen.init(128, new SecureRandom(password.getBytes()));            SecretKey secretKey = kgen.generateKey();            byte[] enCodeFormat = secretKey.getEncoded();            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");            Cipher cipher = Cipher.getInstance("AES");            byte[] byteContent = content.getBytes("utf-8");            cipher.init(Cipher.ENCRYPT_MODE, key);            byte[] result = cipher.doFinal(byteContent);            Base64 base64 = new Base64();            return base64.encodeToString(result);        } catch (Exception e) {            log.info("AES加密出現異常:{}", e);        }        return null;    }    /**     * AES解密     *     * @param content  待解密內容     * @param password 解密密鑰     * @return     */    public static String decrypt(String content, String password) {        try {            Base64 base64 = new Base64();            byte[] text = base64.decode(content);            KeyGenerator kgen = KeyGenerator.getInstance("AES");            kgen.init(128, new SecureRandom(password.getBytes()));            SecretKey secretKey = kgen.generateKey();            byte[] enCodeFormat = secretKey.getEncoded();            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");            Cipher cipher = Cipher.getInstance("AES");            cipher.init(Cipher.DECRYPT_MODE, key);            byte[] result = cipher.doFinal(text);            return new String(result);        } catch (Exception e) {            log.info("AES解密出現異常:{}", e);        }        return null;    }

 

JAVA中使用AES加密解密

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.