📄 blowfishengine.cpp
字号:
}
//CString CBlowFishEngine::getAlgorithmName(void)
//{
// return CString("Blowfish");
//}
int CBlowFishEngine::processBlock(char in[], int inOff, char out[], int outOff)
{
//if(workingKey == null)
// throw new IllegalStateException("Blowfish not initialised");
//if(inOff + 8 > in.length)
// throw new IOException("input buffer too short");
//if(outOff + 8 > out.length)
// throw new IOException("output buffer too short");
if(encrypting)
encryptBlock(in, inOff, out, outOff);
else
decryptBlock(in, inOff, out, outOff);
return 8;
}
int CBlowFishEngine::getBlockSize(void)
{
return 8;
}
int CBlowFishEngine::F(int x)
{
unsigned int ux = (unsigned int)x;
return (int)((S0[ux >> 24] + S1[ux >> 16 & 0xff] ^ S2[ux >> 8 & 0xff]) + S3[ux & 0xff]);
}
void CBlowFishEngine::processTable(int xl, int xr, int table[], int tablelength)
{
int size = tablelength;
for(int s = 0; s < size; s += 2)
{
xl ^= P[0];
for(int i = 1; i < 16; i += 2)
{
xr ^= F(xl) ^ P[i];
xl ^= F(xr) ^ P[i + 1];
}
xr ^= P[17];
table[s] = xr;
table[s + 1] = xl;
xr = xl;
xl = table[s];
}
}
void CBlowFishEngine::setKey(char key[], int keylength)
{
int i;
for(i=0;i<256;i++)
S0[i] = KS0[i];
for(i=0;i<256;i++)
S1[i] = KS1[i];
for(i=0;i<256;i++)
S2[i] = KS2[i];
for(i=0;i<256;i++)
S3[i] = KS3[i];
for(i=0;i<18;i++)
P[i] = KP[i];
int keyLength = keylength;
int keyIndex = 0;
for(int i = 0; i < 18; i++)
{
int data = 0;
for(int j = 0; j < 4; j++)
{
data = data << 8 | key[keyIndex++] & 0xff;
if(keyIndex >= keyLength)
keyIndex = 0;
}
P[i] ^= data;
}
processTable(0, 0, P, 18);
processTable(P[16], P[17], S0, 256);
processTable(S0[254], S0[255], S1, 256);
processTable(S1[254], S1[255], S2, 256);
processTable(S2[254], S2[255], S3, 256);
}
void CBlowFishEngine::encryptBlock(char src[], int srcIndex, char dst[], int dstIndex)
{
int xl = BytesTo32bits(src, srcIndex);
int xr = BytesTo32bits(src, srcIndex + 4);
xl ^= P[0];
for(int i = 1; i < 16; i += 2)
{
xr ^= F(xl) ^ P[i];
xl ^= F(xr) ^ P[i + 1];
}
xr ^= P[17];
Bits32ToBytes(xr, dst, dstIndex);
Bits32ToBytes(xl, dst, dstIndex + 4);
}
void CBlowFishEngine::decryptBlock(char src[], int srcIndex, char dst[], int dstIndex)
{
int xl = BytesTo32bits(src, srcIndex);
int xr = BytesTo32bits(src, srcIndex + 4);
xl ^= P[17];
for(int i = 16; i > 0; i -= 2)
{
xr ^= F(xl) ^ P[i];
xl ^= F(xr) ^ P[i - 1];
}
xr ^= P[0];
Bits32ToBytes(xr, dst, dstIndex);
Bits32ToBytes(xl, dst, dstIndex + 4);
}
int CBlowFishEngine::BytesTo32bits(char b[], int i)
{
return (b[i + 3] & 0xff) << 24 | (b[i + 2] & 0xff) << 16 | (b[i + 1] & 0xff) << 8 | b[i] & 0xff;
}
void CBlowFishEngine::Bits32ToBytes(int in, char b[], int offset)
{
b[offset] = (char)in;
b[offset + 1] = (char)(in >> 8);
b[offset + 2] = (char)(in >> 16);
b[offset + 3] = (char)(in >> 24);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -