RSA与Bouncycastle API进行加密



当我想使用java中的bouncycastle api加密文件时,我有问题。问题在于:在下面的代码中,我创建rsakeyparameter的对象的行,其构造函数问我三个参数:
1.如果我们想与公共或私钥密封。
2.一个带有钥匙模量的biginteger。
3.与密钥指数指数的BigInteger。

我的方法收到的第一个参数是键包含的文件。因此,在rsakeyparameter的构造函数中,如何将其传递给Modulus和enpents的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();
    }
}

如果您的字节数组从文件中的十六进制转换为传统,则是Big-Endian,以将一个正面的Big-Endian字节阵列转换为Biginteger,以查看Biginteger的Javadoc构造函数,该构造器具有阳性和大型字节阵列的int符号。

'教科书'(未加密(RSA不安全;请参阅Crypto.sx Security.sx和Wikipedia。将RSA用于大于一个块的数据,其编码方式将半随机失败,如果您纠正了这一点,那么欧洲央行模式的效率且不安全;请参阅Crypto.sx Security.sx和Wikipedia。使用未经身心的公钥通常是不安全的。

如果您是为了娱乐而这样做,因为它会让您感觉像" L33T Hack5r"或Bond Supperillain,并且不在乎实际的证券,这很好。如果您需要或想要实际的安全性,请删除此问题,并使用知道自己在做什么的人编写的程序,和/或搜索"不要滚动您自己的加密"。

您当前在字节数组上使用toString。这只会返回对象引用的代表,该代表与数组中的值无关。

相反,您可以使用使用16作为radix的BigInteger构造函数。确保您在十六进制表示中没有任何虚假或无效的字符。

最新更新