前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android中自带的加密和解密

Android中自带的加密和解密

作者头像
林老师带你学编程
发布2022-11-30 10:22:43
7600
发布2022-11-30 10:22:43
举报
文章被收录于专栏:强仔仔

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

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

代码语言:javascript
复制
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;
			else
				hs = 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;
	}

}
代码语言:javascript
复制
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);
    }

}

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2015-09-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
腾讯云 BI
腾讯云 BI(Business Intelligence,BI)提供从数据源接入、数据建模到数据可视化分析全流程的BI能力,帮助经营者快速获取决策数据依据。系统采用敏捷自助式设计,使用者仅需通过简单拖拽即可完成原本复杂的报表开发过程,并支持报表的分享、推送等企业协作场景。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档