【问题标题】:Convert a file to encrypted file and decrypt it on server (Using Public key encryption)将文件转换为加密文件并在服务器上解密(使用公钥加密)
【发布时间】:2013-12-17 02:12:59
【问题描述】:

我正在尝试使用 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为解密数据。

请帮忙,我在这里缺少什么。

【问题讨论】:

  • 你的意思是运行后encryptedFile的大小为零?

标签: java file-io cryptography encryption-asymmetric javax.crypto


【解决方案1】:

您不使用 RSA 进行数据加密。您使用它来加密对称密钥,并使用对称密钥来加密您的数据。公钥算法用于密钥传输或密钥协商,而不是数据。

您应该为您的应用程序使用 CMS (S/MIME) 或 PGP 库。

【讨论】:

    【解决方案2】:

    我不知道您尝试加密的文件大小,但在 RSA 中,您无法加密太多数据。它受限于作为键的一部分的 N 参数,因此可以肯定您的数据应该比键短。也许这就是问题所在。

    通常,您使用公钥加密来加密对称密钥(例如 AES),然后使用加密的对称密钥有效地加密数据。这称为混合加密。

    我建议您首先尝试使用 AES 进行加密,然后尝试仅加密 AES 密钥。

    【讨论】:

    • 只有 1.3kb 的简单文本文件
    • 我相信您的意思是 KB - 这比 RSA 的密钥要多得多(即使在 2048 位 = 256 字节的情况下)。按照我在回答中的描述进行混合加密。
    猜你喜欢
    • 2021-02-17
    • 2012-04-11
    • 2011-03-30
    • 2021-02-02
    • 2014-10-22
    • 1970-01-01
    • 2014-10-24
    • 2017-08-18
    • 2017-01-04
    相关资源
    最近更新 更多