RSA算法的分段加密

一.rsa算法介绍:百度百科

二.首先通过rsa算法生成一对公私钥

 private static void generateKeyPair() throws Exception{
        Security.addProvider(new com.sun.crypto.provider.SunJCE());
        /** RSA算法要求有一个可信任的随机数源 */
        SecureRandom sr = new SecureRandom();
        /** 为RSA算法创建一个KeyPairGenerator对象 */
        
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        /** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */
        kpg.initialize(4096, sr);
        /** 生成密匙对 */
        KeyPair kp = kpg.generateKeyPair();
        /** 得到公钥 */
        Key publicKey = kp.getPublic();
        /** 得到私钥 */
        Key privateKey = kp.getPrivate();
    
        /** 用对象流将生成的密钥写入文件 */
        ObjectOutputStream oos1 = new ObjectOutputStream(new FileOutputStream(ResourceBundleUtil.getSystem(WYPublicKey)/*"yxb_ok_publickey.keystore"*/));
        ObjectOutputStream oos2 = new ObjectOutputStream(new FileOutputStream(ResourceBundleUtil.getSystem(WYPrivateKey)/*"text_privatekey.keystore"*/));
        oos1.writeObject(publicKey);
        oos2.writeObject(privateKey);
        /** 清空缓存,关闭文件输出流 */
        oos1.close();
        oos2.close();
    }

三.对字符串进行分段加密操作

    1.进行加密操作

public static String encrypt(String source,String publickey) throws Exception{   //source为需要加密的对应  publickey-rsa公钥
    	  
    	  /** 将文件中的公钥对象读出 */
    	ObjectInputStream ois = new ObjectInputStream(RsaUtil.class.getResourceAsStream("/"+publickey));
    	Key key = (Key) ois.readObject();
        ois.close();
        /** 得到Cipher对象来实现对源数据的RSA加密 */
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, key);
       byte[] b = source.getBytes("utf-8");
      
        byte[] b1 = null;
        /** 执行加密操作 */
        for (int i = 0; i < b.length; i += 501) {  
       	byte[] doFinal  = cipher.doFinal(ArrayUtils.subarray(b, i,i + 501));      
        	b1 = ArrayUtils.addAll(b1, doFinal);  
        }
    	BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(b1);      
        
    }

2.对加密后参数进行对应的解密:

public static String decrypt(String cryptograph,String privatekey) throws Exception{ //cryptograph-通过rsa公钥加密得到的参数  privatekey-与公钥对应的私钥
    	 /** 将文件中的私钥对象读出 */
    	// cryptograph= new String(cryptograph.getBytes(),"gbk");
    	ObjectInputStream ois = new ObjectInputStream(RsaUtil.class.getResourceAsStream("/"+privatekey));
        Key key = (Key) ois.readObject();
        /** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, key);
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] b1 = decoder.decodeBuffer(cryptograph);
        /** 执行解密操作 */
        byte[] b = null;
        
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < b1.length; i += 512) {
       	byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(b1, i, i + 512));    
       	sb.append(new String(doFinal,"utf-8"));
       }
        return sb.toString();

    }

3.测试方法

 public static void main(String[] args) throws Exception {
    	
    	String a = "abc";
    	String b = encrypt(a,"yxb_ok_publickey.keystore");
    	String c = decrypt(b,"yxb_ok_privatekey.keystore");
    	System.out.println("加密前的参数:"+a);
    	System.out.println("加密后的参数为:"+b);
    	System.out.println("解密后的参数:"+c);

}  

4.运行结果为:


5.项目导入的包为:

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.Security;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.crypto.Cipher;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.xml.security.utils.Base64;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
总结:分段加密可以避免应为需要加密的原字符串过长而出现错误。
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
RSA算法是一种非对称加密算法,它的加密过程可以分为两个步骤:密钥生成和加密/解密。 在密钥生成过程中,需要生成一对公私钥对。公钥用于加密数据,私钥用于解密数据。RSA算法的安全性依赖于大素数的存在,因此在密钥生成过程中需要随机生成两个大素数p和q,并计算出n=p*q和φ(n)=(p-1)*(q-1)。然后选择一个整数e,使得1<e<φ(n)且e与φ(n)互质,最后计算出d,使得d*e ≡ 1 mod φ(n)。 在加密过程中,需要将明文分段加密。假设明文为m,密钥为公钥(n,e),将明文m分为若干个长度不超过n-11的块,然后对每个块进行加密。具体的加密过程为:将每个块转化为一个整数x,然后计算出密文c=x^e mod n。 在解密过程中,需要将密文分段解密。假设密文为c,密钥为私钥(n,d),将密文c分为若干个长度为n的块,然后对每个块进行解密。具体的解密过程为:将每个块转化为一个整数y,然后计算出明文m=y^d mod n。 下面是使用Qt语言实现RSA算法分段加密的示例代码: ```cpp #include <QByteArray> #include <QtMath> // 随机生成一个大素数 unsigned int generatePrime() { unsigned int prime; do { prime = qrand() % 10000 + 10000; } while (!QIntValidator(10000, 99999).isPrime(prime)); return prime; } // 计算最大公约数 unsigned int gcd(unsigned int a, unsigned int b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } // 计算模反元素 unsigned int modInverse(unsigned int a, unsigned int n) { int t = 0, newt = 1; unsigned int r = n, newr = a; while (newr != 0) { int quotient = r / newr; int tmp = t; t = newt; newt = tmp - quotient * newt; tmp = r; r = newr; newr = tmp - quotient * newr; } if (r > 1) { return 0; } if (t < 0) { t += n; } return t; } // 生成公私钥对 void generateKeys(unsigned int& n, unsigned int& e, unsigned int& d) { unsigned int p = generatePrime(); unsigned int q = generatePrime(); n = p * q; unsigned int phi = (p - 1) * (q - 1); do { e = qrand() % phi + 1; } while (gcd(e, phi) != 1); d = modInverse(e, phi); } // 分段加密 QByteArray encrypt(const QByteArray& data, unsigned int n, unsigned int e) { QByteArray encryptedData; int blockSize = qFloor(qLn(n) / qLn(256)) - 1; int pos = 0; while (pos < data.size()) { QByteArray block = data.mid(pos, blockSize); unsigned int x = block.toUInt(); unsigned int c = qPow(x, e) % n; QByteArray encryptedBlock = QByteArray::number(c); encryptedData.append(encryptedBlock); pos += blockSize; } return encryptedData; } // 分段解密 QByteArray decrypt(const QByteArray& encryptedData, unsigned int n, unsigned int d) { QByteArray decryptedData; int blockSize = qFloor(qLn(n) / qLn(256)); int pos = 0; while (pos < encryptedData.size()) { QByteArray encryptedBlock = encryptedData.mid(pos, blockSize); unsigned int c = encryptedBlock.toUInt(); unsigned int y = qPow(c, d) % n; QByteArray block = QByteArray::number(y); while (block.size() < blockSize) { block.prepend('\0'); } decryptedData.append(block); pos += blockSize; } return decryptedData; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值