生活随笔
收集整理的這篇文章主要介紹了
RC4算法实现
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1、密鑰流:RC4算法的關鍵是根據(jù)明文和密鑰生成相應的密鑰流,密鑰流的長度和明文的長度是對應的,也就是說明文的長度是500字節(jié),那么密鑰流也是500字節(jié)。當然,加密生成的密文也是500字節(jié),因為密文第i字節(jié)=明文第i字節(jié)^密鑰流第i字節(jié);
2、狀態(tài)向量S:長度為256,S[0],S[1].....S[255]。每個單元都是一個字節(jié),算法運行的任何時候,S都包括0-255的8比特數(shù)的排列組合,只不過值的位置發(fā)生了變換;
3、臨時向量T:長度也為256,每個單元也是一個字節(jié)。如果密鑰的長度是256字節(jié),就直接把密鑰的值賦給T,否則,輪轉(zhuǎn)地將密鑰的每個字節(jié)賦給T;
?4、密鑰K:長度為1-256字節(jié),注意密鑰的長度?keylen?與明文長度、密鑰流的長度沒有必然關系,通常密鑰的長度取為16字節(jié)(128比特)。
5、算法實現(xiàn)
[cpp]?view plaincopy
?? template<class?T>?inline?void???? swap(T&?i,?T&?j)???? {???? ????T?tmp?=?i;???? ????i?=?j;???? ????j?=?tmp;???? }???? class?RC4???? {???? public:???? ????void?SetKey(const?char*?key,?int?keylen);???? ????void?Transform(char*?output,?const?char*?input,?int?len);???? private:???? ????unsigned?char?key_[256];???? };???? ?? ?? #include?"rc4.h"???? void?RC4::SetKey(const?char*?key,?int?keylen)???? {???? ????for?(int?i?=?0;?i?<?256;?i++)???? ????{???? ????????key_[i]?=?i;???? ????}???? ????int?j?=?0;???? ????for?(int?i?=?0;?i?<?256;?i++)???? ????{???? ????????j?=?(j?+?key_[i]?+?key[i%keylen])?%?256;???? ????????swap(key_[i],?key_[j]);???? ????}???? }???? void?RC4::Transform(char*?output,?const?char*?input,?int?len)???? {???? ????int?i?=?0,?j?=?0;???? ????for?(int?k?=?0;?k?<?len;?k++)???? ????{???? ????????i?=?(i?+?1)?%?256;???? ????????j?=?(j?+?key_[i])?%?256;???? ????????swap(key_[i],?key_[j]);???? ????????unsigned?char?subkey?=?key_[(key_[i]?+?key_[j])?%?256];???? ????????output[k]?=?subkey?^?input[k];???? ????}???? }???? ?? ?? #include?<stdio.h>???? #include?<string.h>???? #include?<stdlib.h>???? #include?"rc4.h"???? int?main()???? {???? ????char?input[256]?=?"Times?teaches?all?things?to?him?who?lives?forever?but?I?have?not?the?luxury?of?eternity.";???? ????char?output[256]?=?"";???? ????printf("before?encrypt:%s/n",?input);???? ????const?int?keylen?=?16;???? ????char?key[keylen]?=?"";???? ????for?(int?i?=?0;?i?<?keylen;?i++)???? ????{???? ????????key[i]?=?rand()?%?256;???? ????}???? ????RC4?rc4encrypt,?rc4decrypt;???? ????rc4encrypt.SetKey(key,?keylen);???? ????rc4decrypt.SetKey(key,?keylen);???? ????rc4encrypt.Transform(output,?input,?strlen(input));???? ????printf("after?encrypt:?%s/n",?output);???? ????rc4decrypt.Transform(output,?output,?strlen(input));???? ????printf("after?decrypt:?%s/n",?output);???? ????return?0;???? } ? ?
總結
以上是生活随笔為你收集整理的RC4算法实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。