Java - 加密

编码算法

首先准备好原文

 static String name = "我喜欢你";

URL编码算法

    /*
     * 编码算法
     * */
    @Test
    public void URLEncodeTest() {
        String s = URLEncoder.encode(name, StandardCharsets.UTF_8); // URL编码
        System.out.println(s);
        String decode = URLDecoder.decode(s, StandardCharsets.UTF_8);//URL解码
        System.out.println(decode);
    }

Base64编码算法

    @Test
    public void base64Test() {
        byte[] bytes = name.getBytes(StandardCharsets.UTF_8);
        String encodeToString = Base64.getEncoder().encodeToString(bytes);  //Base64编码
        System.out.println(encodeToString);
        byte[] decode = Base64.getDecoder().decode(encodeToString); //Base64解码
        String s = new String(decode);
        System.out.println(s);
    }

哈希算法

这里以MD5为例

    /*
     * 哈希算法  
     * */
    @Test
    public void md5Test() {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5"); //获取MD5实例
            md.update(name.getBytes(StandardCharsets.UTF_8));  //输入数据
            byte[] bytes = md.digest();     //
            System.out.println(new BigInteger(1, bytes).toString(16)); //转换为16进制的字符输出
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

更多哈希算法可见官网算法,只需要更换实例名称即可。

对称加密算法

以AES加密为例,即有一个密匙,可以是128/192/256位的byte数组
public void arsTest() throws Exception {
        // 128位密钥 = 16 bytes Key:
        byte[] key = "1234567890abcdef".getBytes("UTF-8");
        // 开始加密
        byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8);
        byte[] encrypt = encrypt(key, nameBytes);
        System.out.println("加密:" + new String(encrypt));
        // 解密
        byte[] decrypt = decrypt(key, encrypt);
        System.out.println("解密:" + new String(decrypt));
    }

    // 加密
    public static byte[] encrypt(byte[] key, byte[] nameBytes) throws GeneralSecurityException {
        Cipher instance = Cipher.getInstance("AES/ECB/PKCS5Padding");
        SecretKey secretKey = new SecretKeySpec(key, "AES");
        instance.init(Cipher.ENCRYPT_MODE, secretKey);
        return instance.doFinal(nameBytes);
    }

    //解密
    public static byte[] decrypt(byte[] key, byte[] encrypt) throws GeneralSecurityException {
        Cipher instance = Cipher.getInstance("AES/ECB/PKCS5Padding");
        SecretKey secretKey = new SecretKeySpec(key, "AES");
        instance.init(Cipher.DECRYPT_MODE, secretKey);
        return instance.doFinal(encrypt);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值