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);
}
在SetKey
中的Cast5Engine.cs
方法内,所以我更新了这个方法,因此没有固定长度为x
16,我做了
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);
}`
但现在通过比较Cast5
BouncyCastel
Cast5
与OpenSSL
Bouncycastel Cast5
的结果,似乎Setkey
未更新使用正确的密钥,因此会产生错误的加密/解密。
是否有任何修改{{1}}方法的建议?
答案 0 :(得分:0)
从查看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&gt; 16)len = 16;”行,它们只保留密钥的前16个字节。这不可能是Conquer Online 2.0的吗?我认识到“BC234xs45nme7HU9”。