使用 AES 和 MAC 的 Java 加密

问题描述 投票:0回答:1

我正在尝试找到一种方法来完成我的 Java 课程作业。我应该加密一个文件,但老实说我并没有真正理解这些说明。我实现了文件加密和解密,但是我怀疑它是否按照说明进行操作。说明如下:

  • 加密分为三个阶段:
  • 生成16字节随机数据作为CBC模式所需的初始向量(IV)
  • 应用 AES 密码,使用 PKCS5 填充方案以 CBC 模式加密文件内容。
  • 应用 MAC 密码(例如“HmacSHA1”)来计算封装 IV 和密文的 MAC
  • 加密文件将是以下数据的串联: 16 字节 IV ||密文|| 20 字节 HMAC

我写的代码是这样的,成功加密了一个文本文件。这是我的应用程序的完整代码。

import java.io.FileNotFoundException;
import java.io.*;
import java.util.Scanner;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.AlgorithmParameters;
import java.security.SecureRandom;
import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class AESFileEncryption {

/*public AESFileEncryption(String nameoffile){

}
public String FileReturn(String filename){
    String fl = filename;       
    return fl;      
}*/

public static void main(String[] args) throws Exception {

    File f = new File("plainfile.txt");
    File g = new File("plainfile.txt.8102");
    File fl = new File("plainfile.txt.8102");

    if(g.exists() && !g.isDirectory()){
        System.out.println("The file is already encrypted...");
        String fname = fl.getAbsolutePath();
        System.out.print("Absolute Encrypted File Pathname => "+ fname);
        System.exit(0);
    }       
    else if(f.exists() && !f.isDirectory()) { 
         System.out.println(" The file is found.The encryption process is going to begin...");

    }       
    else{
         System.out.println(" The file is missing!!!!");
         System.exit(0);
    }

    // file to be encrypted
    FileInputStream inFile = new FileInputStream("plainfile.txt");       

    // encrypted file
    FileOutputStream outFile = new FileOutputStream("plainfile.txt.8102");


    // password to encrypt the file
    Scanner scan= new Scanner(System.in);
    System.out.println("Enter the password : => ");
    String password= scan.nextLine();

    //String password = "javapapers";

    // password, iv and salt should be transferred to the other end
    // in a secure manner

    // salt is used for encoding
    // writing it to a file
    // salt should be transferred to the recipient securely
    // for decryption
    byte[] salt = new byte[8];
    SecureRandom secureRandom = new SecureRandom();
    secureRandom.nextBytes(salt);
    FileOutputStream saltOutFile = new FileOutputStream("salt.enc");
    saltOutFile.write(salt);
    saltOutFile.close();

    SecretKeyFactory factory = SecretKeyFactory
            .getInstance("PBKDF2WithHmacSHA1");
    KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 65536,
            256);
    SecretKey secretKey = factory.generateSecret(keySpec);
    SecretKey secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

    //
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = cipher.getParameters();

    // iv adds randomness to the text and just makes the mechanism more
    // secure
    // used while initializing the cipher
    // file to store the iv
    FileOutputStream ivOutFile = new FileOutputStream("iv.enc");
    byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
    ivOutFile.write(iv);
    ivOutFile.close();

    //file encryption
    byte[] input = new byte[64];
    int bytesRead;

    while ((bytesRead = inFile.read(input)) != -1) {
        byte[] output = cipher.update(input, 0, bytesRead);
        if (output != null)
            outFile.write(output);
    }

    byte[] output = cipher.doFinal();
    if (output != null)
        outFile.write(output);

    inFile.close();
    outFile.flush();
    outFile.close();

    System.out.println("File Encrypted.");

    }

}
java encryption cryptography aes hmac
1个回答
5
投票

导师的意思是应该应用HMAC来为密文创建一个认证标签。这称为“先加密后 MAC”。 HMAC 是一种密钥哈希函数,它为拥有正确密钥的接收者提供真实性(和完整性,因为没有完整性的真实性没有任何意义)检查。由于它本质上是一个哈希函数,因此它通过更新内部状态来工作。 Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec macKey = new SecretKeySpec(macKeyBytes, "HmacSHA1"); mac.init(macKey); mac.update(iv); // update for IV ... mac.update(output); // update for each ciphertext chunk ... byte[] authTag = mac.doFinal(); outfile.write(authTag); // at the very end

仍然存在一个问题,那就是
macKeyBytes

的产生。它不应与您通过 PBKDF2 从密码生成的加密密钥相同。您应该使用生成的密钥分别导出加密和 MAC 密钥。这通常是使用

HKDF
完成的,但您也可以再次使用 HMAC 来完成。伪代码: byte[] encKeyBytes = hmacSha256(key, "Encryption"); byte[] macKeyBytes = hmacSha256(key, "Authentication");

该指令没有提及任何有关密钥或密码的信息,因此我假设它应该是静态密钥(用于测试目的)。您使用 PBKDF2 的方式是可以的,但盐也必须写入文件中。否则,如果没有随机盐,接收者将无法导出相同的密钥。另外,salt 的长度应该是 16 个字节。

当前代码的另一个问题是您将 IV 写入单独的文件中。不要那样做。只需将 IV 写入密文文件的开头即可。 IV 与 CBC 模式下的块大小相同,而 AES 的块大小固定为 16 字节。接收者将始终知道 IV 需要读取多少字节。

© www.soinside.com 2019 - 2024. All rights reserved.