【发布时间】:2018-02-26 17:05:32
【问题描述】:
我想在 Java 中使用带有 BouncyCastle API 的 RSA 加密文件时遇到问题。问题如下:在下面的代码中,我创建 RSAKeyParameters 对象的行,它的构造函数询问我三个参数:
1.如果我们想用公钥或私钥加密。
2. 具有键模数的 BigInteger。
3. 具有键指数的 BigInteger。
我的方法接收的第一个参数是包含密钥的文件。那么在 RSAKeyParameter 的构造函数中,如何传递一个 BigInteger 即模数和指数?如何从文件中获取模数和指数?
PD:包含密钥的文件有一个CR和LF,这就是为什么有两个readLine()。
void cifrar_asimetrica(String fichClave, String archivoClaro, String result, boolean conPrivada){
byte[] modulo;
byte[] exponente;
try(
BufferedReader lectorClave = new BufferedReader (new FileReader(fichClave));
BufferedInputStream lectorFichero = new BufferedInputStream(new FileInputStream(archivoClaro));
BufferedOutputStream fsalida = new BufferedOutputStream(new FileOutputStream(result))){
modulo = Hex.decode(lectorClave.readLine());
exponente = Hex.decode(lectorClave.readLine());
RSAEngine cifrador = new RSAEngine();
CipherParameters parametro = new RSAKeyParameters(conPrivada, new BigInteger(modulo.toString()), new BigInteger(exponente.toString()));
cifrador.init(true,parametro); // vamos a cifrar
byte[] datosLeidos = new byte[cifrador.getOutputBlockSize()];
byte[] datosCifrados = new byte[cifrador.getOutputBlockSize()];
int leidos = 0;
//NO SE SI ES GETINPUTBLOCKSIZE O OUTPUT
leidos = lectorFichero.read(datosLeidos, 0, cifrador.getOutputBlockSize());
while(leidos > 0){
datosCifrados = cifrador.processBlock(datosLeidos, 0, cifrador.getOutputBlockSize());
fsalida.write(datosCifrados, 0, datosCifrados.length);
leidos = lectorFichero.read(datosLeidos, 0, cifrador.getOutputBlockSize());
}
}catch(Exception e){
e.printStackTrace();
}
}
【问题讨论】:
-
请注意,要加密的数据大小限制为小于 RSA 的密钥大小。如果您确实需要 RSA(非对称加密)和大于密钥大小的数据,则可能需要混合加密。
标签: java encryption rsa bouncycastle public-key-encryption