一、概述
1、RSA是基于大数因子分解难题。目前各种主流计算机语言都支持RSA算法的实现
2、java6支持RSA算法
3、RSA算法可以用于数据加密和数字签名
4、RSA算法相对于DES/AES等对称加密算法,他的速度要慢的多
5、总原则:公钥加密,私钥解密 / 私钥加密,公钥解密
二、模型分析
RSA算法构建密钥对简单的很,这里我们还是以甲乙双方发送数据为模型
1、甲方在本地构建密钥对(公钥+私钥),并将公钥公布给乙方
2、甲方将数据用私钥进行加密,发送给乙方
3、乙方用甲方提供的公钥对数据进行解密
如果乙方向传送数据给甲方:
4、乙方用公钥对数据进行加密,然后传送给甲方
5、甲方用私钥对数据进行解密
/**非对称加密 * @param content * @return */ public static String rsaEncode(String content){ try { //获取加密格式 KeyFactory keyFactory = KeyFactory.getInstance("rsa"); //根据公钥和大质数乘机进行加密 RSAPublicKeySpec rsaPublicKey = new RSAPublicKeySpec(new BigInteger(MODULUS),new BigInteger(PUB_KEY)); PublicKey publicKey = keyFactory.generatePublic(rsaPublicKey); //获取密码生成器 Cipher cipher = Cipher.getInstance("rsa"); //初始化生成器 cipher.init(Cipher.ENCRYPT_MODE,publicKey); //加密 byte[] bytes = cipher.doFinal(content.getBytes("utf-8")); //返回加密字符串 return Base64.encodeToString(bytes,Base64.DEFAULT); } catch (NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException | BadPaddingException | UnsupportedEncodingException | IllegalBlockSizeException | InvalidKeyException e) { e.printStackTrace(); } return null; } /** 非对称解密 * @param content 传入字符串 * @return 返回结果 */ public static String rsaDecode(String content) throws UnsupportedEncodingException, IllegalBlockSizeException { try { //key工厂 获取加密方式 KeyFactory factory = KeyFactory.getInstance("rsa"); //通过私钥 和 大质数乘机 得到私钥解密 RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(new BigInteger(MODULUS),new BigInteger(PRI_KEY)); PrivateKey privateKey = factory.generatePrivate(rsaPrivateKeySpec); //获取密钥解密生成器 Cipher cipher = Cipher.getInstance("rsa"); //初始化 cipher.init(Cipher.DECRYPT_MODE,privateKey); //解密 1.讲原来base64格式编码的字符串 转换成正常的字符串 2。解码 byte[] bytes = cipher.doFinal(Base64.decode(content.getBytes("utf-8"),Base64.DEFAULT)); return new String(bytes,0,bytes.length); } catch (NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException | BadPaddingException | InvalidKeyException e) { e.printStackTrace(); } return null; }