簡體   English   中英

使用BouncyCastle API進行RSA加密

[英]RSA encrypt with BouncyCastle API

我想在Java中使用帶有BouncyCastle API的RSA使用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();
    }
}

如果從文件中的十六進制轉換而來的字節數組按照常規方式是big-endian,要將正的big-endian字節數組轉換為BigInteger,請在Javadoc中查看BigInteger的構造函數,該構造函數的正負號必須為int -endian字節數組的大小。

RSA的“教科書”(未填充)不安全; 請參閱crypto.SX安全性。SX和Wikipedia。 將RSA用於大於您所編碼方式的一個數據塊的數據將半隨機失敗,並且如果您對此進行糾正,那么ECB模式的效率低下且不安全。 請參閱crypto.SX安全性。SX和Wikipedia。 使用未經身份驗證的公鑰通常是不安全的。

如果您這樣做很有趣,因為它使您感覺像“ l33t hack5r”或Bond超級反派,並且不關心實際的安全性,那就很好。 如果您需要或想要實際的安全性,請放棄此功能,並使用由知道自己在做什么的人編寫的程序,和/或搜索“不要使用自己的加密貨幣”。

您當前在字節數組上使用toString 這只會返回對象引用的代表,該引用與數組中的值無關。

相反,您可以使用BigInteger構造函數,構造函數接受一個字符串和radix ,並將16作為基數。 但是請確保您在十六進制表示形式中沒有任何虛假或無效的字符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM