ASC+Base64加密算法 根据用户id生成秘钥

文章介绍了如何在Java中使用AES加密算法,结合Base64URL编码避免特殊字符,实现在生成用户密钥时的安全链接,确保用户无需登录即可访问系统。
摘要由CSDN通过智能技术生成

需要是要根据用户的id生成密钥 通过密钥生成免登录链接 实现用户根据链接直接访问系统

标准Base64编码包含特殊字符,会被转义 从而登录失败要使生成的密文不包含特殊字符,您可以使用Base64URL编码代替标准的Base64编码。Base64URL编码使用'-'和'_'替换了标准Base64编码中的'+'和'/',并且省略了末尾的'='。这样就可以避免生成的密文包含特殊字符。

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
 
public class AESUtils {
    public static String encryptLongId(long id, String key) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(String.valueOf(id).getBytes());
        return base64UrlEncode(encryptedBytes);
    }
 
    public static Long decryptLongId(String encryptedId, String key) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedBytes = cipher.doFinal(base64UrlDecode(encryptedId));
        return Long.parseLong(new String(decryptedBytes));
    }
 
        public static void main(String[] args) throws Exception {
            for (Long i = 116L; i < 500L; i++) {
                String secretKey = "7987489ABCDEFG";
 
                String encryptedId = encryptLongId(i, secretKey);
                System.out.println("Encrypted ID: " + encryptedId);
 
                Long decryptedId = decryptLongId(encryptedId, secretKey);
                System.out.println("Decrypted ID: " + decryptedId);
            }
    }
    // Base64URL编码
    private static String base64UrlEncode(byte[] bytes) {
        return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
    }
 
    // Base64URL解码
    private static byte[] base64UrlDecode(String str) {
        return Base64.getUrlDecoder().decode(str);
    }
}

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

加瓦程序设计师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值