Android中自带的加密和解密

来源:互联网 发布:站长工具seo是查啥的 编辑:程序博客网 时间:2024/06/05 12:42

在当今社会信息安全越来越重要,其中最为关键的就是传输过程中的安全。这就需要一套安全可靠且有效的加密和解密算法来实现。

Android中有一套成熟的加密和解密的模块。下面不多说直接上代码,大家一看就知道了!

public class DESUtils {/** * 报表json密钥 */private final static String DES = "DES";public final static String PASSWORD_CRYPT_KEY = "_mapp_hz_server_";static {//这个有什么作用??//Security.addProvider(new BouncyCastleProvider());}/** * 加密 *  * @param src *            数据源 * @param key *            密钥,长度必须是8的倍数 * @return 返回加密后的数据 * @throws Exception */public static byte[] encrypt(byte[] src, byte[] key) throws Exception {//产生一个可信任的随机数源SecureRandom sr = new SecureRandom();// 从原始密匙数据创建DESKeySpec对象DESKeySpec dks = new DESKeySpec(key);// 创建一个密匙工厂,然后用它把DESKeySpec转换成// 一个SecretKey对象SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);SecretKey securekey = keyFactory.generateSecret(dks);// Cipher对象实际完成加密操作Cipher cipher = Cipher.getInstance("DES/ECB/PKCS7Padding", "BC");// Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");// Cipher cipher = Cipher.getInstance("DES/CBC/NoPadding");// 用密匙初始化Cipher对象cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);//encrypt_mode// 现在,获取数据并加密// 正式执行加密操作return cipher.doFinal(src);}/** * 解密 *  * @param src *            数据源 * @param key *            密钥,长度必须是8的倍数 * @return 返回解密后的原始数据 * @throws Exception */public static byte[] decrypt(byte[] src, byte[] key) throws Exception {//产生一个可信任的随机数源SecureRandom sr = new SecureRandom();// 从原始密匙数据创建DESKeySpec对象DESKeySpec dks = new DESKeySpec(key);// 创建一个密匙工厂,然后用它把DESKeySpec转换成// 一个SecretKey对象SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);SecretKey securekey = keyFactory.generateSecret(dks);// Cipher对象实际完成解密操作Cipher cipher = Cipher.getInstance("DES/ECB/PKCS7Padding", "BC");// Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");// Cipher cipher = Cipher.getInstance("DES/CBC/NoPadding");cipher.init(Cipher.DECRYPT_MODE, securekey, sr);//decrypt_mode// 现在,获取数据并解密// 正式执行解密操作return cipher.doFinal(src);}/** * 密码解密 *  * @param data * @return * @throws Exception */public final static String decrypt(String hex, String pwd) {try {String data = new String(decrypt(hex2byte(GZip2Utils.decompress(decryptBASE64(hex))),pwd.getBytes()), "UTF-8");return data;} catch (Exception e) {e.printStackTrace();}return null;}/** * 密码加密 * @param password * @return * @throws Exception */public final static String encrypt(String data, String pwd) {try {Log.w("System.out", "加密前的值为:data="+data);Log.w("System.out", "加密前的值为:pwd="+pwd);String hex = byte2hex(encrypt(data.getBytes("UTF-8"),pwd.getBytes()));hex = encryptBASE64(GZip2Utils.compress(hex.getBytes("UTF-8")));Log.w("System.out", "加密后的值为:"+hex);return hex;} catch (Exception e) {e.printStackTrace();}return null;}// Base64.encodeToString(m, Base64.NO_WRAP)/** * BASE64解密 *  * @param key * @return * @throws Exception */public static byte[] decryptBASE64(String key) throws Exception {return android.util.Base64.decode(key, android.util.Base64.NO_WRAP);}/** * BASE64加密 *  * @param key * @return * @throws Exception */public static String encryptBASE64(byte[] key) throws Exception {return android.util.Base64.encodeToString(key,android.util.Base64.NO_WRAP);}/** *  * 二行制转字符串 *  * @param b *  * @return */public static String byte2hex(byte[] b) {String hs = "";String stmp = "";for (int n = 0; n < b.length; n++) {stmp = (Integer.toHexString(b[n] & 0XFF));//变为十六进制的字符串if (stmp.length() == 1)hs = hs + "0" + stmp;elsehs = hs + stmp;}return hs.toUpperCase();}// 将byte数组进行处理生产新的的byte数组public static byte[] hex2byte(byte[] b) {if ((b.length % 2) != 0)throw new IllegalArgumentException("长度不是偶数");byte[] b2 = new byte[b.length / 2];for (int n = 0; n < b.length; n += 2) {String item = new String(b, n, 2);b2[n / 2] = (byte) Integer.parseInt(item, 16);//将字符串变为十六进制数。}return b2;}public static void main(String[] args) throws Exception {try {} catch (Exception e) {e.printStackTrace();}}public static String encryptNoDes(String jsonStr, String passwordCryptKey) {String str = "";try {str = encryptBASE64(GZip2Utils.compress(jsonStr.getBytes("UTF-8")));} catch (Exception e) {}return str;}public final static String decryptNoDes(String str, String pwd) {String data = "";try {data = new String(GZip2Utils.decompress(decryptBASE64(str)), "UTF-8");} catch (Exception e) {}return data;}}

public abstract class GZip2Utils {    private static final int BUFFER = 1024;    private static final CharSequence EXT = ".bz2";    public static byte[] compress(byte[] data) throws Exception {        ByteArrayInputStream bais = new ByteArrayInputStream(data);        ByteArrayOutputStream baos = new ByteArrayOutputStream();        compress(bais, baos);        byte[] output = baos.toByteArray();        baos.flush();        baos.close();        bais.close();        return output;    }    public static void compress(File file) throws Exception {        compress(file, true);    }    public static void compress(File file, boolean delete) throws Exception {        FileInputStream fis = new FileInputStream(file);        FileOutputStream fos = new FileOutputStream(file.getPath() + EXT);        compress(fis, fos);        fis.close();        fos.flush();        fos.close();        if (delete) {           file.delete();        }   }    public static void compress(InputStream is, OutputStream os)            throws Exception {    GZIPOutputStream gos = new GZIPOutputStream(os);        try {int count;byte data[] = new byte[BUFFER];while ((count = is.read(data, 0, BUFFER)) != -1) {    gos.write(data, 0, count);}gos.finish();gos.close();} catch (Exception e) {}finally{gos.close();}    }    public static void compress(String path) throws Exception {        compress(path, true);    }    public static void compress(String path, boolean delete) throws Exception {       File file = new File(path);       compress(file, delete);    }    public static byte[] decompress(byte[] data) throws Exception {        ByteArrayInputStream bais = new ByteArrayInputStream(data);        ByteArrayOutputStream baos = new ByteArrayOutputStream();        decompress(bais, baos);        data = baos.toByteArray();        baos.flush();        baos.close();        bais.close();       return data;    }    public static void decompress(File file) throws Exception {        decompress(file, true);    }    public static void decompress(File file, boolean delete) throws Exception {        FileInputStream fis = new FileInputStream(file);        FileOutputStream fos = new FileOutputStream(file.getPath().replace(EXT,                ""));        decompress(fis, fos);        fis.close();        fos.flush();        fos.close();        if (delete) {            file.delete();        }    }    public static void decompress(InputStream is, OutputStream os)            throws Exception {    GZIPInputStream gis = new GZIPInputStream(is);        int count;        byte data[] = new byte[BUFFER];        while ((count = gis.read(data, 0, BUFFER)) != -1) {           os.write(data, 0, count);       }        gis.close();    }    public static void decompress(String path) throws Exception {        decompress(path, true);    }    public static void decompress(String path, boolean delete) throws Exception {        File file = new File(path);        decompress(file, delete);    }}

通过调用这两个类中加密和解密函数就可以做到安全有效的加密和解密啦。当然还有其他的算法这里就不详细解释啦。

0 0
原创粉丝点击