首頁 > 軟體

Springboot整合JwtHelper實現非對稱加密

2022-03-31 16:00:51

一、生成公私鑰對

提供兩種方法,一種基於命令列中的Keytool工具生成,一種是基於SpringSecurity中的KeyPairGenerator類生成,現實現第二種方式:

//    加密演演算法
    private static final String KEY_ALGORITHM = "RSA";
//    公鑰key
    private static final String PUB_KEY="publicKey";
//    私鑰key
    private static final String PRI_KEY="privateKey";
 
    public static Map<String,String> generateKey() throws NoSuchAlgorithmException {
        Map<String,String> keyMap=new HashMap<>();
        KeyPairGenerator instance = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        KeyPair keyPair = instance.generateKeyPair();
        PrivateKey privateKey = keyPair.getPrivate();
        PublicKey publicKey = keyPair.getPublic();
        //Base64 編碼
        byte[] privateKeyEncoded = privateKey.getEncoded();
        String privateKeyStr = Base64.encodeBase64String(privateKeyEncoded);
        byte[] publicKeyEncoded = publicKey.getEncoded();
        String publicKeyStr=Base64.encodeBase64String(publicKeyEncoded);
        keyMap.put(PUB_KEY,publicKeyStr);
        keyMap.put(PRI_KEY,privateKeyStr);
        return keyMap;
    }

二、利用私鑰生產token

 //    加密演演算法
    private static final String KEY_ALGORITHM = "RSA";
    //    公鑰key
    private static final String PUB_KEY="publicKey";
    //    私鑰key
    private static final String PRI_KEY="privateKey";
//    GenerateKey Key=new GenerateKey();
//    利用私鑰生產token
    public static Map<String,String> generateToken(UserDetails userDetails) throws NoSuchAlgorithmException, InvalidKeySpecException {
        GenerateKey Key=new GenerateKey();
        RSAPrivateKey privateKey = null;
        RSAPublicKey publicKey=null;
        String token=null;
        Map<String, String> map=new HashMap<>();
        Map<String, String> keyMap = Key.generateKey();
        privateKey=getPrivateKey(keyMap.get(PRI_KEY));
        Map<String,String> tokenMap=new HashMap<>();
        tokenMap.put("userName",userDetails.getUsername());
//        使用私鑰加密
        token = JwtHelper.encode(JSON.toJSONString(tokenMap), new RsaSigner(privateKey)).getEncoded();
 
 
        map.put("token",token);
        map.put("publicKey",keyMap.get(PUB_KEY));
        return map;
    }

三、利用公鑰解密token

public static String parseToken(String token,String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        Jwt jwt=null;
        RSAPublicKey rsaPublicKey;
        rsaPublicKey=getPublicKey(publicKey);
        jwt=JwtHelper.decodeAndVerify(token, new RsaVerifier(rsaPublicKey) );
        String claims= jwt.getClaims();
        return claims;
    }

四、將String型別的公鑰轉換成RSAPublicKey物件

    /**
     * 得到公鑰
     *
     * @param publicKey
     *            金鑰字串(經過base64編碼)
     * @throws Exception
     */
    public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        // 通過X509編碼的Key指令獲得公鑰物件
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
        RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
        return key;
    }

五、將String型別的私鑰轉換成RSAPrivateKey物件

    /**
     * 得到私鑰pkcs8
     *
     * @param privateKey
     *            金鑰字串(經過base64編碼)
     * @throws Exception
     */
    public static RSAPrivateKey getPrivateKey(String privateKey)
            throws NoSuchAlgorithmException, InvalidKeySpecException {
        // 通過PKCS#8編碼的Key指令獲得私鑰物件
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
        RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
        return key;
    }

到此這篇關於Springboot整合JwtHelper實現非對稱加密的文章就介紹到這了,更多相關Springboot JwtHelper非對稱加密內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com