2017-07-24 64 views
1

我正在编写一个加密程序,并希望将多个密码块和流模式与哈希机制一起使用。我没有任何使用OFB等流模式对消息进行加密,解密和验证的问题,但是当他们使用填充时,我在使用blockcipher moder解密和验证消息时遇到了问题。在填充和块密码模式下使用哈希

例如我使用ECB(我知道它不是很好)与PKCS7Padding和SHA-256。在我解密消息后,它最后有一些字符。除此之外,我收到消息,散列摘要不等于原始摘要。

这个问题不会发生,当我不使用填充。

这里是我的代码:

@Override 
public byte[] encrypt(byte[] input) throws Exception { 
    Cipher cipher = Cipher.getInstance("AES/ECB/" + getPadding(), "BC"); 
    cipher.init(Cipher.ENCRYPT_MODE, getKey()); 
    byte[] output = getBytesForCipher(cipher, input); 
    int ctLength = cipher.update(input, 0, input.length, output, 0); 
    updateHash(input); 
    cipher.doFinal(getDigest(), 0, getDigest().length, output, ctLength); 
    return output; 
} 

protected byte[] getBytesForCipher(Cipher cipher, byte[] input) { 
    return new byte[cipher.getOutputSize(input.length + hash.getDigestLength())]; 
} 

protected void updateHash(byte[] input) { 
    hash.update(input); 
} 


public byte[] decrypt(byte[] input) throws Exception { 
    Cipher cipher = Cipher.getInstance("AES/ECB/" + getPadding(), "BC"); 
    cipher.init(Cipher.DECRYPT_MODE, getKey()); 
    byte[] output = new byte[cipher.getOutputSize(input.length)]; 
    int ctLength = cipher.update(input, 0, input.length, output, 0); 
    cipher.doFinal(output, ctLength); 
    return removeHash(output); 
} 

protected byte[] removeHash(byte[] output) { 
    int messageLength = output.length - hash.getDigestLength(); 
    hash.update(output, 0, output.length - hash.getDigestLength());; 
    byte[] realOutput = new byte[messageLength]; 
    System.arraycopy(output, 0, realOutput, 0, messageLength); 
    messageValid = isValid(output); 
    return realOutput; 
} 

private boolean isValid(byte[] output) { 
    int messageLength = output.length - hash.getDigestLength(); 
    byte[] messageHash = new byte[hash.getDigestLength()]; 
    System.arraycopy(output, messageLength, messageHash, 0, messageHash.length); 
    return MessageDigest.isEqual(hash.digest(), messageHash); 
} 

我使用BouncyCastle的供应商。

+0

*为什么*您是否在使用BC提供程序来实现这种功能?你不喜欢硬件加速?这是应该在默认提供程序上执行的基本功能。 –

回答

2

如果您在CiphergetOutputSize方法来看看你会得到从文档以下内容:

下一个updatedoFinal调用的实际输出长度可能小于此方法返回的长度。

而这恰恰是什么咬你。由于密码实例在解密前无法确定填充量,因此会假定输出/明文大小与明文大小相同。实际上,由于始终执行PKCS#7填充,因此它可能会在JCE实现中假设太多一个字节。

所以你不能忽略doFinal的回应;您需要调整数组大小(例如使用Arrays类),或者从缓冲区中的正确位置抓取明文和散列。

很明显,流密码不会有这个问题,因为明文大小和密文大小是相同的。


通常一个密钥的散列(即,MAC或HMAC)或认证密码被用来确保密文未改变。在明文上使用散列可能无法完全保护您的明文。