AES加密解密技術

通常都據說過MD5加密技術,MD5加密確實強大。但那是非對稱加密技術,也就是說從密文變成明文不是那麼容易。當咱們須要一種對稱性加密技術,MD5就不適用了。好比視頻加密解密,此時就能夠用ASE加密解密了。java

AES有更安全、靈活、有效率等優勢,使用範圍也很廣,因此今天就講講AES加密如何使用,這裏以java開展。安全

密鑰

  1. 就是把明文轉換爲密文,密文轉換爲明文的一把鑰匙。接下來咱們會用ASE加密技術生成一把密鑰。學習

public void generateSecretKey() {
    KeyGenerator keyGenerator = null;
    FileOutputStream fos = null;
    try {
        keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128);//size
        SecretKey secretKey = keyGenerator.generateKey();
        byte[] keyBytes = secretKey.getEncoded();
        fos = new FileOutputStream("key");
        fos.write(keyBytes);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (fos != null) {
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

keyGenerator.init(128); 這裏是初始化密鑰的長度。翻看底層代碼,發現密鑰支持的長度爲:128, 192 or 256。咱們這裏是128位的長度,也就是16byte。加密

補充: 剛學習的時候,看到網上有人把密鑰(字節碼)轉變成字符串保存,而後用來加密解密的時候,頗有可能出錯。由於不一樣語言的緣由,字符串轉變成字節碼就有可能再也不是原來的字節碼了。code

密鑰生成後,在項目目錄下能夠找到一個key文件。視頻

加密

將明文和密鑰一塊兒,做爲參數傳入。ip

/**
 * ASE 加密
 * @param str 明文
 * @param key 祕鑰
 * @return
 */
public static String enStr(String str, byte[] key) {
    Cipher cipher = null;
    SecretKey generateKey = null;
    try {
        generateKey = new SecretKeySpec(key, "AES");
        cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, generateKey);
        byte[] resultBytes = cipher.doFinal(str.getBytes());
        return Hex.encodeHexString(resultBytes);
    } catch (Exception e) {
        logger.error("AES加密出錯", e);
    }
    return null;
}

解密

解密就是加密的互逆過程,因此代碼很相似。ci

/**
 * 解密
 * @param key 祕鑰
 * @param str 密文
 * @return
 */
public static String deStr(String str, byte[] key) {
    Cipher cipher = null;
    SecretKey generateKey = null;
    try {
        generateKey = new SecretKeySpec(key, "AES");
        cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, generateKey);
        byte[] result = Hex.decodeHex(str.toCharArray());
        return new String(cipher.doFinal(result));

    } catch(Exception e) {
        logger.error("ASE解密出錯", e);
    }
    return null;
}
相關文章
相關標籤/搜索