Java加密技術相關__Java

來源:互聯網
上載者:User
1、ECB加密模式是最簡單的模式,每一個資料區塊之間沒有任何關係。因此它不需要也不能使用IV(初始化向量:Initialization vector)。預設的加密模式就是ECB(直接使用"AES"擷取演算法時)   2、其它加密模式需要使用IV,IV的使用方式: IvParameterSpec iv = new IvParameterSpec(keyBytes);
encypher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, alogorithmBase), iv); 注意進行加密時不指定初始化向量不會報錯,但是每次加密的結果都可能不同,不可預知。解密時必須制定初始化向量,否則會拋出異常。   3、沒有指定IV時,加密器會產生一個IV,產生演算法可能是隨機演算法。可以使用cliper.getIV()來擷取其產生的IV。再使用該IV進行解密就沒有問題了。通過更換IV也是演算法的一種安全保障。
import android.util.Base64;import java.security.Key;import javax.crypto.Cipher;import javax.crypto.spec.IvParameterSpec;import javax.crypto.spec.SecretKeySpec;public class EncryptUtil {    /**     * close     *     * @param content     * @param key     * @return     */    public static String encrypt4AES(String content, String key) {        try {            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");            IvParameterSpec iv = new IvParameterSpec(initIv());            SecretKeySpec key1 = new SecretKeySpec(key.getBytes(), "AES");            cipher.init(Cipher.ENCRYPT_MODE, key1, iv);            byte[] encryptedData = cipher.doFinal(content.getBytes());            String encryptResultStr = Base64.encodeToString(encryptedData, Base64.NO_WRAP);//不換行            return encryptResultStr;        } catch (Exception e) {            e.printStackTrace();        }        return null;    }    /**     * 位移量.保證每次產生密文的唯一性     *     * @return     */    private static byte[] initIv() {        String iv = "0000000000000000";        return iv.getBytes();    }    /**     * @param content     * @param pass     * @return open     */    public static String deCiphering(String content, String pass) {        byte[] bytea = Base64.decode(content, Base64.NO_WRAP);        IvParameterSpec iv = new IvParameterSpec(initIv());        Key key = new SecretKeySpec(pass.getBytes(), "AES");        Cipher cipher = null;        try {            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");            cipher.init(Cipher.DECRYPT_MODE, key, iv);               //與加密時不同MODE:Cipher.DECRYPT_MODE            byte[] ret = cipher.doFinal(bytea);            return new String(ret, "utf-8");        } catch (Exception e) {            e.printStackTrace();        }        return null;    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.