android使用AES加密和解密文件实例代码
程序员文章站
2023-12-10 19:51:10
前言
最近公司需要对本公司的一些下载文件进行加密解密需求,也就尝试去实现下,其实需要借助第三方的jar包:bcprov-jdk15on-155.jar,下载这个可以到...
前言
最近公司需要对本公司的一些下载文件进行加密解密需求,也就尝试去实现下,其实需要借助第三方的jar包:bcprov-jdk15on-155.jar,下载这个可以到网上搜或者下载本人的demo即可,注意:需要加密和解密的key是一致的才可以解密,不然就会解密失败。不多说,直接上代码。
效果图
代码:
实现加密解密逻辑代码
package com.vsoontech.p2p.sample; import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import java.security.invalidkeyexception; import java.security.key; import java.security.nosuchalgorithmexception; import java.security.securerandom; import javax.crypto.badpaddingexception; import javax.crypto.cipher; import javax.crypto.illegalblocksizeexception; import javax.crypto.keygenerator; import javax.crypto.nosuchpaddingexception; import javax.crypto.shortbufferexception; /** * @author zhou * @since 2016/9/26 */ public enum aes { instance; private key key; /** * 生成aes对称秘钥 */ public string generatekey() throws nosuchalgorithmexception { keygenerator keygen = keygenerator.getinstance("aes"); securerandom random = new securerandom(); keygen.init(random); this.key = keygen.generatekey(); return "algorithm format encoded:" + key.getalgorithm() + " - " + key.getformat() + " - " + new string(key.getencoded()); } /** * 加密 */ public void encrypt(inputstream in) throws invalidkeyexception, shortbufferexception, illegalblocksizeexception, badpaddingexception, nosuchalgorithmexception, nosuchpaddingexception, ioexception { this.crypt(in, null, cipher.encrypt_mode); } /** * 解密 */ public string decrypt(inputstream in) throws invalidkeyexception, shortbufferexception, illegalblocksizeexception, badpaddingexception, nosuchalgorithmexception, nosuchpaddingexception, ioexception { return this.crypt(in, cipher.decrypt_mode); } /** * 加密 */ public void encrypt(inputstream in, outputstream out) throws invalidkeyexception, shortbufferexception, illegalblocksizeexception, badpaddingexception, nosuchalgorithmexception, nosuchpaddingexception, ioexception { this.crypt(in, out, cipher.encrypt_mode); } /** * 解密 */ public void decrypt(inputstream in, outputstream out) throws invalidkeyexception, shortbufferexception, illegalblocksizeexception, badpaddingexception, nosuchalgorithmexception, nosuchpaddingexception, ioexception { this.crypt(in, out, cipher.decrypt_mode); } /** * 实际的加密解密过程 */ public void crypt(inputstream in, outputstream out, int mode) throws ioexception, shortbufferexception, illegalblocksizeexception, badpaddingexception, nosuchalgorithmexception, nosuchpaddingexception, invalidkeyexception { cipher cipher = cipher.getinstance("aes"); cipher.init(mode, this.key); int blocksize = cipher.getblocksize(); int outputsize = cipher.getoutputsize(blocksize); byte[] inbytes = new byte[blocksize]; byte[] outbytes = new byte[outputsize]; int inlength = 0; boolean more = true; while (more) { inlength = in.read(inbytes); if (inlength == blocksize) { //只要输入数据块具有全长度(长度可被8整除),调用update方法 int outlength = cipher.update(inbytes, 0, blocksize, outbytes); if (out != null) out.write(outbytes, 0, outlength); } else { more = false; } } if (inlength > 0) //不具有全长度,调用dofinal方法 outbytes = cipher.dofinal(inbytes, 0, inlength); else outbytes = cipher.dofinal(); if (out != null) { out.write(outbytes); out.flush(); } } /** * 实际的加密解密过程 */ public string crypt(inputstream in, int mode) throws ioexception, shortbufferexception, illegalblocksizeexception, badpaddingexception, nosuchalgorithmexception, nosuchpaddingexception, invalidkeyexception { cipher cipher = cipher.getinstance("aes"); cipher.init(mode, this.key); int blocksize = cipher.getblocksize(); int outputsize = cipher.getoutputsize(blocksize); byte[] inbytes = new byte[blocksize]; byte[] outbytes = new byte[outputsize]; int inlength = 0; boolean more = true; stringbuilder sb = new stringbuilder(); while (more) { inlength = in.read(inbytes); if (inlength == blocksize) { //只要输入数据块具有全长度(长度可被8整除),调用update方法 int outlength = cipher.update(inbytes, 0, blocksize, outbytes); } else { more = false; } } if (inlength > 0) //不具有全长度,调用dofinal方法 outbytes = cipher.dofinal(inbytes, 0, inlength); else outbytes = cipher.dofinal(); sb.append(new string(outbytes)); return sb.tostring(); } public void setkey(key key) { this.key = key; } public key getkey() { return key; } }
生成秘钥代码
package com.vsoontech.p2p.sample; import org.bouncycastle.jce.provider.bouncycastleprovider; import java.io.file; import java.io.fileinputstream; import java.io.fileoutputstream; import java.security.key; import java.security.nosuchalgorithmexception; import javax.crypto.cipher; import javax.crypto.keygenerator; import javax.crypto.secretkey; import javax.crypto.spec.ivparameterspec; import javax.crypto.spec.secretkeyspec; /** * @author zhou * @since 2016/9/26 */ public class aeskeymodel { public static final string key_algorithm = "aes"; private static final string default_cipher_algorithm = "aes/cbc/pkcs5padding"; private string srcfile = "", destionfile = ""; /** * 初始化密钥 * * @return byte[] 密钥 * @throws exception */ public byte[] initsecretkey() { //返回生成指定算法的秘密密钥的 keygenerator 对象 keygenerator kg = null; try { kg = keygenerator.getinstance(key_algorithm); } catch (nosuchalgorithmexception e) { e.printstacktrace(); return new byte[0]; } //初始化此密钥生成器,使其具有确定的密钥大小 //aes 要求密钥长度为 128 kg.init(128); //生成一个密钥 secretkey secretkey = kg.generatekey(); return secretkey.getencoded(); } public void setdestionfile(string destionfile) { this.destionfile = destionfile; } public void setsrcfile(string srcfile) { this.srcfile = srcfile; } /** * 转换密钥 * * @param key 二进制密钥 * @return 密钥 */ private static key tokey(byte[] key) { //生成密钥 return new secretkeyspec(key, key_algorithm); } /** * 加密 * * @param data 待加密数据 * @param key 密钥 * @return byte[] 加密数据 * @throws exception */ public static byte[] encrypt(byte[] data, key key) throws exception { return encrypt(data, key, default_cipher_algorithm); } /** * 加密 * * @param data 待加密数据 * @param key 二进制密钥 * @return byte[] 加密数据 * @throws exception */ public static byte[] encrypt(byte[] data, byte[] key) throws exception { return encrypt(data, key, default_cipher_algorithm); } /** * 加密 * * @param data 待加密数据 * @param key 二进制密钥 * @param cipheralgorithm 加密算法/工作模式/填充方式 * @return byte[] 加密数据 * @throws exception */ public static byte[] encrypt(byte[] data, byte[] key, string cipheralgorithm) throws exception { //还原密钥 key k = tokey(key); return encrypt(data, k, cipheralgorithm); } /** * 加密 * * @param data 待加密数据 * @param key 密钥 * @param cipheralgorithm 加密算法/工作模式/填充方式 * @return byte[] 加密数据 * @throws exception */ public static byte[] encrypt(byte[] data, key key, string cipheralgorithm) throws exception { //实例化 cipher cipher = cipher.getinstance(cipheralgorithm); //使用密钥初始化,设置为加密模式 cipher.init(cipher.encrypt_mode, key); //执行操作 return cipher.dofinal(data); } /** * 解密 * * @param data 待解密数据 * @param key 二进制密钥 * @return byte[] 解密数据 * @throws exception */ public static byte[] decrypt(byte[] data, byte[] key) throws exception { return decrypt(data, key, default_cipher_algorithm); } /** * 解密 * * @param data 待解密数据 * @param key 密钥 * @return byte[] 解密数据 * @throws exception */ public static byte[] decrypt(byte[] data, key key) throws exception { return decrypt(data, key, default_cipher_algorithm); } /** * 解密 * * @param data 待解密数据 * @param key 二进制密钥 * @param cipheralgorithm 加密算法/工作模式/填充方式 * @return byte[] 解密数据 * @throws exception */ public static byte[] decrypt(byte[] data, byte[] key, string cipheralgorithm) throws exception { //还原密钥 key k = tokey(key); return decrypt(data, k, cipheralgorithm); } /** * 解密 * * @param data 待解密数据 * @param key 密钥 * @param cipheralgorithm 加密算法/工作模式/填充方式 * @return byte[] 解密数据 * @throws exception */ public static byte[] decrypt(byte[] data, key key, string cipheralgorithm) throws exception { //实例化 cipher cipher = cipher.getinstance(cipheralgorithm); //使用密钥初始化,设置为解密模式 cipher.init(cipher.decrypt_mode, key); //执行操作 return cipher.dofinal(data); } public void encryptionfile(key sessionkey) throws exception { int len = 0; byte[] buffer = new byte[1024]; byte[] cipherbuffer = null; // 使用会话密钥对文件加密。 cipher cipher = cipher.getinstance(default_cipher_algorithm, new bouncycastleprovider()); ivparameterspec iv = new ivparameterspec("0000000000123456".getbytes()); cipher.init(cipher.encrypt_mode, sessionkey, iv); fileinputstream fis = new fileinputstream(new file(srcfile)); fileoutputstream fos = new fileoutputstream(new file(destionfile)); // 读取原文,加密并写密文到输出文件。 while ((len = fis.read(buffer)) != -1) { cipherbuffer = cipher.update(buffer, 0, len); fos.write(cipherbuffer); fos.flush(); } cipherbuffer = cipher.dofinal(); fos.write(cipherbuffer); fos.flush(); if (fis != null) fis.close(); if (fos != null) fos.close(); } public void descryptionfile(key sessionkey) throws exception { int len = 0; byte[] buffer = new byte[5 * 1024]; byte[] plainbuffer = null; cipher cipher = cipher.getinstance(default_cipher_algorithm, new bouncycastleprovider()); ivparameterspec iv = new ivparameterspec("0000000000123456".getbytes()); cipher.init(cipher.decrypt_mode, sessionkey, iv); fileinputstream fis = new fileinputstream(new file(srcfile)); fileoutputstream fos = new fileoutputstream(new file(destionfile)); while ((len = fis.read(buffer)) != -1) { plainbuffer = cipher.update(buffer, 0, len); fos.write(plainbuffer); fos.flush(); } plainbuffer = cipher.dofinal(); fos.write(plainbuffer); fos.flush(); if (fis != null) fis.close(); if (fos != null) fos.close(); } }
加密逻辑示例代码
/** * 加密 * * @param path * @param destionfile */ private void aes(string path, string destionfile) { try { log.d(tag, "aes key: " + aes.instance.generatekey()); fileinputstream fis = new fileinputstream(new file(path)); fileoutputstream fos = new fileoutputstream(new file(destionfile)); aes.instance.encrypt(fis, fos); } catch (exception e) { log.d(tag, "exception: " + e.tostring()); e.printstacktrace(); } }
解密逻辑示例代码:
/** * aes解密文件 * * @param path 需要解密的文件目录 */ private void aesjiemi(string path) { file f = new file(path); if (!f.exists() || f.isdirectory()) toast.maketext(getapplicationcontext(), "该文件不合法!", toast.length_short).show(); else { string prefix = f.getname().substring(0, f.getname().indexof('.')); string suffix = f.getname().substring(f.getname().indexof('.')); string outjiemifile = environment.getexternalstoragedirectory() + file.separator + prefix + "aes_jiemi" + suffix; aeskeymodel model_aes = new aeskeymodel(); model_aes.setsrcfile(path); model_aes.setdestionfile(outjiemifile); try { // model_aes.descryptionfile(key_aes); model_aes.descryptionfile(key_aes); // todo: 加密后的文件 randomaccessfile raf = new randomaccessfile(path, "rw"); log.d(tag, "解密后 file length: " + raf.length()); log.d(tag, "解密后 file content: " + raf.readline()); } catch (exception e) { e.printstacktrace(); } } }
总结:
注意秘钥需要一致。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。