BouncyCastel Cast5 setkey
本文关键字:setkey Cast5 BouncyCastel | 更新日期: 2023-09-27 18:22:00
using System;
using System.Linq;
using System.Text;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Utilities.Encoders;
namespace Common.Encryption {
public class Cast5Cryptographer {
private bool forEncryption;
private BufferedBlockCipher cipher;
public Cast5Cryptographer(bool forEncryption) {
this.forEncryption = forEncryption;
cipher = new BufferedBlockCipher(new CfbBlockCipher(new Cast5Engine(), 64));
cipher.Init(forEncryption, new ParametersWithIV(new KeyParameter(Encoding.ASCII.GetBytes("BC234xs45nme7HU9")), new byte[8]));
}
public void ReInit(byte[] IV, BigInteger pubkey) {
cipher.Init(forEncryption, new ParametersWithIV(new KeyParameter(pubkey.ToByteArrayUnsigned()), IV));
}
public int BlockSize {
get {
return cipher.GetBlockSize();
}
}
public byte[] DoFinal() {
return cipher.DoFinal();
}
public byte[] DoFinal(byte[] buffer) {
return cipher.DoFinal(buffer);
}
public byte[] DoFinal(byte[] buffer, int startIndex, int len) {
return cipher.DoFinal(buffer, startIndex, len);
}
public byte[] ProcessBytes(byte[] buffer) {
return cipher.ProcessBytes(buffer);
}
public byte[] ProcessBytes(byte[] buffer, int startIndex, int len) {
return cipher.ProcessBytes(buffer, startIndex, len);
}
}
}
它使用上面的键工作正常,上面的长度为 16 ,但是当我尝试使用此键ReInit()
它时 byte[] newkey = new byte[] { 0x39, 0x65, 0x38, 0x63, 0x64, 0x32, 0x36, 0x63, 0x37, 0x37, 0x34, 0x31, 0x33, 0x65, 0x61, 0x36, 0x65, 0x35, 0x35, 0x39, 0x61, 0x32, 0x35, 0x32, 0x66, 0x30, 0x31, 0x35, 0x32, 0x38, 0x66, 0x39, 0x34, 0x38, 0x66, 0x33, 0x33, 0x34, 0x32, 0x62, 0x31, 0x38, 0x37, 0x36, 0x34, 0x61, 0x66, 0x35, 0x36, 0x38, 0x62, 0x39, 0x63, 0x39, 0x30, 0x33, 0x63, 0x35, 0x38, 0x38, 0x35, 0x34, 0x65, 0x63 };
它抛出此异常Index was outside the bounds of the array.
for (int i = 0; i < key.Length; i++) {
x[i] = (int)(key[i] & 0xff);
}
在 Cast5Engine.cs
年的 SetKey
方法中,所以我更新了这个方法,而不是将固定长度固定为 16 x
我做到了
int[] x = new int[key.Length];
for (int i = 0; i < 16; i++) x[i] = 0;
/* copy the key into x */
for (int i = 0; i < key.Length; i++) {
x[i] = (int)(key[i] & 0xff);
}`
但是现在通过比较从BouncyCastel
Cast5
到OpenSSL
Cast5
的结果,似乎Bouncycastel Cast5
没有使用正确的密钥进行更新,因此会产生错误的加密/解密。
是否有任何修复Setkey
方法的建议?
从查看OpenSSL的CAST_setKey方法的源代码来看...
void CAST_set_key(CAST_KEY *key, int len, const unsigned char *data)
#ifdef OPENSSL_FIPS
{
fips_cipher_abort(CAST);
private_CAST_set_key(key, len, data);
}
void private_CAST_set_key(CAST_KEY *key, int len, const unsigned char *data)
#endif
{
CAST_LONG x[16];
CAST_LONG z[16];
CAST_LONG k[32];
CAST_LONG X[4],Z[4];
CAST_LONG l,*K;
int i;
for (i=0; i<16; i++) x[i]=0;
if (len > 16) len=16;
请参阅行"if (len> 16( len = 16;",它们只保留密钥的前 16 个字节。这不会碰巧适用于征服在线2.0吧?,我认得"BC234xs45nme7HU9"。