RSA 算法的使用

1 . 生成密钥

public static Map<String, Object> initKey() throws Exception{
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);

        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();

        Map<String, Object> map = new HashMap<>();
        map.put(PUBLIC_KEY, rsaPublicKey);
        map.put(PRIVATE_KEY, rsaPrivateKey);

        return map;

    }

2 . 利用公钥进行加密

public static byte[] encryptRSA(byte[] data, RSAPublicKey key) throws Exception{
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] resultBytes = cipher.doFinal(data);
        return resultBytes;
    }

3 . 利用私钥解密

public static byte[] decryptRSA(byte[] src, RSAPrivateKey key) throws Exception{
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] plainBytes = cipher.doFinal(src);
        return plainBytes;
    }

4 . 测试

public class Client {

    public static final String DATA = "helloworld"; 

    public static void main(String[] args) throws Exception {

        Map<String, Object> map = RSAUtil.initKey();
        RSAPrivateKey rsaPrivateKey = RSAUtil.getPrivateKey(map);
        RSAPublicKey rsaPublicKey = RSAUtil.getPublicKey(map);

        byte[] resultBytes = RSAUtil.encryptRSA(DATA.getBytes(), rsaPublicKey);
        System.out.println("RSA Encrypt : " + Helper.fromByteToHex(resultBytes));
        byte[] plainBytes = RSAUtil.decryptRSA(resultBytes, rsaPrivateKey);
        System.out.println("RES Plain : " + new String(plainBytes));

    }

}

5 . 结果

RSA Encrypt : 50005af95cc6d79f22c4baf9c289926ef2afb48c0c1760eecbe2bacc22e989349af66cea1f12be343629f8889a6d06679924df445e4c59012753529c7dffb563c783a2e45a20a8ca8ec0ee0fa74625cfce0a4f77cf4fea96c0d1c944ce2f4433aecc941fdd213f1186e8e71668e842acbc4c630a7befdbf20a901af2da1718e4
RSA Plain : helloworld
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值