using System;namespace cn.com.daway { public class Rijndael { /* Rijndael Block Cipher - rijndael.c Written by Mike Scott 21st April 1999 [email protected] An alternative faster version is implemented in MIRACL ftp://ftp.computing.dcu.ie/pub/crypto/miracl.zip Copyright (c) 1999 Mike Scott Simply compile and run, e.g. cl /O2 rijndael.c (Microsoft C) bcc32 /O2 rijndael.c (Borland C) gcc -O2 rijndael.c -o rijndael (Gnu C) Compiles and runs fine as a C++ program also. See rijndael documentation. The code follows the documentation as closely as possible, and where possible uses the same function and variable names. Permission for free direct or derivative use is granted subject to compliance with any conditions that the originators of the algorithm place on its exploitation. Inspiration from Brian Gladman's implementation is acknowledged. Written for clarity, rather than speed. Assumes long is 32 bit quantity. Full implementation. Endian indifferent.
Ported to C# by http://www.egilh.com/ */ /* rotates x one bit to the left */ private const string PASSWORD="dawayitspanfeng"; private static byte ROTL(byte x) { return (byte) (((x)>>7)|((x)<<1)); } /* Rotates 32-bit word left by 1, 2 or 3 byte */ private static uint ROTL8(uint x) { return (((x)<<8)|((x)>>24)); } private static uint ROTL16(uint x) { return (((x)<<16)|((x)>>16)); }
private static uint ROTL24(uint x) { return (((x)<<24)|((x)>>8)); } /* Fixed Data */ static byte[] InCo = {0xB,0xD,0x9,0xE}; /* Inverse Coefficients */ static byte[] fbsub = new byte[256]; static byte[] rbsub = new byte[256]; static byte[] ptab = new byte[256]; static byte[] ltab = new byte [256]; static uint[] ftable = new uint[256]; static uint[] rtable = new uint[256]; static uint[] rco = new uint[30]; /* Parameter-dependent data */ int Nk,Nb,Nr; byte[] fi = new byte[24]; byte[] ri = new byte[24]; uint[] fkey = new uint[120]; uint[] rkey = new uint[120]; static uint pack(byte []b) { /* pack bytes into a 32-bit Word */ return (uint) (b[3]<<24|b[2]<<16|b[1]<<8|b[0]); } static uint packAt(byte []b, int i) { /* pack bytes into a 32-bit Word */ return (uint) (b[i + 3]<<24|b[i + 2]<<16|b[i + 1]<<8|b[i + 0]); } static void unpack(uint a, byte []b) { /* unpack bytes from a word */ b[0]=(byte)a; b[1]=(byte)(a>>8); b[2]=(byte)(a>>16); b[3]=(byte)(a>>24); } static void unpackAt(uint a, byte []b, int i) { /* unpack bytes from a word */ b[0 + i]=(byte)a; b[1 + i]=(byte)(a>>8); b[2 + i]=(byte)(a>>16); b[3 + i]=(byte)(a>>24); } static byte xtime(byte a) { byte b; if ((a & 0x80) != 0) b=0x1B; else b=0; a<<=1; a^=b; return a; } static byte bmul(byte x,byte y) { /* x.y= AntiLog(Log(x) + Log(y)) */ if (x !=0 && y != 0) return ptab[(ltab[x]+ltab[y])%255]; else return 0; } static uint SubByte(uint a) { byte[] b = new byte[4]; unpack(a,b); b[0]=fbsub[b[0]]; b[1]=fbsub[b[1]]; b[2]=fbsub[b[2]]; b[3]=fbsub[b[3]]; return pack(b); } static byte product(uint x,uint y) { /* dot product of two 4-byte arrays */ byte[] xb = new byte[4]; byte[] yb = new byte[4]; unpack(x,xb); unpack(y,yb); return (byte) (bmul(xb[0],yb[0])^bmul(xb[1],yb[1])^bmul(xb[2],yb[2])^bmul(xb[3],yb[3])); } static uint InvMixCol(uint x) { /* matrix Multiplication */ uint y,m; byte[]b = new byte[4]; m=pack(InCo); b[3]=product(m,x); m=ROTL24(m); b[2]=product(m,x); m=ROTL24(m); b[1]=product(m,x); m=ROTL24(m); b[0]=product(m,x); y=pack(b); return y; } byte ByteSub(byte x) { byte y=ptab[255-ltab[x]]; /* multiplicative inverse */ x=y; x=ROTL(x); y^=x; x=ROTL(x); y^=x; x=ROTL(x); y^=x; x=ROTL(x); y^=x; y^=0x63; return y; } void gentables() { /* generate tables */ int i; byte y; byte[] b = new byte[4]; /* use 3 as primitive root to generate power and log tables */ ltab[0]=0; ptab[0]=1; ltab[1]=0; ptab[1]=3; ltab[3]=1; for (i=2;i<256;i++) { ptab[i] = (byte) (ptab[i-1]^xtime(ptab[i-1])); ltab[ptab[i]]= (byte) i; }
/* affine transformation:- each bit is xored with itself shifted one bit */ fbsub[0]=0x63; rbsub[0x63]=0; for (i=1;i<256;i++) { y=ByteSub((byte)i); fbsub[i]= (byte) y; rbsub[y]=(byte) i; } for (i=0,y=1;i<30;i++) { rco[i]=y; y=xtime(y); } /* calculate forward and reverse tables */ for (i=0;i<256;i++) { y=fbsub[i]; b[3]=(byte) (y^xtime(y)); b[2]=y; b[1]=y; b[0]=xtime(y); ftable[i]=pack(b); y=rbsub[i]; b[3]=bmul(InCo[0],y); b[2]=bmul(InCo[1],y); b[1]=bmul(InCo[2],y); b[0]=bmul(InCo[3],y); rtable[i]=pack(b); } } void gkey(int nb,int nk,byte []key) { /* blocksize=32*nb bits. Key=32*nk bits */ /* currently nb,bk = 4, 6 or 8 */ /* key comes as 4*Nk bytes */ /* Key Scheduler. Create expanded encryption key */ int i,j,k,m,N; int C1,C2,C3; uint[] CipherKey = new uint[8];
Nb=nb; Nk=nk; /* Nr is number of rounds */ if (Nb>=Nk) Nr=6+Nb; else Nr=6+Nk; C1=1; if (Nb<8) { C2=2; C3=3; } else { C2=3; C3=4; } /* pre-calculate forward and reverse increments */ for (m=j=0;j<nb;j++,m+=3) { fi[m]= (byte) ((j+C1)%nb); fi[m+1]= (byte) ((j+C2)%nb); fi[m+2]= (byte) ((j+C3)%nb); ri[m]= (byte) ((nb+j-C1)%nb); ri[m+1]= (byte) ((nb+j-C2)%nb); ri[m+2]= (byte) ((nb+j-C3)%nb); } N=Nb*(Nr+1);
for (i=j=0;i<Nk;i++,j+=4) { CipherKey[i] = packAt(key, j); } for (i=0;i<Nk;i++) fkey[i]=CipherKey[i]; for (j=Nk,k=0;j<N;j+=Nk,k++) { fkey[j]=fkey[j-Nk]^SubByte(ROTL24(fkey[j-1]))^rco[k]; if (Nk<=6) { for (i=1;i<Nk && (i+j)<N;i++) fkey[i+j]=fkey[i+j-Nk]^fkey[i+j-1]; } else { for (i=1;i<4 &&(i+j)<N;i++) fkey[i+j]=fkey[i+j-Nk]^fkey[i+j-1]; if ((j+4)<N) fkey[j+4]=fkey[j+4-Nk]^SubByte(fkey[j+3]); for (i=5;i<Nk && (i+j)<N;i++) fkey[i+j]=fkey[i+j-Nk]^fkey[i+j-1]; } } /* now for the expanded decrypt key in reverse order */ for (j=0;j<Nb;j++) rkey[j+N-Nb]=fkey[j]; for (i=Nb;i<N-Nb;i+=Nb) { k=N-Nb-i; for (j=0;j<Nb;j++) rkey[k+j]=InvMixCol(fkey[i+j]); } for (j=N-Nb;j<N;j++) rkey[j-N+Nb]=fkey[j]; }
/* There is an obvious time/space trade-off possible here. * * Instead of just one ftable[], I could have 4, the other * * 3 pre-rotated to save the ROTL8, ROTL16 and ROTL24 overhead */ void encrypt(byte []buff, int offset) { int i,j,k,m; uint[] a = new uint[8]; uint[] b = new uint[8];
uint[] x; uint[] y; uint[] t; for (i=j=0;i<Nb;i++,j+=4) { a[i] = packAt(buff, j + offset); a[i] ^= fkey[i]; } k=Nb; x = a; y = b; /* State alternates between a and b */ for (i=1;i<Nr;i++) { /* Nr is number of rounds. May be odd. */ /* if Nb is fixed - unroll this next loop and hard-code in the values of fi[] */ for (m=j=0;j<Nb;j++,m+=3) { /* deal with each 32-bit element of the State */ /* This is the time-critical bit */ y[j]=fkey[k++]^ftable[(byte)x[j]]^ ROTL8(ftable[(byte)(x[fi[m]]>>8)])^ ROTL16(ftable[(byte)(x[fi[m+1]]>>16)])^ ROTL24(ftable[x[fi[m+2]]>>24]); } t=x; x=y; y=t; /* swap pointers */ } /* Last Round - unroll if possible */ for (m=j=0;j<Nb;j++,m+=3) { y[j]=fkey[k++]^(uint)fbsub[(byte)x[j]]^ ROTL8((uint)fbsub[(byte)(x[fi[m]]>>8)])^ ROTL16((uint)fbsub[(byte)(x[fi[m+1]]>>16)])^ ROTL24((uint)fbsub[x[fi[m+2]]>>24]); } for (i=j=0;i<Nb;i++,j+=4) { unpackAt(y[i], buff, j + offset); x[i]=y[i]=0; /* clean up stack */ } return; } void decrypt(byte []buff, int offset) { int i,j,k,m; uint[] a = new uint[8]; uint[] b = new uint[8]; uint[] x; uint[] y; uint[] t; for (i=j=0;i<Nb;i++,j+=4) { a[i]=packAt(buff, j + offset); a[i]^=rkey[i]; } k=Nb; x=a; y=b; /* State alternates between a and b */ for (i=1;i<Nr;i++) { /* Nr is number of rounds. May be odd. */ /* if Nb is fixed - unroll this next loop and hard-code in the values of ri[] */ for (m=j=0;j<Nb;j++,m+=3) { /* This is the time-critical bit */ y[j]=rkey[k++]^rtable[(byte)x[j]]^ ROTL8(rtable[(byte)(x[ri[m]]>>8)])^ ROTL16(rtable[(byte)(x[ri[m+1]]>>16)])^ ROTL24(rtable[x[ri[m+2]]>>24]); } t=x; x=y; y=t; /* swap pointers */ } /* Last Round - unroll if possible */ for (m=j=0;j<Nb;j++,m+=3) { y[j]=rkey[k++]^(uint)rbsub[(byte)x[j]]^ ROTL8((uint)rbsub[(byte)(x[ri[m]]>>8)])^ ROTL16((uint)rbsub[(byte)(x[ri[m+1]]>>16)])^ ROTL24((uint)rbsub[x[ri[m+2]]>>24]); } for (i=j=0;i<Nb;i++,j+=4) { unpackAt(y[i], buff, j + offset); x[i]=y[i]=0; /* clean up stack */ } return; } public Rijndael() { gentables(); } public int keySize { get { return 0; } set {
} } /// <summary> /// Generate the 32 bit key from the password. Each character becomes one byte /// in the key. If the password is not long enough we use it again until /// we reach 32 bits. /// </summary> /// <param name="sPassword"></param> /// <returns></returns> private byte[] generateKey(string sPassword) { //void gkey(int nb,int nk,byte []key) /* blocksize=32*nb bits. Key=32*nk bits */ /* currently nb,bk = 4, 6 or 8 */ /* key comes as 4*Nk bytes */ const byte KEY_LENGTH = 32; int iPasswordLength = sPassword.Length; byte[] key = new byte[32];
for (byte i=0; i < KEY_LENGTH; i++) { key[i] = (byte) sPassword[i % iPasswordLength]; } gkey(8,8,key); return key; } public byte[] Encrypt (string sData, string sPassword) { // Convert the string to byte byte[] baReturn = new byte[sData.Length]; for (int i=0; i < sData.Length; i++) { baReturn[i] = (byte) sData[i]; } return Encrypt(baReturn, sPassword); }
private static char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; public static string ToHexString(byte[] bytes) { char[] chars = new char[bytes.Length * 2]; for (int i = 0; i < bytes.Length; i++) { int b = bytes[i]; chars[i * 2] = hexDigits[b >> 4]; chars[i * 2 + 1] = hexDigits[b & 0xF]; } return new string(chars); } public static string ByteToString(byte[] bytes) { char[] chars = new char[bytes.Length]; for (int i = 0; i < bytes.Length; i++) { chars[i] = (char) bytes[i]; } return new string(chars); } /// <summary> /// Encrypt an array of bytes with the given password /// </summary> /// <param name="baData"></param> /// <param name="sPassword"></param> /// <returns>Encrypted array of bytes. The size of the array will be larger than the source </returns> public byte[] Encrypt (byte[] baData, string sPassword) { // Generate the key from the password byte [] key = generateKey(sPassword);
// Rijandel works on blocks of 32 bytes. // Final size is: // - 4 bytes for the size of the original data // - the source data // - possibly half empty last block so byte [] encoded = new byte [4 + baData.Length + (32 - (baData.Length % 32))]; // Store the length of the source data encoded[0] = (byte) (0x000000ff & baData.Length); encoded[1] = (byte) ((0x0000ff00 & baData.Length) >> 8); encoded[2] = (byte) ((0x00ff0000 & baData.Length) >> 16); encoded[3] = (byte) ((0xff000000 & baData.Length) >> 24);
// Copy the data Array.Copy(baData, 0, encoded, 4, baData.Length); // Init the rest of the data with 0's for (int i = baData.Length + 4 ; i < encoded.Length; i++) { encoded[i] = 0; } // Encode the data for (int block = 0; block <= baData.Length / 32; block ++ ) { encrypt(encoded, (block * 32) + 4); } return encoded; } /// <summary> /// 加密 /// </summary> /// <param name="baData">明文</param> /// <returns>密文</returns> public byte[] Encrypt (byte[] baData) { return Encrypt(baData,PASSWORD); } /// <summary> /// Decrypt an array of bytes with the given password /// </summary> /// <param name="encoded"></param> /// <param name="sPassword"></param> /// <returns></returns> public byte[] Decrypt (byte[] encoded, string sPassword) { // Generate the key from the password byte [] key = generateKey(sPassword);
// TO DO: Sanity check on the data at least 36 bytes, multiple of 32 (-4) // Get the size of the decoded data int iDecodedLength = (int) (encoded[0] + ROTL8(encoded[1]) +ROTL16(encoded[2]) + ROTL24(encoded[3]));
// Decode the data for (int block = 0; block <= iDecodedLength / 32; block ++ ) { decrypt(encoded, (block * 32) + 4); } byte [] decoded = new byte [iDecodedLength]; // Copy the data Array.Copy(encoded, 4, decoded, 0, iDecodedLength); return decoded; } /// <summary> /// 解密 /// </summary> /// <param name="encoded">密文</param> /// <returns>明文</returns> public byte[] Decrypt(byte[] encoded) { return Decrypt(encoded,PASSWORD); } } }
{
public class Rijndael
{
/* Rijndael Block Cipher - rijndael.c Written by Mike Scott 21st April 1999
[email protected]
An alternative faster version is implemented in MIRACL
ftp://ftp.computing.dcu.ie/pub/crypto/miracl.zip Copyright (c) 1999 Mike Scott Simply compile and run, e.g. cl /O2 rijndael.c (Microsoft C)
bcc32 /O2 rijndael.c (Borland C)
gcc -O2 rijndael.c -o rijndael (Gnu C) Compiles and runs fine as a C++ program also. See rijndael documentation. The code follows the documentation as closely
as possible, and where possible uses the same function and variable names. Permission for free direct or derivative use is granted subject
to compliance with any conditions that the originators of the
algorithm place on its exploitation. Inspiration from Brian Gladman's implementation is acknowledged. Written for clarity, rather than speed.
Assumes long is 32 bit quantity.
Full implementation.
Endian indifferent.
Ported to C# by http://www.egilh.com/
*/ /* rotates x one bit to the left */
private const string PASSWORD="dawayitspanfeng"; private static byte ROTL(byte x)
{
return (byte) (((x)>>7)|((x)<<1));
} /* Rotates 32-bit word left by 1, 2 or 3 byte */ private static uint ROTL8(uint x)
{
return (((x)<<8)|((x)>>24));
}
private static uint ROTL16(uint x)
{
return (((x)<<16)|((x)>>16));
}
private static uint ROTL24(uint x)
{
return (((x)<<24)|((x)>>8));
} /* Fixed Data */ static byte[] InCo = {0xB,0xD,0x9,0xE}; /* Inverse Coefficients */ static byte[] fbsub = new byte[256];
static byte[] rbsub = new byte[256];
static byte[] ptab = new byte[256];
static byte[] ltab = new byte [256];
static uint[] ftable = new uint[256];
static uint[] rtable = new uint[256];
static uint[] rco = new uint[30]; /* Parameter-dependent data */ int Nk,Nb,Nr;
byte[] fi = new byte[24];
byte[] ri = new byte[24];
uint[] fkey = new uint[120];
uint[] rkey = new uint[120]; static uint pack(byte []b)
{ /* pack bytes into a 32-bit Word */
return (uint) (b[3]<<24|b[2]<<16|b[1]<<8|b[0]);
} static uint packAt(byte []b, int i)
{ /* pack bytes into a 32-bit Word */
return (uint) (b[i + 3]<<24|b[i + 2]<<16|b[i + 1]<<8|b[i + 0]);
} static void unpack(uint a, byte []b)
{ /* unpack bytes from a word */
b[0]=(byte)a;
b[1]=(byte)(a>>8);
b[2]=(byte)(a>>16);
b[3]=(byte)(a>>24);
} static void unpackAt(uint a, byte []b, int i)
{ /* unpack bytes from a word */
b[0 + i]=(byte)a;
b[1 + i]=(byte)(a>>8);
b[2 + i]=(byte)(a>>16);
b[3 + i]=(byte)(a>>24);
} static byte xtime(byte a)
{
byte b;
if ((a & 0x80) != 0) b=0x1B;
else b=0;
a<<=1;
a^=b;
return a;
} static byte bmul(byte x,byte y)
{ /* x.y= AntiLog(Log(x) + Log(y)) */
if (x !=0 && y != 0) return ptab[(ltab[x]+ltab[y])%255];
else return 0;
} static uint SubByte(uint a)
{
byte[] b = new byte[4];
unpack(a,b);
b[0]=fbsub[b[0]];
b[1]=fbsub[b[1]];
b[2]=fbsub[b[2]];
b[3]=fbsub[b[3]];
return pack(b);
} static byte product(uint x,uint y)
{ /* dot product of two 4-byte arrays */
byte[] xb = new byte[4];
byte[] yb = new byte[4];
unpack(x,xb);
unpack(y,yb);
return (byte) (bmul(xb[0],yb[0])^bmul(xb[1],yb[1])^bmul(xb[2],yb[2])^bmul(xb[3],yb[3]));
} static uint InvMixCol(uint x)
{ /* matrix Multiplication */
uint y,m;
byte[]b = new byte[4]; m=pack(InCo);
b[3]=product(m,x);
m=ROTL24(m);
b[2]=product(m,x);
m=ROTL24(m);
b[1]=product(m,x);
m=ROTL24(m);
b[0]=product(m,x);
y=pack(b);
return y;
} byte ByteSub(byte x)
{
byte y=ptab[255-ltab[x]]; /* multiplicative inverse */
x=y; x=ROTL(x);
y^=x; x=ROTL(x);
y^=x; x=ROTL(x);
y^=x; x=ROTL(x);
y^=x; y^=0x63;
return y;
} void gentables()
{ /* generate tables */
int i;
byte y;
byte[] b = new byte[4]; /* use 3 as primitive root to generate power and log tables */ ltab[0]=0;
ptab[0]=1; ltab[1]=0;
ptab[1]=3; ltab[3]=1;
for (i=2;i<256;i++)
{
ptab[i] = (byte) (ptab[i-1]^xtime(ptab[i-1]));
ltab[ptab[i]]= (byte) i;
}
/* affine transformation:- each bit is xored with itself shifted one bit */ fbsub[0]=0x63;
rbsub[0x63]=0;
for (i=1;i<256;i++)
{
y=ByteSub((byte)i);
fbsub[i]= (byte) y; rbsub[y]=(byte) i;
} for (i=0,y=1;i<30;i++)
{
rco[i]=y;
y=xtime(y);
} /* calculate forward and reverse tables */
for (i=0;i<256;i++)
{
y=fbsub[i];
b[3]=(byte) (y^xtime(y)); b[2]=y;
b[1]=y; b[0]=xtime(y);
ftable[i]=pack(b); y=rbsub[i];
b[3]=bmul(InCo[0],y); b[2]=bmul(InCo[1],y);
b[1]=bmul(InCo[2],y); b[0]=bmul(InCo[3],y);
rtable[i]=pack(b);
}
} void gkey(int nb,int nk,byte []key)
{ /* blocksize=32*nb bits. Key=32*nk bits */
/* currently nb,bk = 4, 6 or 8 */
/* key comes as 4*Nk bytes */
/* Key Scheduler. Create expanded encryption key */
int i,j,k,m,N;
int C1,C2,C3;
uint[] CipherKey = new uint[8];
Nb=nb; Nk=nk; /* Nr is number of rounds */
if (Nb>=Nk) Nr=6+Nb;
else Nr=6+Nk; C1=1;
if (Nb<8) { C2=2; C3=3; }
else { C2=3; C3=4; } /* pre-calculate forward and reverse increments */
for (m=j=0;j<nb;j++,m+=3)
{
fi[m]= (byte) ((j+C1)%nb);
fi[m+1]= (byte) ((j+C2)%nb);
fi[m+2]= (byte) ((j+C3)%nb);
ri[m]= (byte) ((nb+j-C1)%nb);
ri[m+1]= (byte) ((nb+j-C2)%nb);
ri[m+2]= (byte) ((nb+j-C3)%nb);
} N=Nb*(Nr+1);
for (i=j=0;i<Nk;i++,j+=4)
{
CipherKey[i] = packAt(key, j);
}
for (i=0;i<Nk;i++) fkey[i]=CipherKey[i];
for (j=Nk,k=0;j<N;j+=Nk,k++)
{
fkey[j]=fkey[j-Nk]^SubByte(ROTL24(fkey[j-1]))^rco[k];
if (Nk<=6)
{
for (i=1;i<Nk && (i+j)<N;i++)
fkey[i+j]=fkey[i+j-Nk]^fkey[i+j-1];
}
else
{
for (i=1;i<4 &&(i+j)<N;i++)
fkey[i+j]=fkey[i+j-Nk]^fkey[i+j-1];
if ((j+4)<N) fkey[j+4]=fkey[j+4-Nk]^SubByte(fkey[j+3]);
for (i=5;i<Nk && (i+j)<N;i++)
fkey[i+j]=fkey[i+j-Nk]^fkey[i+j-1];
} } /* now for the expanded decrypt key in reverse order */ for (j=0;j<Nb;j++) rkey[j+N-Nb]=fkey[j];
for (i=Nb;i<N-Nb;i+=Nb)
{
k=N-Nb-i;
for (j=0;j<Nb;j++) rkey[k+j]=InvMixCol(fkey[i+j]);
}
for (j=N-Nb;j<N;j++) rkey[j-N+Nb]=fkey[j];
}
* Instead of just one ftable[], I could have 4, the other *
* 3 pre-rotated to save the ROTL8, ROTL16 and ROTL24 overhead */
void encrypt(byte []buff, int offset)
{
int i,j,k,m;
uint[] a = new uint[8];
uint[] b = new uint[8];
uint[] x;
uint[] y;
uint[] t; for (i=j=0;i<Nb;i++,j+=4)
{
a[i] = packAt(buff, j + offset);
a[i] ^= fkey[i];
}
k=Nb;
x = a;
y = b; /* State alternates between a and b */
for (i=1;i<Nr;i++)
{ /* Nr is number of rounds. May be odd. */ /* if Nb is fixed - unroll this next
loop and hard-code in the values of fi[] */ for (m=j=0;j<Nb;j++,m+=3)
{ /* deal with each 32-bit element of the State */
/* This is the time-critical bit */
y[j]=fkey[k++]^ftable[(byte)x[j]]^
ROTL8(ftable[(byte)(x[fi[m]]>>8)])^
ROTL16(ftable[(byte)(x[fi[m+1]]>>16)])^
ROTL24(ftable[x[fi[m+2]]>>24]);
}
t=x; x=y; y=t; /* swap pointers */
} /* Last Round - unroll if possible */
for (m=j=0;j<Nb;j++,m+=3)
{
y[j]=fkey[k++]^(uint)fbsub[(byte)x[j]]^
ROTL8((uint)fbsub[(byte)(x[fi[m]]>>8)])^
ROTL16((uint)fbsub[(byte)(x[fi[m+1]]>>16)])^
ROTL24((uint)fbsub[x[fi[m+2]]>>24]);
}
for (i=j=0;i<Nb;i++,j+=4)
{
unpackAt(y[i], buff, j + offset);
x[i]=y[i]=0; /* clean up stack */
}
return;
} void decrypt(byte []buff, int offset)
{
int i,j,k,m;
uint[] a = new uint[8];
uint[] b = new uint[8];
uint[] x;
uint[] y;
uint[] t; for (i=j=0;i<Nb;i++,j+=4)
{
a[i]=packAt(buff, j + offset);
a[i]^=rkey[i];
}
k=Nb;
x=a; y=b; /* State alternates between a and b */
for (i=1;i<Nr;i++)
{ /* Nr is number of rounds. May be odd. */ /* if Nb is fixed - unroll this next
loop and hard-code in the values of ri[] */
for (m=j=0;j<Nb;j++,m+=3)
{ /* This is the time-critical bit */
y[j]=rkey[k++]^rtable[(byte)x[j]]^
ROTL8(rtable[(byte)(x[ri[m]]>>8)])^
ROTL16(rtable[(byte)(x[ri[m+1]]>>16)])^
ROTL24(rtable[x[ri[m+2]]>>24]);
}
t=x; x=y; y=t; /* swap pointers */
} /* Last Round - unroll if possible */
for (m=j=0;j<Nb;j++,m+=3)
{
y[j]=rkey[k++]^(uint)rbsub[(byte)x[j]]^
ROTL8((uint)rbsub[(byte)(x[ri[m]]>>8)])^
ROTL16((uint)rbsub[(byte)(x[ri[m+1]]>>16)])^
ROTL24((uint)rbsub[x[ri[m+2]]>>24]);
}
for (i=j=0;i<Nb;i++,j+=4)
{
unpackAt(y[i], buff, j + offset);
x[i]=y[i]=0; /* clean up stack */
}
return;
}
public Rijndael()
{
gentables();
} public int keySize
{
get
{
return 0;
}
set
{
}
} /// <summary>
/// Generate the 32 bit key from the password. Each character becomes one byte
/// in the key. If the password is not long enough we use it again until
/// we reach 32 bits.
/// </summary>
/// <param name="sPassword"></param>
/// <returns></returns>
private byte[] generateKey(string sPassword)
{
//void gkey(int nb,int nk,byte []key)
/* blocksize=32*nb bits. Key=32*nk bits */
/* currently nb,bk = 4, 6 or 8 */
/* key comes as 4*Nk bytes */
const byte KEY_LENGTH = 32;
int iPasswordLength = sPassword.Length;
byte[] key = new byte[32];
for (byte i=0; i < KEY_LENGTH; i++)
{
key[i] = (byte) sPassword[i % iPasswordLength];
} gkey(8,8,key); return key;
} public byte[] Encrypt (string sData, string sPassword)
{
// Convert the string to byte
byte[] baReturn = new byte[sData.Length];
for (int i=0; i < sData.Length; i++)
{
baReturn[i] = (byte) sData[i];
}
return Encrypt(baReturn, sPassword);
}
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
public static string ToHexString(byte[] bytes)
{
char[] chars = new char[bytes.Length * 2];
for (int i = 0; i < bytes.Length; i++)
{
int b = bytes[i];
chars[i * 2] = hexDigits[b >> 4];
chars[i * 2 + 1] = hexDigits[b & 0xF];
}
return new string(chars);
} public static string ByteToString(byte[] bytes)
{
char[] chars = new char[bytes.Length];
for (int i = 0; i < bytes.Length; i++)
{
chars[i] = (char) bytes[i];
}
return new string(chars);
} /// <summary>
/// Encrypt an array of bytes with the given password
/// </summary>
/// <param name="baData"></param>
/// <param name="sPassword"></param>
/// <returns>Encrypted array of bytes. The size of the array will be larger than the source </returns>
public byte[] Encrypt (byte[] baData, string sPassword)
{
// Generate the key from the password
byte [] key = generateKey(sPassword);
// Rijandel works on blocks of 32 bytes.
// Final size is:
// - 4 bytes for the size of the original data
// - the source data
// - possibly half empty last block so
byte [] encoded = new byte [4 + baData.Length + (32 - (baData.Length % 32))];
// Store the length of the source data
encoded[0] = (byte) (0x000000ff & baData.Length);
encoded[1] = (byte) ((0x0000ff00 & baData.Length) >> 8);
encoded[2] = (byte) ((0x00ff0000 & baData.Length) >> 16);
encoded[3] = (byte) ((0xff000000 & baData.Length) >> 24);
// Copy the data
Array.Copy(baData, 0, encoded, 4, baData.Length); // Init the rest of the data with 0's
for (int i = baData.Length + 4 ; i < encoded.Length; i++)
{
encoded[i] = 0;
} // Encode the data
for (int block = 0; block <= baData.Length / 32; block ++ )
{
encrypt(encoded, (block * 32) + 4);
} return encoded;
} /// <summary>
/// 加密
/// </summary>
/// <param name="baData">明文</param>
/// <returns>密文</returns>
public byte[] Encrypt (byte[] baData)
{
return Encrypt(baData,PASSWORD);
}
/// <summary>
/// Decrypt an array of bytes with the given password
/// </summary>
/// <param name="encoded"></param>
/// <param name="sPassword"></param>
/// <returns></returns>
public byte[] Decrypt (byte[] encoded, string sPassword)
{
// Generate the key from the password
byte [] key = generateKey(sPassword);
// TO DO: Sanity check on the data at least 36 bytes, multiple of 32 (-4) // Get the size of the decoded data
int iDecodedLength = (int) (encoded[0] + ROTL8(encoded[1]) +ROTL16(encoded[2]) + ROTL24(encoded[3]));
// Decode the data
for (int block = 0; block <= iDecodedLength / 32; block ++ )
{
decrypt(encoded, (block * 32) + 4);
}
byte [] decoded = new byte [iDecodedLength]; // Copy the data
Array.Copy(encoded, 4, decoded, 0, iDecodedLength);
return decoded;
}
/// <summary>
/// 解密
/// </summary>
/// <param name="encoded">密文</param>
/// <returns>明文</returns>
public byte[] Decrypt(byte[] encoded)
{
return Decrypt(encoded,PASSWORD); }
}
}