Android數(shù)據(jù)加密之Aes加密

文章來源:http://www.cnblogs.com/whoislcj/p/5473030.html
前言:
項目中除了登陸露久,支付等接口采用rsa非對稱加密要尔,之外的采用aes對稱加密闹击,今天我們來認識一下aes加密妥畏。
其他幾種加密方式:
Android數(shù)據(jù)加密之Rsa加密

Android數(shù)據(jù)加密之Aes加密

Android數(shù)據(jù)加密之Des加密

Android數(shù)據(jù)加密之MD5加密

Android數(shù)據(jù)加密之Base64編碼算法

Android數(shù)據(jù)加密之異或加密算法

什么是aes加密智润?
高級加密標準(英語:Advanced Encryption Standard国葬,縮寫:AES)贤徒,在密碼學中又稱Rijndael加密法,是美國聯(lián)邦政府采用的一種區(qū)塊加密標準汇四。這個標準用來替代原先的DES接奈,已經(jīng)被多方分析且廣為全世界所使用。
接下來我們來實際看下具體怎么實現(xiàn):
對于AesUtils類常量簡介:

    private final static String HEX = "0123456789ABCDEF";
    private  static final String CBC_PKCS5_PADDING = "AES/CBC/PKCS5Padding";//AES是加密方式 CBC是工作模式 PKCS5Padding是填充模式
    private  static final String AES = "AES";//AES 加密
    private  static final String  SHA1PRNG="SHA1PRNG";//// SHA1PRNG 強隨機種子算法, 要區(qū)別4.2以上版本的調(diào)用方法

如何生成一個隨機Key通孽?

/*
     * 生成隨機數(shù)鲫趁,可以當做動態(tài)的密鑰 加密和解密的密鑰必須一致,不然將不能解密
     */
    public static String generateKey() {
        try {
            SecureRandom localSecureRandom = SecureRandom.getInstance(SHA1PRNG);
            byte[] bytes_key = new byte[20];
            localSecureRandom.nextBytes(bytes_key);
            String str_key = toHex(bytes_key);
            return str_key;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

Aes密鑰處理

// 對密鑰進行處理
    private static byte[] getRawKey(byte[] seed) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance(AES);
        //for android
        SecureRandom sr = null;
        // 在4.2以上版本中利虫,SecureRandom獲取方式發(fā)生了改變
        if (android.os.Build.VERSION.SDK_INT >= 17) {
            sr = SecureRandom.getInstance(SHA1PRNG, "Crypto");
        } else {
            sr = SecureRandom.getInstance(SHA1PRNG);
        }
        // for Java
        // secureRandom = SecureRandom.getInstance(SHA1PRNG);
        sr.setSeed(seed);
        kgen.init(128, sr); //256 bits or 128 bits,192bits
        //AES中128位密鑰版本有10個加密循環(huán)挨厚,192比特密鑰版本有12個加密循環(huán),256比特密鑰版本則有14個加密循環(huán)糠惫。
        SecretKey skey = kgen.generateKey();
        byte[] raw = skey.getEncoded();
        return raw;
    }

Aes加密過程

/*
     * 加密
     */
    public static String encrypt(String key, String cleartext) {
        if (TextUtils.isEmpty(cleartext)) {
            return cleartext;
        }
        try {
            byte[] result = encrypt(key, cleartext.getBytes());
            return Base64Encoder.encode(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /*
    * 加密
    */
    private static byte[] encrypt(String key, byte[] clear) throws Exception {
        byte[] raw = getRawKey(key.getBytes());
        SecretKeySpec skeySpec = new SecretKeySpec(raw, AES);
        Cipher cipher = Cipher.getInstance(CBC_PKCS5_PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[cipher.getBlockSize()]));
        byte[] encrypted = cipher.doFinal(clear);
        return encrypted;
    }

Aes解密過程

/*
     * 解密
     */
    public static String decrypt(String key, String encrypted) {
        if (TextUtils.isEmpty(encrypted)) {
            return encrypted;
        }
        try {
            byte[] enc = Base64Decoder.decodeToBytes(encrypted);
            byte[] result = decrypt(key, enc);
            return new String(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /*
     * 解密
     */
    private static byte[] decrypt(String key, byte[] encrypted) throws Exception {
        byte[] raw = getRawKey(key.getBytes());
        SecretKeySpec skeySpec = new SecretKeySpec(raw, AES);
        Cipher cipher = Cipher.getInstance(CBC_PKCS5_PADDING);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(new byte[cipher.getBlockSize()]));
        byte[] decrypted = cipher.doFinal(encrypted);
        return decrypted;
    }

二進制轉(zhuǎn)字符

//二進制轉(zhuǎn)字符
    public static String toHex(byte[] buf) {
        if (buf == null)
            return "";
        StringBuffer result = new StringBuffer(2 * buf.length);
        for (int i = 0; i < buf.length; i++) {
            appendHex(result, buf[i]);
        }
        return result.toString();
    }

    private static void appendHex(StringBuffer sb, byte b) {
        sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
    }

測試程序:

List<Person> personList = new ArrayList<>();
        int testMaxCount = 1000;//測試的最大數(shù)據(jù)條數(shù)
        //添加測試數(shù)據(jù)
        for (int i = 0; i < testMaxCount; i++) {
            Person person = new Person();
            person.setAge(i);
            person.setName(String.valueOf(i));
            personList.add(person);
        }
        //FastJson生成json數(shù)據(jù)
        String jsonData = JsonUtils.objectToJsonForFastJson(personList);
        Log.e("MainActivity", "AES加密前json數(shù)據(jù) ---->" + jsonData);
        Log.e("MainActivity", "AES加密前json數(shù)據(jù)長度 ---->" + jsonData.length());

        //生成一個動態(tài)key
        String secretKey = AesUtils.generateKey();
        Log.e("MainActivity", "AES動態(tài)secretKey ---->" + secretKey);

        //AES加密
        long start = System.currentTimeMillis();
        String encryStr = AesUtils.encrypt(secretKey, jsonData);
        long end = System.currentTimeMillis();
        Log.e("MainActivity", "AES加密耗時 cost time---->" + (end - start));
        Log.e("MainActivity", "AES加密后json數(shù)據(jù) ---->" + encryStr);
        Log.e("MainActivity", "AES加密后json數(shù)據(jù)長度 ---->" + encryStr.length());

        //AES解密
        start = System.currentTimeMillis();
        String decryStr = AesUtils.decrypt(secretKey, encryStr);
        end = System.currentTimeMillis();
        Log.e("MainActivity", "AES解密耗時 cost time---->" + (end - start));
        Log.e("MainActivity", "AES解密后json數(shù)據(jù) ---->" + decryStr);

運行耗時:



數(shù)據(jù)前后變化:


由此可見對稱Aes效率還是比較高的
補充關(guān)于Base64Decoder類和Base64Encoder類

package com.whoislcj.testhttp.utils;

import android.text.TextUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

public class Base64Decoder extends FilterInputStream {

    private static final char[] chars = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
            'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' };

    // A mapping between char values and six-bit integers
    private static final int[] ints = new int[128];
    static {
        for (int i = 0; i < 64; i++) {
            ints[chars[i]] = i;
        }
    }

    private int charCount;
    private int carryOver;

    /***
     * Constructs a new Base64 decoder that reads input from the given
     * InputStream.
     * 
     * @param in
     *            the input stream
     */
    private Base64Decoder(InputStream in) {
        super(in);
    }

    /***
     * Returns the next decoded character from the stream, or -1 if end of
     * stream was reached.
     * 
     * @return the decoded character, or -1 if the end of the input stream is
     *         reached
     * @exception IOException
     *                if an I/O error occurs
     */
    public int read() throws IOException {
        // Read the next non-whitespace character
        int x;
        do {
            x = in.read();
            if (x == -1) {
                return -1;
            }
        } while (Character.isWhitespace((char) x));
        charCount++;

        // The '=' sign is just padding
        if (x == '=') {
            return -1; // effective end of stream
        }

        // Convert from raw form to 6-bit form
        x = ints[x];

        // Calculate which character we're decoding now
        int mode = (charCount - 1) % 4;

        // First char save all six bits, go for another
        if (mode == 0) {
            carryOver = x & 63;
            return read();
        }
        // Second char use previous six bits and first two new bits,
        // save last four bits
        else if (mode == 1) {
            int decoded = ((carryOver << 2) + (x >> 4)) & 255;
            carryOver = x & 15;
            return decoded;
        }
        // Third char use previous four bits and first four new bits,
        // save last two bits
        else if (mode == 2) {
            int decoded = ((carryOver << 4) + (x >> 2)) & 255;
            carryOver = x & 3;
            return decoded;
        }
        // Fourth char use previous two bits and all six new bits
        else if (mode == 3) {
            int decoded = ((carryOver << 6) + x) & 255;
            return decoded;
        }
        return -1; // can't actually reach this line
    }

    /***
     * Reads decoded data into an array of bytes and returns the actual number
     * of bytes read, or -1 if end of stream was reached.
     * 
     * @param buf
     *            the buffer into which the data is read
     * @param off
     *            the start offset of the data
     * @param len
     *            the maximum number of bytes to read
     * @return the actual number of bytes read, or -1 if the end of the input
     *         stream is reached
     * @exception IOException
     *                if an I/O error occurs
     */
    public int read(byte[] buf, int off, int len) throws IOException {
        if (buf.length < (len + off - 1)) {
            throw new IOException("The input buffer is too small: " + len + " bytes requested starting at offset " + off + " while the buffer " + " is only " + buf.length + " bytes long.");
        }

        // This could of course be optimized
        int i;
        for (i = 0; i < len; i++) {
            int x = read();
            if (x == -1 && i == 0) { // an immediate -1 returns -1
                return -1;
            } else if (x == -1) { // a later -1 returns the chars read so far
                break;
            }
            buf[off + i] = (byte) x;
        }
        return i;
    }

    /***
     * Returns the decoded form of the given encoded string, as a String. Note
     * that not all binary data can be represented as a String, so this method
     * should only be used for encoded String data. Use decodeToBytes()
     * otherwise.
     * 
     * @param encoded
     *            the string to decode
     * @return the decoded form of the encoded string
     */
    public static String decode(String encoded) {
        if (TextUtils.isEmpty(encoded)) {
            return "";
        }
        return new String(decodeToBytes(encoded));
    }

    /***
     * Returns the decoded form of the given encoded string, as bytes.
     * 
     * @param encoded
     *            the string to decode
     * @return the decoded form of the encoded string
     */
    public static byte[] decodeToBytes(String encoded) {
        byte[] bytes = encoded.getBytes();
        Base64Decoder in = new Base64Decoder(new ByteArrayInputStream(bytes));
        ByteArrayOutputStream out = new ByteArrayOutputStream((int) (bytes.length * 0.75));
        try {
            byte[] buf = new byte[4 * 1024]; // 4K buffer
            int bytesRead;
            while ((bytesRead = in.read(buf)) != -1) {
                out.write(buf, 0, bytesRead);
            }
            return out.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                out.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

Base64Decoder
package com.whoislcj.testhttp.utils;

import java.io.ByteArrayOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class Base64Encoder extends FilterOutputStream {

    private static final char[] chars = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
            'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' };

    private int charCount;
    private int carryOver;
    // 是否每76字節(jié)換行
    private boolean isWrapBreak = true;

    /***
     * Constructs a new Base64 encoder that writes output to the given
     * OutputStream.
     * 
     * @param out
     *            the output stream
     */
    private Base64Encoder(OutputStream out) {
        super(out);
    }

    /***
     * Constructs a new Base64 encoder that writes output to the given
     * OutputStream.
     * 
     * @param out
     *            the output stream
     */
    private Base64Encoder(OutputStream out, boolean isWrapBreak) {
        this(out);
        this.isWrapBreak = isWrapBreak;
    }

    /***
     * Writes the given byte to the output stream in an encoded form.
     * 
     * @exception IOException
     *                if an I/O error occurs
     */
    public void write(int b) throws IOException {
        // Take 24-bits from three octets, translate into four encoded chars
        // Break lines at 76 chars
        // If necessary, pad with 0 bits on the right at the end
        // Use = signs as padding at the end to ensure encodedLength % 4 == 0

        // Remove the sign bit,
        // thanks to Christian Schweingruber <chrigu@lorraine.ch>
        if (b < 0) {
            b += 256;
        }

        // First byte use first six bits, save last two bits
        if (charCount % 3 == 0) {
            int lookup = b >> 2;
            carryOver = b & 3; // last two bits
            out.write(chars[lookup]);
        }
        // Second byte use previous two bits and first four new bits,
        // save last four bits
        else if (charCount % 3 == 1) {
            int lookup = ((carryOver << 4) + (b >> 4)) & 63;
            carryOver = b & 15; // last four bits
            out.write(chars[lookup]);
        }
        // Third byte use previous four bits and first two new bits,
        // then use last six new bits
        else if (charCount % 3 == 2) {
            int lookup = ((carryOver << 2) + (b >> 6)) & 63;
            out.write(chars[lookup]);
            lookup = b & 63; // last six bits
            out.write(chars[lookup]);
            carryOver = 0;
        }
        charCount++;

        // Add newline every 76 output chars (that's 57 input chars)
        if (this.isWrapBreak && charCount % 57 == 0) {
            out.write('\n');
        }
    }

    /***
     * Writes the given byte array to the output stream in an encoded form.
     * 
     * @param buf
     *            the data to be written
     * @param off
     *            the start offset of the data
     * @param len
     *            the length of the data
     * @exception IOException
     *                if an I/O error occurs
     */
    public void write(byte[] buf, int off, int len) throws IOException {
        // This could of course be optimized
        for (int i = 0; i < len; i++) {
            write(buf[off + i]);
        }
    }

    /***
     * Closes the stream, this MUST be called to ensure proper padding is
     * written to the end of the output stream.
     * 
     * @exception IOException
     *                if an I/O error occurs
     */
    public void close() throws IOException {
        // Handle leftover bytes
        if (charCount % 3 == 1) { // one leftover
            int lookup = (carryOver << 4) & 63;
            out.write(chars[lookup]);
            out.write('=');
            out.write('=');
        } else if (charCount % 3 == 2) { // two leftovers
            int lookup = (carryOver << 2) & 63;
            out.write(chars[lookup]);
            out.write('=');
        }
        super.close();
    }

    /***
     * Returns the encoded form of the given unencoded string.<br>
     * 默認是否每76字節(jié)換行
     * 
     * @param bytes
     *            the bytes to encode
     * @return the encoded form of the unencoded string
     * @throws IOException
     */
    public static String encode(byte[] bytes) {
        return encode(bytes, true);
    }

    /***
     * Returns the encoded form of the given unencoded string.
     * 
     * @param bytes
     *            the bytes to encode
     * @param isWrapBreak
     *            是否每76字節(jié)換行
     * @return the encoded form of the unencoded string
     * @throws IOException
     */
    public static String encode(byte[] bytes, boolean isWrapBreak) {
        ByteArrayOutputStream out = new ByteArrayOutputStream((int) (bytes.length * 1.4));
        Base64Encoder encodedOut = new Base64Encoder(out, isWrapBreak);
        try {
            encodedOut.write(bytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                encodedOut.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return out.toString();
    }

    // public static void main(String[] args) throws Exception {
    // if (args.length != 1) {
    // System.err
    // .println("Usage: java com.oreilly.servlet.Base64Encoder fileToEncode");
    // return;
    // }
    // Base64Encoder encoder = null;
    // BufferedInputStream in = null;
    // try {
    // encoder = new Base64Encoder(System.out);
    // in = new BufferedInputStream(new FileInputStream(args[0]));
    //
    // byte[] buf = new byte[4 * 1024]; // 4K buffer
    // int bytesRead;
    // while ((bytesRead = in.read(buf)) != -1) {
    // encoder.write(buf, 0, bytesRead);
    // }
    // } finally {
    // if (in != null)
    // in.close();
    // if (encoder != null)
    // encoder.close();
    // }
    // }
}

Base64Encoder
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末疫剃,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子硼讽,更是在濱河造成了極大的恐慌巢价,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,590評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件固阁,死亡現(xiàn)場離奇詭異壤躲,居然都是意外死亡,警方通過查閱死者的電腦和手機备燃,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,157評論 3 399
  • 文/潘曉璐 我一進店門碉克,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人并齐,你說我怎么就攤上這事漏麦】退埃” “怎么了?”我有些...
    開封第一講書人閱讀 169,301評論 0 362
  • 文/不壞的土叔 我叫張陵撕贞,是天一觀的道長更耻。 經(jīng)常有香客問我,道長捏膨,這世上最難降的妖魔是什么秧均? 我笑而不...
    開封第一講書人閱讀 60,078評論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮号涯,結(jié)果婚禮上目胡,老公的妹妹穿的比我還像新娘。我一直安慰自己诚隙,他們只是感情好讶隐,可當我...
    茶點故事閱讀 69,082評論 6 398
  • 文/花漫 我一把揭開白布起胰。 她就那樣靜靜地躺著久又,像睡著了一般。 火紅的嫁衣襯著肌膚如雪效五。 梳的紋絲不亂的頭發(fā)上地消,一...
    開封第一講書人閱讀 52,682評論 1 312
  • 那天,我揣著相機與錄音畏妖,去河邊找鬼脉执。 笑死,一個胖子當著我的面吹牛戒劫,可吹牛的內(nèi)容都是我干的半夷。 我是一名探鬼主播,決...
    沈念sama閱讀 41,155評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼迅细,長吁一口氣:“原來是場噩夢啊……” “哼巫橄!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起茵典,我...
    開封第一講書人閱讀 40,098評論 0 277
  • 序言:老撾萬榮一對情侶失蹤湘换,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后统阿,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體彩倚,經(jīng)...
    沈念sama閱讀 46,638評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,701評論 3 342
  • 正文 我和宋清朗相戀三年扶平,在試婚紗的時候發(fā)現(xiàn)自己被綠了帆离。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,852評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡结澄,死狀恐怖盯质,靈堂內(nèi)的尸體忽然破棺而出袁串,到底是詐尸還是另有隱情,我是刑警寧澤呼巷,帶...
    沈念sama閱讀 36,520評論 5 351
  • 正文 年R本政府宣布囱修,位于F島的核電站,受9級特大地震影響王悍,放射性物質(zhì)發(fā)生泄漏破镰。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,181評論 3 335
  • 文/蒙蒙 一压储、第九天 我趴在偏房一處隱蔽的房頂上張望鲜漩。 院中可真熱鬧,春花似錦集惋、人聲如沸孕似。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,674評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽喉祭。三九已至,卻和暖如春雷绢,著一層夾襖步出監(jiān)牢的瞬間泛烙,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,788評論 1 274
  • 我被黑心中介騙來泰國打工翘紊, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留蔽氨,地道東北人。 一個月前我還...
    沈念sama閱讀 49,279評論 3 379
  • 正文 我出身青樓帆疟,卻偏偏與公主長得像鹉究,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子踪宠,可洞房花燭夜當晚...
    茶點故事閱讀 45,851評論 2 361

推薦閱讀更多精彩內(nèi)容