andorid 使用3DES加解密

参考:
http://blog.csdn.net/lvxiangan/article/details/72529221

https://www.jianshu.com/p/251a619864f3



直接上代码:


/**
 * <pre>
 *      author : WangChaowei
 *      time   : 2018/3/12.
 *      desc   : 3DES 加解密
 *              双倍长密钥:16位
 *              三倍长密钥:24位
 *              加密流程是:1、先用前8字节加密成TMP1,
 *                         2、再用中8字节解密TMP1成TMP2,
 *                         3、最后用后8字节加密TMP2。
 * </pre>
 */

public class ThreeDESDemo {
    private static final String Algorithm = "DESede";//定义加密算法(3DES)
    private String keyString = "haha01234567899876543210";
    private byte[] key = null; //密钥(16位/24位)

    /**
     * 加密
     *
     * @param data 加密数据
     * @return
     */
    public String encrypt3DES(String data) {
        String result = null;
        try {
            //String转byte数组
            this.key = keyString.getBytes("UTF-8");

            SecretKey secretKey = new SecretKeySpec(key, Algorithm);
            //获取cipher对象
            Cipher cipher = Cipher.getInstance(Algorithm);
            //cipher初始化(加密)
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encrypt = cipher.doFinal(data.getBytes("UTF-8"));
            //base64转码成String(不用base64转String,可能有异常)
            result = new String(Base64.encode(encrypt, Base64.DEFAULT), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return "密钥有误,byte数组16位/24位";
        }
        return result;
    }

    /**
     * 解密
     *
     * @param data 解密数据
     * @return
     */
    public String decrypt3DES(String data) {
        String result = null;
        try {
            SecretKey secretKey = new SecretKeySpec(this.key, Algorithm);
            Cipher cipher = Cipher.getInstance(Algorithm);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] bytes = Base64.decode(data.getBytes("UTF-8"), Base64.DEFAULT);
            byte[] plain = cipher.doFinal(bytes);
            result = new String(plain, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值