最近研究JWT算法, JWT由header、payload、signature三个部分组成,payload是非加密的,一些敏感信息能被别人非法获得,必要时候要加密。
加密算法中,RC4算法的速度可以达到DES加密的10倍左右,且具有很高级别的非线性。由于RC4算法加密是采用的xor,所以,一旦子密钥序列出现了重复,密文就有可能被破解。而jwt的payload是json格式,所以容易被破解。
经过几天对RC4算法研究,终于写成性能不错的算法,趁IPHONE X的热,就叫RCX算法。
加密例子:
密钥(secret key):ToolGood 输出数据类型(output data type):Base64_Url
RC4('ABCDDDDDDDDDDDDDDDDDDDDDD') => O8AF0I3sAzyQaTO78S9irZwDfemUR4eGsw
RC4('ACBDDDDDDDDDDDDDDDDDDDDDD') => O8EE0I3sAzyQaTO78S9irZwDfemUR4eGsw
RC4('CBADDDDDDDDDDDDDDDDDDDDDD') => OcAH0I3sAzyQaTO78S9irZwDfemUR4eGsw
RC4('1234567891234567891234567') => S7B1oPyecEDtHEXMgV4Q3uB-CJ_jN_b0wA
RC4('1234567800034567891234567') => S7B1oPyecEDkHUfMgV4Q3uB-CJ_jN_b0wA
RCX('ABCDDDDDDDDDDDDDDDDDDDDDD') => O3priO83Pd4e-7IeTBJmrIax7kmO5yzr2Q
RCX('ACBDDDDDDDDDDDDDDDDDDDDDD') => O3s81pEyp9daRW9yHYC4ynIOalk8FYSI9g
RCX('CBADDDDDDDDDDDDDDDDDDDDDD') => OXpp1Sm4eyyhg5MQGWrjGa6w2MZhoK09Kw
RCX('1234567891234567891234567') => SwoWZFa8uiJnqv_arFs0WVHOfYRvMGTsAw
RCX('1234567800034567891234567') => SwoWZFa8uiJuQXjGVkKaspQseRHK9qtVZA
从上面的代码,可以明显看出RC4算法的缺点,数据经过RCX算法加密后变得无序。
RCX的算法如下:
public class RCX { private const int keyLen = 256; /// <summary> /// Encrypt /// </summary> /// <param name="data"></param> /// <param name="pass"></param> /// <returns></returns> public static byte[] Encrypt(byte[] data, byte[] pass) { if (data == null) throw new ArgumentNullException("data"); if (pass == null) throw new ArgumentNullException("pass"); byte[] mBox = GetKey(pass, keyLen); byte[] output = new byte[data.Length]; int i = 0, j = 0; for (int offset = 0; offset < data.Length; offset++) { i = (++i) & 0xFF; j = (j + mBox[i]) & 0xFF; byte a = data[offset]; byte c = (byte)(a ^ mBox[(mBox[i] + mBox[j]) & 0xFF]); output[offset] = c; byte temp2 = mBox[c]; mBox[c] = mBox[a]; mBox[a] = temp2; j = (j + a + c); } return output; } /// <summary> /// Encrypt /// </summary> /// <param name="data"></param> /// <param name="pass"></param> /// <returns></returns> public static byte[] Encrypt(byte[] data, string pass) { if (data == null) throw new ArgumentNullException("data"); if (pass == null) throw new ArgumentNullException("pass"); return Encrypt(data, Encoding.Unicode.GetBytes(pass)); } private static byte[] GetKey(byte[] pass, int kLen) { byte[] mBox = new byte[kLen]; for (Int64 i = 0; i < kLen; i++) { mBox[i] = (byte)i; } Int64 j = 0; for (Int64 i = 0; i < kLen; i++) { j = (j + mBox[i] + pass[i % pass.Length]) % kLen; byte temp = mBox[i]; mBox[i] = mBox[j]; mBox[j] = temp; } return mBox; } }
代码分析:
RC4采用 i 与 j 对密码盘进行调换。
RCX采用[明文]与[密文]进行调换,并且对 j 进行修改。
性能:
密钥(secret key):ToolGood
数据长度(data length):10000
加密次数(encryption count):1000
RC4 => 150ms
RCX => 255ms
原代码:https://github.com/toolgood/RCX