Created
May 8, 2014 07:15
-
-
Save irmansulaeman41/f85577d4648f6970e501 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
namespace PhoneApp1 | |
{ | |
public class RC4 | |
{ | |
public static string Encrypt(string key, string data) | |
{ | |
Encoding unicode = Encoding.Unicode; | |
return Convert.ToBase64String(Encrypt(unicode.GetBytes(key), unicode.GetBytes(data))); | |
} | |
public static string Decrypt(string key, string data) | |
{ | |
Encoding unicode = Encoding.Unicode; | |
byte[] byData = Encrypt(unicode.GetBytes(key), Convert.FromBase64String(data)); | |
return unicode.GetString(byData, 0, byData.Length); | |
} | |
public static byte[] Encrypt(byte[] key, byte[] data) | |
{ | |
return EncryptOutput(key, data).ToArray(); | |
} | |
public static byte[] Decrypt(byte[] key, byte[] data) | |
{ | |
return EncryptOutput(key, data).ToArray(); | |
} | |
private static byte[] EncryptInitalize(byte[] key) | |
{ | |
byte[] s = Enumerable.Range(0, 256) | |
.Select(i => (byte)i) | |
.ToArray(); | |
for (int i = 0, j = 0; i < 256; i++) | |
{ | |
j = (j + key[i % key.Length] + s[i]) & 255; | |
Swap(s, i, j); | |
} | |
return s; | |
} | |
private static IEnumerable<byte> EncryptOutput(byte[] key, IEnumerable<byte> data) | |
{ | |
byte[] s = EncryptInitalize(key); | |
int i = 0; | |
int j = 0; | |
return data.Select((b) => | |
{ | |
i = (i + 1) & 255; | |
j = (j + s[i]) & 255; | |
Swap(s, i, j); | |
return (byte)(b ^ s[(s[i] + s[j]) & 255]); | |
}); | |
} | |
private static void Swap(byte[] s, int i, int j) | |
{ | |
byte c = s[i]; | |
s[i] = s[j]; | |
s[j] = c; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
coba diubah encodingnya jadi pake utf-8