完整性检查文件加密方法

时间:2014-09-18 03:55:16

标签: java encryption

我正在加密文件,作为执行其他操作的更大应用程序的一部分。该文件使用AES加密(随机密钥)进行加密,并包含在RSA公钥加密中。这样做的原因是加密文件将由具有匹配私钥的适当人员发送/访问。

我的加密文件的核心功能如下。我将keyBlock写入加密文件的前面,然后写入加密数据。

我有几个问题:

1)从架构和安全角度来看,这种加密文件的方法是否真正加密文件? - 还是有点傻?如果愚蠢的话,其他选择可能是合理的;和

2)从安全的角度来看,是否将keyBlock附加到加密文件的前面?

为任何想法或评论事先欢呼并表示感谢。

Java函数:

// File in = plain input file
// File out = encrypted output file
// Key pubKey = public Key (that wraps a random AES key)
public static void encryptFile(File in, File out, Key pubKey) throws Exception {
    FileInputStream fin;
    FileOutputStream fout;
    int nread = 0;
    byte[] inbuf = new byte[1024];
    fout = new FileOutputStream(out);
    fin = new FileInputStream(in);

    SecureRandom random = new SecureRandom();
    // symmetric wrapping
    Key sKey = createKeyForAES(Config.SYM_CRYPTO_STR, random);
    IvParameterSpec sIvSpec = createCtrIvForAES(0, random);

    // encrypt symmetric key with RSA/pub key
    Cipher xCipher = Cipher.getInstance(Config.RSA_INSTANCE);
    xCipher.init(Cipher.ENCRYPT_MODE, pubKey, random);
    byte[] keyBlock = xCipher.doFinal(packKeyAndIv(sKey, sIvSpec));

    fout.write(keyBlock);
    System.out.println("keyblock size = " + keyBlock.length);

    // encrypt data with symmetric key
    Cipher sCipher = Cipher.getInstance(Config.AES_INSTANCE);
    sCipher.init(Cipher.ENCRYPT_MODE, sKey, sIvSpec);


    // Now read our file and encrypt it.
    while((nread = fin.read(inbuf)) >0) {
        byte[] trimbuf = new byte[nread];
        for(int i=0;i<nread;i++)
            trimbuf[i] = inbuf[i];

        byte[] newtmp = sCipher.update(trimbuf);
        if(newtmp != null)
            fout.write(newtmp);
    }

    byte[] finalbuf = sCipher.doFinal();
    if(finalbuf !=null)
        fout.write(finalbuf);

    fout.flush();
    fin.close();
    fout.close();
}                                                                

1 个答案:

答案 0 :(得分:0)

// Now read our file and encrypt it.
while((nread = fin.read(inbuf)) >0) {
    byte[] trimbuf = new byte[nread];
    for(int i=0;i<nread;i++)
        trimbuf[i] = inbuf[i];

    byte[] newtmp = sCipher.update(trimbuf);
    if(newtmp != null)
        fout.write(newtmp);
}

byte[] finalbuf = sCipher.doFinal();
if(finalbuf !=null)
    fout.write(finalbuf);

你是在一个小山丘上建造一座山:

// Now read our file and encrypt it.
while((nread = fin.read(inbuf)) > 0) {
    fout.write(sCipher.update(inbuf, 0, nread)); // cannot be null, by construction
}
// NB doFinal() cannot return null, but can return a zero-length array, which is benign below.
fout.write(sCipher.doFinal());
  

从架构和安全角度来看,这种加密文件的方法是否真正加密文件?

我相信这很常见。

  

2)从安全的角度来看,是否将keyBlock附加到加密文件的前面?

它与您的私钥一样安全。