Java RSA加密算法 + Jwt创建token

RSA非对称加密:

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RsaUtil {
    // RSA算法常量,用于生成RSA密钥对和进行加解密操作。
    private static final String RSA_ALGORITHM = "RSA";

    // 生成RSA密钥对。
    // secret             生成私钥的密文
    private static void generateKey(String secret) throws NoSuchAlgorithmException {
        // 实例化一个密钥对生成器,指定算法为RSA
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA_ALGORITHM);
        SecureRandom secureRandom = new SecureRandom(secret.getBytes());
        // 初始化密钥对生成器,指定密钥长度为2048位
        keyPairGenerator.initialize(2048, secureRandom); // 密钥大小为2048位

        KeyPair keyPair = keyPairGenerator.genKeyPair();

        String publicKey = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());
        String privateKey = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());

        System.out.println("公钥:" + publicKey);
        System.out.println("私钥:" + privateKey);
    }

    // 使用公钥加密数据
    public static String encrypt(String data, String publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(publicKey.getBytes()));
        byte[] encryptedData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedData);
    }

    // 使用私钥解密数据
    public static String decrypt(String data, String privateKey) throws Exception {
        byte[] decodedData = Base64.getDecoder().decode(data);
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(privateKey.getBytes()));
        byte[] decryptedData = cipher.doFinal(decodedData);
        return new String(decryptedData, StandardCharsets.UTF_8);
    }

    // 获取公钥
    private static PublicKey getPublicKey(byte[] bytes) throws Exception {
        bytes = Base64.getDecoder().decode(bytes);
        X509EncodedKeySpec spec = new X509EncodedKeySpec(bytes);
        KeyFactory factory = KeyFactory.getInstance("RSA");
        return factory.generatePublic(spec);
    }

    // 获取私钥
    private static PrivateKey getPrivateKey(byte[] bytes) throws NoSuchAlgorithmException, InvalidKeySpecException {
        bytes = Base64.getDecoder().decode(bytes);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes);
        KeyFactory factory = KeyFactory.getInstance("RSA");
        return factory.generatePrivate(spec);
    }

    public static void main(String[] args) throws Exception {
        String publicKey = "";
        String privateKey = "";
        // 生成RSA密钥对
        // generateKey("innoshine");

        String data = "学习RSA加密";
        String encrypt = encrypt(data, publicKey);
        System.out.println("加密后:" + encrypt);
        String decrypt = decrypt(encrypt, privateKey);
        System.out.println("解密后:" + decrypt);
    }
}

 (JWT) 使用auth0 + rsa 生成token:

依赖:

 <dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>3.11.0</version>
</dependency>


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.inno.framework.util.jwt.RsaUtil;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Date;

public class JwtUtil {
    // token有效期(毫秒)
    private static final long EXPIRE_TIME = 30 * 60 * 1000;

    private static final String JWT_PAYLOAD_USER_KEY = "user";

    // 使用私钥加密token
    public static String sign(String obj, PrivateKey privateKey) {
        // 使用私钥和RSA签名算法创建一个Algorithm对象
        Algorithm algorithm = Algorithm.RSA256(null, (RSAPrivateKey) privateKey);
        // 创建一个JWT,附带user信息并设置过期时间
        String token = JWT.create()
                .withClaim(JWT_PAYLOAD_USER_KEY, obj)
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRE_TIME))
                .sign(algorithm);
        return token;
    }

    // 使用 公钥 校验token是否正确
    private static boolean verify(String token, PublicKey publicKey) {
        try {
            // 根据密码生成JWT效验器
            Algorithm algorithm = Algorithm.RSA256((RSAPublicKey) publicKey, null);
            JWTVerifier verifier = JWT.require(algorithm).build();
            // 效验TOKEN
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (Exception e) {
            System.out.println("token校验失败:" + e.getMessage());
            return false;
        }
    }

    // 公钥 获取token的信息
    public static String getPayload(String token, PublicKey publicKey) {
        if (!verify(token, publicKey)) {
            return null;// token校验失败
        }
        try {
            DecodedJWT jwt = JWT.decode(token);
            // Date expiresAt = jwt.getExpiresAt();// 获取过期时间
            return jwt.getClaim(JWT_PAYLOAD_USER_KEY).asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
        String publicKey = "";
        String privateKey = "";

        // String token = sign("12345", getPrivateKey(privateKey.getBytes()));
        String token = "";
        System.out.println("创建的token: " + token);
        String username = getPayload(token, RsaUtil.getPublicKey(publicKey.getBytes()));
        System.out.println("获取toekn的值:" + username);
    }
}

AES加密:

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;

public class AESUtil {
    private static String SECRET_KEY = "eh49671237434878";

    private static final String CIPHER_ALGORITHM = "AES/CBC/NoPadding";

    public static void main(String[] args) {
        String encrypt = encrypt("12345");
        System.out.println("加密后:" + encrypt);
        System.out.println("解密后:" + decrypt(encrypt));
    }

    /**
     * 加密 成Base64字符串
     */
    public static String encrypt(String data) {
        try {
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(SECRET_KEY.getBytes(), "AES"), new IvParameterSpec("0000000000000000".getBytes()));
            byte[] encrypted = cipher.doFinal(Arrays.copyOf(data.getBytes(), 16 * ((data.getBytes().length / 16) + 1)));
            return Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密 将加密后的Base64字符串进行解密
     */
    public static String decrypt(String data) {
        try {
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(SECRET_KEY.getBytes(), "AES"), new IvParameterSpec("0000000000000000".getBytes()));
            return new String(cipher.doFinal(Base64.getDecoder().decode(data)), "UTF-8").trim();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值