RSA加解密学习笔记

RSA加解密简单说明:

RSA是非对称加密方式,就是说加密解密不是同一个Key。私钥加密公钥解密,待加密的明文字节长度不能大于密钥的字节长度减11(比如1024位的,那么待加密的数据长度不能大于117字节),待解密数据的字节长度不能大于密钥的字节长度(比如1024位的就不能大于128字节)

RSA公钥私钥的生成:
//获取RSA密钥生成器的实例,还可以是DES/AES等,当然这里只需要RSA
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
//初始化密钥的长度
keyPairGenerator.initialize(2048);
//生成密钥对
KeyPair keyPair = keyPairGenerator.generateKeyPair();
//获取私钥
PrivateKey privateKey = keyPair.getPrivate();
//获取公钥
PublicKey publicKey = keyPair.getPublic();
RSA公钥加密:
//从Base64编码的字符串生成公钥
String publicKeyStr = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQ"
byte[] publicKeyBytes = Base64.decodeBase64(publicKeyStr .getBytes());
//这里需要注意一下,生成公钥的spec只能是X509EncodedKeySpec或者RSAPublicKeySpec,私钥只能是PKCS8EncodedKeySpec或者RSAPrivateKeySpec
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes );
PublicKey publicKey = KeyFactory
                .getInstance("RSA")
                .generatePublic(keySpec);
//待加密数据
String content = "Hello RSA 77 Hello RSA 77Hello RSA 77Hello RSA 77Hello RSA 77Hello RSA 77Hello RSA 77Hello RSA 77Hello RSA";
byte[] data = Base64.encodeBase64(content.getBytes());
//公钥加密
Cipher rsa = Cipher.getInstance("RSA");
//初始化加密模式
rsa.init(Cipher.ENCRYPT_MODE, publicKey);
ByteArrayInputStream is = new ByteArrayInputStream(data );
ByteArrayOutputStream os = new ByteArrayOutputStream();
//这里是2048位密钥,所以加密最大长度不能超过245字节
byte[] buffer = new byte[245];
int len;
while ((len = is.read(buffer)) != -1) {
            byte[] doFinal = rsa.doFinal(buffer, 0, len);
            int length = doFinal.length;
            os.write(doFinal);
//加密后的数据,为了防止乱码,这里将加密数据采用Base64编码
String encryptedData = new String(Base64.encodeBase64(os.toByteArray()));
RSA私钥解密:
         //从Base64编码的字符串生成私钥
        String privateKeyStr = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCDKI2SovlB9CcI/EztKXeiBQ5UMoGA";
        byte[] privateKey_bytes = Base64.decodeBase64(privateKeyStr.getBytes());
        //这里需要注意一下,生成公钥的spec只能是X509EncodedKeySpec或者RSAPublicKeySpec,私钥只能是PKCS8EncodedKeySpec或者RSAPrivateKeySpec
        PKCS8EncodedKeySpec sk_keySpec = new PKCS8EncodedKeySpec(privateKey_bytes);
        PrivateKey privateKey = KeyFactory
                .getInstance("RSA")
                .generatePrivate(sk_keySpec);
        //私钥解密
        Cipher rsa2 = Cipher.getInstance("RSA");
        rsa2.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] input = Base64.decodeBase64(encryptedData.getBytes());
        ByteArrayInputStream is2 = new ByteArrayInputStream(input);
        ByteArrayOutputStream os2 = new ByteArrayOutputStream();
        byte[] buffer2 = new byte[256];
        int len2;
        while ((len2 = is2.read(buffer2)) != -1) {