我正在编写一个加密程序,并希望将多个密码块和流模式与哈希机制一起使用。我没有任何使用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的供应商。
*为什么*您是否在使用BC提供程序来实现这种功能?你不喜欢硬件加速?这是应该在默认提供程序上执行的基本功能。 –