java中Token加解密的3种方法

1.三种加解密方法

对称加密算法(例如 AES、DES 等):使用同一个密钥来加密和解密数据。

非对称加密算法(例如 RSA、ECC 等):使用公钥和私钥对数据进行加密和解密。

HMAC(Hash-based Message Authentication Code):使用哈希函数和密钥来生成消息验证码。

2.对称加密算法

import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;

public class AES {
    // 生成 AES 密钥
    public static SecretKey generateKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128);
        SecretKey secretKey = keyGenerator.generateKey();
        return secretKey;
    }

    // 加密
    public static String encrypt(String message, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(new byte[16]));

        byte[] encryptedBytes = cipher.doFinal(message.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    // 解密
    public static String decrypt(String encryptedMessage, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(new byte[16]));

        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedMessage));
        return new String(decryptedBytes);
    }


    public static void main(String[] args) throws Exception {
        // 生成 AES 密钥
        SecretKey key = generateKey();
        // 待加密消息
        String message = "eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxMjcsInVzZXJfa2V5IjoiOGVmM2ZiMGEtNDcxMS00ZmY4LThmYTMtMTRmODQ1ODUzNGY3IiwidXNlcm5hbWUiOiIxOTgyOTIxOTUxMCJ9.rzORCmw_O53nQ-rWbvLNBfoqawXJ_44nSEtWAXrVRU2d_rWl-HX9xN964BgWz_-dG8QhRt5vEuAEZZ3aHgIfKQ";
        // 加密消息
        String encryptedMessage = encrypt(message, key);

        // 解密消息
        String decryptedMessage = decrypt(encryptedMessage, key);

        System.out.println("原始消息:" + message);
        System.out.println("加密消息:" + encryptedMessage);
        System.out.println("解密消息:" + decryptedMessage);
    }
}

3.非对称加密算法

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;

import javax.crypto.Cipher;

public class RSA {
    // 生成 RSA 密钥对
    public static KeyPair generateKeyPair() throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        return keyPair;
    }

    // 加密
    public static String encrypt(String message, RSAPublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        byte[] encryptedBytes = cipher.doFinal(message.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    // 解密
    public static String decrypt(String encryptedMessage, RSAPrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedMessage));
        return new String(decryptedBytes);
    }

    public static void main(String[] args) throws Exception {
        // 生成 RSA 密钥对
        KeyPair keyPair = generateKeyPair();

        // 获取公钥和私钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

        // 待加密消息
        String message = "eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxMjcsInVzZXJfa2V5IjoiOGVmM2ZiMGEtNDcxMS00ZmY4LThmYTMtMTRmODQ1ODUzNGY3IiwidXNlcm5hbWUiOiIxOTgyOTIxOTUxMCJ9.rzORCmw_O53nQ-rWbvLNBfoqawXJ_44nSEtWAXrVRU2d_rWl-HX9xN964BgWz_-dG8QhRt5vEuAEZZ3aHgIfKQ";

        // 加密消息
        String encryptedMessage = encrypt(message, publicKey);

        // 解密消息
        String decryptedMessage = decrypt(encryptedMessage, privateKey);

        System.out.println("原始消息:" + message);
        System.out.println("加密消息:" + encryptedMessage);
        System.out.println("解密消息:" + decryptedMessage);
    }
}

4.HMAC加密方法

HMAC它不提供解密方法。HMAC 的目的是验证消息的完整性和真实性,而不是用于解密消息。

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class HMAC{
    // 生成 HMAC 密钥
    public static SecretKey generateHmacKey() throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("HMACSHA256");
        keyGenerator.init(256);
        SecretKey secretKey = keyGenerator.generateKey();
        return secretKey;
    }

    // 计算 HMAC
    public static String calculateHmac(String message, SecretKey key) throws Exception {
        Mac mac = Mac.getInstance("HMACSHA256");
        mac.init(key);

        byte[] hmacBytes = mac.doFinal(message.getBytes());
        return Base64.getEncoder().encodeToString(hmacBytes);
    }

    public static void main(String[] args) throws Exception {
        // 生成 HMAC 密钥
        SecretKey key = generateHmacKey();

        // 待计算 HMAC 的消息
        String message = "11231312";
        System.out.println("原始:" + message);
        // 计算 HMAC
        String hmac = calculateHmac(message, key);

        System.out.println("HMAC:" + hmac);
    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小舒卿雨

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

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

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

打赏作者

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

抵扣说明:

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

余额充值