Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ///
- /// <summary>
- /// Encrypt and compress data in one. Invented by gigajew.
- /// </summary>
- ///
- public class TinyCrypt {
- private Random _random;
- private byte[] _key;
- public byte[] Key {
- get {
- return _key;
- }
- private set {
- _key = value;
- }
- }
- public byte[] Encrypt(byte[] data, byte[] key = null) {
- if(key != null) {
- Key = key;
- }
- using (MemoryStream memory = new MemoryStream()) {
- data = Compress(data);
- for (int i = 0; i < data.Length; i++)
- {
- data[i] ^= Key[i % Key.Length];
- memory.WriteByte(data[i]);
- }
- return memory.ToArray();
- }
- }
- public byte[] Decrypt(byte[] data, byte[] key = null) {
- if(key != null) {
- Key = key;
- }
- using (MemoryStream memory = new MemoryStream(data)) {
- byte[] buffer = new byte[memory.Length];
- for(int i = 0 ; i < buffer.Length; i++) {
- buffer[i] = (byte) ((int) memory.ReadByte() ^ (int) Key[i % Key.Length]);
- }
- return Decompress(buffer);
- }
- }
- private byte[] Compress(byte[] data) {
- using (MemoryStream output = new MemoryStream())
- {
- using (GZipStream zip = new GZipStream(output, CompressionMode.Compress, true)) {
- zip.Write(data, 0, data.Length);
- }
- return output.ToArray();
- }
- }
- private byte[] Decompress(byte[] data)
- {
- using (MemoryStream memory = new MemoryStream(data))
- using (GZipStream zip = new GZipStream(memory, CompressionMode.Decompress))
- {
- const int size = 4096;
- byte[] buffer = new byte[size];
- using (MemoryStream output = new MemoryStream())
- {
- int count = 0;
- do
- {
- count = zip.Read(buffer, 0, size);
- if (count > 0)
- {
- output.Write(buffer, 0, count);
- }
- }
- while (count > 0);
- return output.ToArray();
- }
- }
- }
- public void RandomizeKey() {
- _key = new byte[4096];
- _random.NextBytes(_key);
- }
- public void RandomizeSeed() {
- _random = new Random(Guid.NewGuid().GetHashCode());
- }
- public TinyCrypt() {
- RandomizeSeed();
- RandomizeKey();
- }
- }
Add Comment
Please, Sign In to add comment