RSA加密算法心得

RSA加密算法心得RSA加密密钥是非对称的,一般是成对出现分为公钥和私钥,所以也叫非对称加密,可以公钥加密,私钥解密,也可以私钥加密,公钥解密。一般用于数据加密。

大家好,又见面了,我是你们的朋友全栈君。

RSA加密密钥是非对称的,一般是成对出现分为公钥和私钥,所以也叫非对称加密,可以公钥加密,私钥解密,也可以私钥加密,公钥解密。

一般用于数据加密。

初始化密钥,可生成一对RSA密钥:

KeyPairGenerator keyPairGenerator= KeyPairGenerator.getInstance("RSA"); ---设置加密算法
keyPairGenerator.initialize(2048); ---设置密钥的位数
KeyPair keyPair=keyPairGenerator.generateKeyPair();
RSAPublicKey rsaPublicKey=(RSAPublicKey)keyPair.getPublic(); ----公钥
RSAPrivateKey rsaPrivateKey=(RSAPrivateKey)keyPair.getPrivate(); ----私钥
            System.out.println("publickey:"+Base64.encodeBase64String(rsaPublicKey.getEncoded())); ---输出的是字符串型公钥
            System.out.println("privatekey:"+Base64.encodeBase64String(rsaPrivateKey.getEncoded())); ---输出的是字符串型私钥

需要注意的是,需要使用Base64 类来对密钥进行相应的转换,需要导入jar包 commons-codec-1.8.jar

有两个常用的方法:
encodeBase64String(byte数组);用于将byte数组类型的密钥转换成字符串型密钥
decodeBase64(字符串); 用于将字符串型密钥转换成byte数组型密钥

使用公钥加密:

//获取公钥
X509EncodedKeySpec x509EncodedKeySpec=new X509EncodedKeySpec(pubKey);  ---使用公钥时用的一个关键类,
//密钥工厂初始化
 KeyFactory keyFactory=KeyFactory.getInstance("RSA"); //生成公钥
PublicKey publicKey=keyFactory
.generatePublic(x509EncodedKeySpec); //数据加密
 Cipher cipher=Cipher.getInstance("RSA");
 cipher.init(Cipher.ENCRYPT_MODE, publicKey);  ----设置是模式,即加密还是解密,此处是加密 ENCRYPT_MODE
 byte[] result=cipher.doFinal(data);
return result;

返回的result就是加密后的byte型密文,注意转成字符串是需要用Base64的方法

使用私钥解密:

//获取私钥
PKCS8EncodedKeySpec pkcs8EncodedKeySpec=new PKCS8EncodedKeySpec(privKey);  --使用私钥时用的一个关键类
//密钥工厂初始化
KeyFactory keyFactory=KeyFactory.getInstance("RSA"); //生成私钥
PrivateKey privateKey=keyFactory
.generatePrivate(pkcs8EncodedKeySpec); //数据解密
Cipher cipher=Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);   -------设置是模式,即加密还是解密,此处是解密DECRYPT_MODE
byte[] clearText=cipher.doFinal(cipherText);
return clearText; 

返回的就是byte类型的解密后的明文,注意转成字符串是不需要用Base64的方法,直接new 一个String对象就行newString(clearText)

源码:

package org.me.demo1;

import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import org.apache.commons.codec.binary.Base64;

/** * * @author zhouluping * RSA公钥加密和私钥解密 * 需要导一个jar包 commons-codec-1.8.jar, Base64类 用于将密文转换成byte数组 */
public class RsaDemo2 { 
   

    //公钥加密
    public static byte[] rsaEncrypt(byte[] data,byte[] pubKey){

        try {
            //获取公钥
            X509EncodedKeySpec x509EncodedKeySpec=new X509EncodedKeySpec(pubKey);
            //密钥工厂初始化
            KeyFactory keyFactory=KeyFactory.getInstance("RSA");
            //生成公钥
            PublicKey publicKey=keyFactory.generatePublic(x509EncodedKeySpec);
            //数据加密
            Cipher cipher=Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] result=cipher.doFinal(data);

            return result;

        } catch (NoSuchAlgorithmException e) {
            System.out.println("NoSuchAlgorithmException!");
        } catch (InvalidKeySpecException e) {
            System.out.println("InvalidKeySpecException!");
        } catch (NoSuchPaddingException e) {
            System.out.println("NoSuchPaddingException!");
        } catch (InvalidKeyException e) {
            System.out.println("InvalidKeyException!");
        } catch (IllegalBlockSizeException e) {
            System.out.println("IllegalBlockSizeException!");
        } catch (BadPaddingException e) {
            System.out.println("IllegalBlockSizeException!");
        }

        return null;
    }

    //私钥解密
    public static byte[] rsaDecrypt(byte[] cipherText,byte[] privKey){

        try {
            //获取私钥
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec=new PKCS8EncodedKeySpec(privKey);
            //密钥工厂初始化
            KeyFactory keyFactory=KeyFactory.getInstance("RSA");
            //生成私钥
            PrivateKey privateKey=keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            //数据解密
            Cipher cipher=Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] clearText=cipher.doFinal(cipherText);
            return clearText;

        } catch (NoSuchAlgorithmException e) {
            System.out.println("NoSuchAlgorithmException!");
        } catch (InvalidKeySpecException e) {
            System.out.println("InvalidKeySpecException!");
        } catch (NoSuchPaddingException e) {
            System.out.println("NoSuchPaddingException!");
        } catch (InvalidKeyException e) {
            System.out.println("InvalidKeyException!");
        } catch (IllegalBlockSizeException e) {
            System.out.println("IllegalBlockSizeException!");
        } catch (BadPaddingException e) {
            System.out.println("IllegalBlockSizeException!");
        }

        return null;
    }

    public static void main(String[] args) {
// String pubKey="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqUWHDpQcks/TcWTR5kFM2TXBUS9Gsm/qJ6ZTN9lGQlXIEQEaVwze8YpcgcVnQjbd5V+ogejZlO2EbYygwdzHDYDK5foNy9xk3Tpf9RF1h6X0ilsGSmbt7IIJoTK76C35ep/r7EiVR+LVNxF47OKVevIk6bvFca2Tg2Qfcc1wTZTHF2BD9EcnCt7a4pDYK1q0S+1pnald6yrCZIHtBuxZ5B5x099ArRHackQzf6FrxVuVud3Du98NlbJIVtm7L0l9sVmx4ItdGUA3YTSAzwd67l52ka5gVkLeGdpWTEiLLNJbBVXesqdLEdVub/q9Di23v3ftZC9vXWU/VOmLc5mDnwIDAQAB";
        String pubKey="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAp8CEgkk2+5fgSncArbujdZyBCrN8D5cpSHHAm/ItkA3DuGV3cYqDV83Xx5m173UETOkJvhhSi/uT4d+lxqk4NBh0CYHfP6gElDHp+syQ5dvrm6jxiwnc/3RBOfyusa4kDrknGncn+w9iwruB7Wsng/YnA4G99BjXfI+QCYzgUSJYQxetZg79805kIxu0/hfMqkQWCdwUV6B0bk2Cn5CLWhRk/MT1gTgVclVJHw1Bb83wWmYtHu0PWfUyUi+nM3o8jzXKuwBK8aDqNZ2EXMZ5GTU1TXBYbdyZ17YhOU3kD/hdTYwzXdzr7wSv/f+RZWaOPF5doqfOLP3VKRRH/IPy3wIDAQAB";
        String clearText="today is third day!";
        System.out.println("未加密明文:"+clearText);
        byte[] cipherText=rsaEncrypt(clearText.getBytes(),Base64.decodeBase64(pubKey));
        System.out.println("密文:"+Base64.encodeBase64String(cipherText));

        String priKey="MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCnwISCSTb7l+BKdwCtu6N1nIEKs3wPlylIccCb8i2QDcO4ZXdxioNXzdfHmbXvdQRM6Qm+GFKL+5Ph36XGqTg0GHQJgd8/qASUMen6zJDl2+ubqPGLCdz/dEE5/K6xriQOuScadyf7D2LCu4HtayeD9icDgb30GNd8j5AJjOBRIlhDF61mDv3zTmQjG7T+F8yqRBYJ3BRXoHRuTYKfkItaFGT8xPWBOBVyVUkfDUFvzfBaZi0e7Q9Z9TJSL6czejyPNcq7AErxoOo1nYRcxnkZNTVNcFht3JnXtiE5TeQP+F1NjDNd3OvvBK/9/5FlZo48Xl2ip84s/dUpFEf8g/LfAgMBAAECggEBAKd7ttC9eH/JKs4t8ieC57hNASlF+d829Ki3qa4JJSRmGbrI03Aw8uF/Sqil9teU5S5EnM2GSyQnkYY6XLDz0oFwyKmVWOedQLUVAJ6+DwzvfVR0YHSI7HTABT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N8YnJDkWa/w==";
        byte[] dectyptText=rsaDecrypt(cipherText, Base64.decodeBase64(priKey));
        System.out.println("解密后的明文:"+new String(dectyptText));
    }
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/138507.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号