基于AES和MAC的Java加密

基于AES和MAC的Java加密,java,encryption,cryptography,aes,hmac,Java,Encryption,Cryptography,Aes,Hmac,我正试图找到一种方法来完成我的Java课程。我被要求加密一个文件,但老实说,我没有真正理解说明。我实现了文件加密和解密,但我怀疑它是否符合说明中的要求。说明如下: 加密分为三个阶段: 生成16字节随机数据作为CBC模式所需的初始向量(IV) 使用PKCS5填充方案,在CBC模式下应用AES密码加密文件内容 应用MAC密码(例如,“HmacSHA1”)来计算封装IV和密文的MAC 加密文件将是以下数据的串联:16字节IV | | |密文| | 20字节HMAC 我写的代码是这样的,它成功地加密

我正试图找到一种方法来完成我的Java课程。我被要求加密一个文件,但老实说,我没有真正理解说明。我实现了文件加密和解密,但我怀疑它是否符合说明中的要求。说明如下:

  • 加密分为三个阶段:
  • 生成16字节随机数据作为CBC模式所需的初始向量(IV)
  • 使用PKCS5填充方案,在CBC模式下应用AES密码加密文件内容
  • 应用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.");

    }

}

讲师的意思是应该应用HMAC为密文创建身份验证标签。这就是所谓的。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密钥。这通常是用来完成的,但是您也可以再次使用HMAC来完成。伪代码:

byte[] encKeyBytes = hmacSha256(key, "Encryption");
byte[] macKeyBytes = hmacSha256(key, "Authentication");

该指令没有说明任何关于密钥或密码的内容,因此我假设它应该是一个静态密钥(用于测试目的)。但是您使用PBKDF2的方式是可以的,但是salt也必须写入文件。否则,如果没有随机salt,收件人将无法派生相同的密钥。此外,salt的长度应该大约为16字节


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