java中使用JWK格式传输密钥(密钥对象和jwk对象相互转换)

时间:2025-02-13 08:19:29

最近项目需要用到数据加密,要把密钥传输出去,但是需要使用jwk格式;

网上资料很少. 并且都是解释jwk概念的. 没有教你操作. 自己找了好久终于找到了.特地记录一下. 供后来者使用;

本文主要涉及到:
1.生成的rsa密钥转换成jwk格式的json.
2. jwk格式 json 转为rsa密钥;

依赖

主要用到了两个,jose4j 和 hutool

        <!--        jwk转换 -->
        <dependency>
            <groupId>org.bitbucket.b_c</groupId>
            <artifactId>jose4j</artifactId>
            <version>0.6.4</version>
        </dependency>


            <dependency>
                <groupId>cn.hutool</groupId>
                <artifactId>hutool-all</artifactId>
                <version>5.8.1</version>
            </dependency>

生成rsa密钥并且转换成JWK格式的json

不废话,直接上代码

   		//生成rsa密钥
        KeyPair rsa1 = KeyUtil.generateKeyPair("RSA", 1024);

        RSAPrivateKey aPrivate = (RSAPrivateKey) rsa1.getPrivate();
        RSAPublicKey aPublic = (RSAPublicKey) rsa1.getPublic();
       //重点. 生成jwk对象, 通过公钥
        RsaJsonWebKey rsaJsonWebKey1 = new RsaJsonWebKey(aPublic);
		//设置进去私钥
        rsaJsonWebKey1.setPrivateKey(aPrivate);

		//打印公钥的jwkStr
        String pubJson = rsaJsonWebKey1.toJson();
        //传递private参数, 打印私钥的 jwkStr
        String priJson = rsaJsonWebKey1.toJson(INCLUDE_PRIVATE);



通过jwk的json文件获取rsa公私钥

一般jwk文件 私钥是包含公钥的 . 所以可以通过私钥的jwk获取公私钥.

    public String getRsaPrivateHex(String priKeyJson) throws JoseException {
        //生成密钥
        JSONObject readJSONObject = JSONUtil.parseObj(priKeyJson);
        //通过jwk的私钥json 获取jwk对象
        RsaJsonWebKey pri = new RsaJsonWebKey(readJSONObject);
        //获取私钥
        RSAPrivateKey rsaPrivateKey = pri.getRsaPrivateKey();
        //当然也能获取公钥, 毕竟是包含关系嘛
        RSAPublicKey rsaPublicKey = pri.getRsaPublicKey();
        
        byte[] encoded = rsaPrivateKey.getEncoded();
        //java中自己常用的私钥形式. 要么就base64,要么就16进制, 这里是16进制
        String hexStrPri = HexUtil.encodeHexStr(encoded);
        return hexStrPri;
    }


还有一种是通过公钥的jwk.获取公钥; 其实跟上述是一样的

        //生成密钥
        JSONObject readJSONObject = JSONUtil.parseObj(pubKeyJson);
        RsaJsonWebKey pub = new RsaJsonWebKey(readJSONObject);
        //获取公钥
        RSAPublicKey rsaPublicKey = pub .getRsaPublicKey();

结尾

对你有帮助就点点赞,谢谢