0

RSA를 사용하여 파일을 암호화/해독하려고합니다. 그러나 파일 안의 데이터는 볼 수 없습니다.파일을 암호화 된 파일로 변환하고 서버에서 해독합니다 (공개 키 암호화 사용).

 // To encrypt a file 

    private static void encrypt(InputStream input, OutputStream output, PublicKey key) 
     throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException  { 
    final Cipher encrypt = Cipher.getInstance(ALGORITHM); 
    // encrypt the plain text using the public key 
     encrypt.init(Cipher.ENCRYPT_MODE, key); 
     // encrypt.doFinal(); 
    output = new CipherOutputStream(output,encrypt); 
    writeBytes(input, output, encrypt); 
      output.close(); 
} 


    // To decrypt the file 

private static void decrypt(InputStream input, OutputStream output, PrivateKey key) 
     throws IOException,NoSuchAlgorithmException,InvalidKeyException,NoSuchPaddingException,BadPaddingException,IllegalBlockSizeException { 
     final Cipher decrypt = Cipher.getInstance(ALGORITHM); 

    // decrypt the text using the private key 
    decrypt.init(Cipher.DECRYPT_MODE, key); 
    input = new CipherInputStream(input, decrypt); 
    writeBytes(input, output, decrypt); 
      input.close(); 
} 

// To write on the file from the inputstream 

private static void writeBytes(InputStream input, OutputStream output, Cipher cipher) 
     throws IOException, IllegalBlockSizeException,BadPaddingException { 
    byte[] writeBuffer = new byte[512]; 
    int readBytes = 0; 

    while ((readBytes = input.read(writeBuffer)) >= 0) { 
       System.out.println(readBytes); 




       // String text = input.read(writeBuffer); 
       // cipher.doFinal(); 
       try{ 
        System.out.println("Here"); 
     output.write(writeBuffer, 0, readBytes); 
       } 
       catch(Exception e){ 
       e.printStackTrace(); 
       } 
    } 

    output.close(); 
    input.close(); 
} 

주요 기능 : 나는 암호화뿐만 아니라 해독 파일에서 데이터를 가져 오는하고 있지 않다

// Check if the pair of keys are present else generate those. 
    if (!areKeysPresent()) { 
    // Method generates a pair of keys using the RSA algorithm and stores it 
    // in their respective files 
    generateKey(); 
    } 

    final String originalText = "Text to be encrypted "; 
    ObjectInputStream inputStream = null; 

    String clearFile = "/UploadFile/Log.txt";  
    String encryptedFile = "/UploadFile/LogE.txt";  
    String decryptedFile = "/UploadFile/LogD.txt"; 

    // Encrypt the string using the public key 
    inputStream = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE)); 
    final PublicKey publicKey = (PublicKey) inputStream.readObject(); 
// final byte[] cipherText = encrypt(originalText, publicKey); 

    encrypt(new FileInputStream(clearFile), new FileOutputStream(encryptedFile), publicKey); 
    System.out.println("Successfully Encrypted"); 

    } 
    // Decrypt the cipher text using the private key. 
    inputStream = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE)); 
    final PrivateKey privateKey = (PrivateKey) inputStream.readObject(); 
// final String plainText = decrypt(cipherText, privateKey); 

    decrypt(new FileInputStream(encryptedFile), new FileOutputStream(decryptedFile), privateKey); 
    System.out.println("Successfully Decrypted"); 


GenerateKey Function : 

public static void generateKey() { 
try { 
    final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM); 
    keyGen.initialize(1024); 
    final KeyPair key = keyGen.generateKeyPair(); 

    File privateKeyFile = new File(PRIVATE_KEY_FILE); 
    File publicKeyFile = new File(PUBLIC_KEY_FILE); 

    // Create files to store public and private key 
    if (privateKeyFile.getParentFile() != null) { 
    privateKeyFile.getParentFile().mkdirs(); 
    } 
    privateKeyFile.createNewFile(); 

    if (publicKeyFile.getParentFile() != null) { 
    publicKeyFile.getParentFile().mkdirs(); 
    } 
    publicKeyFile.createNewFile(); 

    // Saving the Public key in a file 
    ObjectOutputStream publicKeyOS = new ObjectOutputStream(
     new FileOutputStream(publicKeyFile)); 
    publicKeyOS.writeObject(key.getPublic()); 
    publicKeyOS.close(); 

    // Saving the Private key in a file 
    ObjectOutputStream privateKeyOS = new ObjectOutputStream(
     new FileOutputStream(privateKeyFile)); 
    privateKeyOS.writeObject(key.getPrivate()); 
    privateKeyOS.close(); 
} catch (Exception e) { 
    e.printStackTrace(); 
} 

    } 

여기

는 코드입니다.

clearFile은 원래 데이터 파일이며 encryptedFile은 암호화 된 데이터이고, decryptedFile은 해독 된 데이터입니다.

제발 도와주세요, 내가 여기에서 누락되었습니다.

+0

실행 후,'encryptedFile'의 크기는 0입니까? – erickson

답변

0

데이터 암호화에는 RSA를 사용하지 않습니다. 이를 사용하여 대칭 키를 암호화하고 대칭 키를 사용하여 데이터를 암호화합니다. 공개 키 알고리즘은 데이터가 아닌 주요 전송 또는 키 협약을위한 알고리즘입니다.

응용 프로그램에 CMS (S/MIME) 또는 PGP 라이브러리를 사용해야합니다.

0

암호화하려는 파일의 크기를 알 수는 없지만 RSA에서는 너무 많은 데이터를 암호화 할 수 없습니다. 그것은 키의 일부인 N 매개 변수에 한정되어 있으므로 데이터가 키보다 짧아야합니다. 어쩌면 이것이 문제 일 수 있습니다.

일반적으로 공개 키 암호화를 사용하여 대칭 키 (예 : AES)를 암호화 한 다음 암호화 된 대칭 키를 사용하여 데이터를 효율적으로 암호화합니다. 이를 하이브리드 암호화라고합니다.

먼저 AES를 사용하여 암호화 한 다음 AES 키만 시도하고 암호화하는 것이 좋습니다.

+0

그 1.3kb의 단순한 텍스트 파일 – Jeet

+0

나는 당신이 KB를 의미한다고 생각한다. 이것은 RSA의 열쇠 (2048 비트 = 256 바이트의 경우 라 할지라도)보다 중요하다. 내 대답에 설명 된 것처럼 하이브리드 암호화를 수행하십시오. –