Java文件加密 [英] Java File Encryption

查看:104
本文介绍了Java文件加密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用AES algortihm编写一个简单的程序来加密和解密文件。我没有加密问题,但解密..

I'm trying to write a simple program to encrypt and decrypt files using the AES algortihm. I haven't problems with encryption, but decryption..

public static void main(String[] args) throws NoSuchAlgorithmException, FileNotFoundException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {

    // Инициализация секретных ключей
    KeyGenerator keyGenS = KeyGenerator.getInstance("AES");
    keyGenS.init(128);
    SecretKey sKey1 = keyGenS.generateKey();
    SecretKey sKey2 = keyGenS.generateKey();
    // Перевод секретных ключей в строку и запись в файл
    String key1 = SecretKeyToString(sKey1);
    String key2 = SecretKeyToString(sKey2);

    spreader.write(fileName1, key1);
    spreader.write(fileName2, key2);
    spreader.write(fileNameS1, key1);
    spreader.write(fileNameS2, key2);


    // Чтение секретных ключей из файла и перевод обратно в тип SecretKey
    key1 = spreader.read(fileName1);
    System.out.println("Секретный ключ 1го пользователя: " +key1);


    SecretKey seansKey1=getKeyInstance(key1);

    key2 = spreader.read(fileName2);
    System.out.println("Секретный ключ 2го пользователя: " +key2);

    SecretKey seansKey2=getKeyInstance(key2);


    //инициализация и зашифрование сеансового ключа с помощью секретных
    Cipher aesCipher = Cipher.getInstance("AES");
    aesCipher.init(Cipher.ENCRYPT_MODE,seansKey1);

    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(128);
    SecretKey secretKey = keyGen.generateKey();

    String stringsecretKey = SecretKeyToString(secretKey);
    byte[] byteKey = stringsecretKey.getBytes();
    byte[] byteCipherKey1 = aesCipher.doFinal(byteKey); 
    String encryptedKey = new BASE64Encoder().encode(byteCipherKey1);
    System.out.println("Зашифрованный сеансовый ключ с помощью секретного ключа 1: " +encryptedKey);





    aesCipher = Cipher.getInstance("AES");
    aesCipher.init(Cipher.ENCRYPT_MODE,SeansKey2);


     byteKey = etringsecretKey.getBytes();
     byte[] byteCipherKey2 = aesCipher.doFinal(byteKey); 
     encryptedKey = new BASE64Encoder().encode(byteCipherKey2);
    System.out.println("Зашифрованный сеансовый ключ с помощью секретного ключа 2: " +encryptedKey);
    spreader.write(fileNameEK2, encryptedKey);

    //Чтение данных из файла
    String text =spreader.read(fileName);
    System.out.println(text);

    // Зашифрование данных


            aesCipher.init(Cipher.ENCRYPT_MODE,secretKey); // константная переменная

            byte[] byteText = text.getBytes();
            byte[] byteCipherText = aesCipher.doFinal(byteText); 
            encryptedText = new BASE64Encoder().encode(byteCipherText);
            System.out.println("Зашифрованный текст: " +encryptedText);

            spreader.write(fileNameOK, encryptedText);





}

这是解密部分:

public static void main(String[] args) throws NoSuchAlgorithmException, FileNotFoundException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, UnsupportedEncodingException {

    String encryptedText = user.read(fileNameOK);
    String key1 = user.read(fileName1);
    String key2 = user.read(fileName2);
    String encryptedSeanceKey1 = user.read(fileNameEK1);
    String encryptedSeanceKey2 = user.read(fileNameEK2);




    SecretKey secretKey1=getKeyInstance(key1);
    SecretKey secretKey2=getKeyInstance(key2);



    Cipher aesCipher = Cipher.getInstance("AES");
    aesCipher.init(Cipher.DECRYPT_MODE,secretKey1,aesCipher.getParameters());




    //byte[] byteKey = encryptedSeanceKey1.getBytes();

       byte[] byteDecryptedKey = aesCipher.doFinal(encryptedSeanceKey1.getBytes());
       String decryptedKey1 = new String(byteDecryptedKey);
       System.out.println("Расшифрованный сеансовый ключ с помощью секретного ключа 1: " +decryptedKey1);

    aesCipher.init(Cipher.DECRYPT_MODE,secretKey2,aesCipher.getParameters());




    byte[] byteKey2 = encryptedSeanceKey2.getBytes();
        byteDecryptedKey = aesCipher.doFinal(byteKey2); 
        String decryptedKey2 = new String(byteDecryptedKey);
       System.out.println("Расшифрованный сеансовый ключ с помощью секретного ключа 2: " +decryptedKey2);





        // Расшифрование данных
        aesCipher.init(Cipher.DECRYPT_MODE,getKeyInstance(decryptedKey1),aesCipher.getParameters());

         byte[] byteText = encryptedText.getBytes();

        byte[] byteDecryptedText = aesCipher.doFinal(byteText);
        decryptedText = new String(byteDecryptedText);
        System.out.println(" Расшифрованный текст " +decryptedText);



}

}

现在的问题是解密部分是:使用填充密码解密时输入长度必须是16的倍数

Now the problem is the decryption part is: Input length must be multiple of 16 when decrypting with padded cipher

我知道我错误地保留会话密钥和字节的错误丢失了。但是我可以如何正确地做到这一点?

I know that a mistake that I incorrectly keep a session key and bytes are lost. But how I can correctly do it?

推荐答案

你的代码有点混乱,也许是因为你所调用的一些方法或者是因为您正在使用密钥加密...您的密钥(!!!)

我们尝试加密和解密这个简单的方法,删除所有不严格需要的东西您的代码(如编码您的密钥并将其保存到文件,然后恢复密钥而不解码等)。

There is a little bit of confusion in your code, maybe because some method you called are missing, or maybe because you are using your keys to encrypt...your keys(!!!)
Let's try to encrypt and decrypt the easy way, removing all the stuff that is not strictly needed in your code (like encode your key and save it to a file, and then restore the key without decoding it, etc..).

我们来看看下面的简化代码:

Let's take a look at the following simplified code based on your:

    KeyGenerator keyGenS = KeyGenerator.getInstance("AES");
    keyGenS.init(128);
    SecretKey sKey1 = keyGenS.generateKey();

    Cipher aesCipher = Cipher.getInstance("AES");
    aesCipher.init(Cipher.ENCRYPT_MODE,sKey1);

    byte[] byteText = "Insert here whatever you want to crypt".getBytes();

    byte[] byteCipherText = aesCipher.doFinal(byteText);

我们已经用KeyGenerator生成了我们的密钥,然后我们用该密钥初始化了我们的密码实例。在这一点上,我们只需调用 doFinal()传递我们要加密的plainText。

这就是加密部分。当然,如果你想要的话,你可以将你的密钥和 byteCipherText 保存到一个文件中,但所有其他的工作人员(至少)是无用的。

We have generated our key with KeyGenerator, and then we have initialized our Cipher instance with that key. At this point we simply call doFinal() passing the plainText we want to encrypt.
That's all for the encryption part. Of course you can save your keys and byteCipherText to a file if you want, but all the other staff is (at least) useless.

解密部分很容易作为加密。逻辑是一样的
如果您将密钥保存在文件中,只需将其读入 byte [] ,并将其用于初始化您的密码实例。这样做:

The decryption part is easy as the encryption. The logic is the same. If you saved your key on a file, just read it into a byte[], and use it for initialize your cipher instance. Something like this:

    aesCipher.init(Cipher.DECRYPT_MODE, sKey1);
    byte[] plainText = aesCipher.doFinal(byteCipherText);

如果将所有上述代码放入一个 main()并运行它,你应该具有 plainText byteText 中相同的文本。

您可以使用

If you put all the above code into a main() and run it, you should have into plainText the same text as in byteText.
You can verify it with a

    System.out.println(new String(plainText));

尝试从这里开始,然后添加您可能需要的所有其他内容。

希望这有帮助。

问候

Try to start from here, then add all other things you may need.
Hope this helps.
Regards

这篇关于Java文件加密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆