Linux進行AES加密每次結果都不一致並且解密失敗報錯


1. 現象

windows操作系統下進行"123456"的AES加密

encrypted message is below :
QLNYZyjRnKF/zxAjzDt/lw==
decrypted message is below :
123456
 
阿里雲服務器,同樣是"123456"的密碼,每次加密結果都不一樣,且不是QLNYZyjRnKF/zxAjzDt/lw==,解密是報錯的
 
2.解決方法
 
經過檢查之后,定位在生成KEY的方法上,如下:
public static Key getSecretKey(String key) throws Exception {
    SecretKey secureKey = null;
    if (key == null) {
        key = "";
    }
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    keyGenerator.init(new SecureRandom(key.getBytes()));
    secureKey = keyGenerator.generateKey();
    return secureKey;
}

修改到如下方式,問題解決:

public static Key getKey(String strKey) {
    try {
        if (strKey == null) {
            strKey = "";
        }
        KeyGenerator _generator = KeyGenerator.getInstance("AES");
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(strKey.getBytes());
        _generator.init(128, secureRandom);
        return _generator.generateKey();
    } catch (Exception e) {
        throw new RuntimeException(" 初始化密鑰出現異常 ");
    }
}
3.原因分析
 
原因一:
SecureRandom 實現完全隨操作系統本身的內部狀態,除非調用方在調用 getInstance 方法之后又調用了 setSeed 方法;該實現在 windows 上每次生成的 key 都相同,但是在 solaris 或部分 linux 系統上則不同。
 
原因二:
 
1、加密完byte[] 后,需要將加密了的byte[] 轉換成base64保存,如: 
BASE64Encoder base64encoder = new BASE64Encoder(); 
String encode=base64encoder.encode(bytes); 

2、解密前,需要將加密后的字符串從base64轉回來再解密,如: 
BASE64Decoder base64decoder = new BASE64Decoder(); 
byte[] encodeByte = base64decoder.decodeBuffer(str); 
 
4. 附錄完整代碼
package com.binfoo.wechat.util;

import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class SecurityUtil {
    public static String DES = "AES"; // optional value AES/DES/DESede

    public static String CIPHER_ALGORITHM = "AES"; // optional value AES/DES/DESede


    public static Key getKey(String strKey) {
        try {
            if (strKey == null) {
                strKey = "";
            }
            KeyGenerator _generator = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(strKey.getBytes());
            _generator.init(128, secureRandom);
            return _generator.generateKey();
        } catch (Exception e) {
            throw new RuntimeException(" 初始化密鑰出現異常 ");
        }
    }

    public static String encrypt(String data, String key) throws Exception {
        SecureRandom sr = new SecureRandom();
        Key secureKey = getKey(key);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secureKey, sr);
        byte[] bt = cipher.doFinal(data.getBytes());
        String strS = new BASE64Encoder().encode(bt);
        return strS;
    }


    public static String decrypt(String message, String key) throws Exception {
        SecureRandom sr = new SecureRandom();
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        Key secureKey = getKey(key);
        cipher.init(Cipher.DECRYPT_MODE, secureKey, sr);
        byte[] res = new BASE64Decoder().decodeBuffer(message);
        res = cipher.doFinal(res);
        return new String(res);
    }

    public static void main(String[] args) throws Exception {
        String message = "123456";
        String key = "landLeaf";
        String encryptMsg = encrypt(message, key);
        System.out.println("encrypted message is below :");
        System.out.println(encryptMsg);

        String decryptedMsg = decrypt(encryptMsg, key);
        System.out.println("decrypted message is below :");
        System.out.println(decryptedMsg);
    }
}

 

 


免責聲明!

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



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