1 /**
2  * Copyright:       Copyright (C) 2018 Gabriel Gheorghe, All Rights Reserved
3  * Authors:         $(Gabriel Gheorghe)
4  * License:         $(LINK2 https://www.gnu.org/licenses/gpl-3.0.txt, GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007)
5  * Source
6  * Documentation:
7  * Coverage:
8  */
9 module liberty.core.securetypes;
10 ///
11 enum SecureLevel: ubyte {
12     /// Crypted Key is initialized once when program executes.
13     Level0 = 0x00,
14     /// Crypted Key is changed when value is initialized. Inherits Level0.
15     Level1 = 0x01,
16     /// Crypted Key is changed every frame. Inherits Level1.
17     Level2 = 0x02,
18     /// Crypted Key is changed every tick. Inherits Level2.
19     /// The most secure level but unfortunately it decreases CPU performance.
20     /// It drastically decrease CPU performance when used in most declarations.
21     /// Recommended for keeping money or similar things.
22     Level3 = 0x03,
23     /// Crypted Key is changed when developer wants.
24     /// To use this Level developer should create some rules.
25     Custom = 0xFF
26 }
27 ///
28 struct Crypted(T) {
29     ///
30     alias type = T;
31     ///
32     alias value this;
33     private {
34         T _value;
35         T _cryptedKey;
36         SecureLevel _secureLevel;
37     }
38     ///
39     this(T value, SecureLevel secure_level = SecureLevel.Level0) pure nothrow @safe @nogc @property {
40         _secureLevel = secure_level;
41         _value = value;
42         final switch (_secureLevel) with (SecureLevel) {
43             case Level0:
44             case Level1:
45             case Level2:
46             case Level3:
47                 generateRandomKey;
48                 cryptWithKey;
49                 break;
50             case Custom:
51                 break;
52         }
53     }
54     ///
55     void value(T value) pure nothrow @safe @nogc @property {
56     }
57     ///
58     T value() pure nothrow const @safe @nogc @property {
59         return _value - _cryptedKey;
60     }
61     private void generateRandomKey() nothrow @safe @nogc {
62         import std.random : uniform, Random;
63         auto rnd = Random(73);
64         _cryptedKey = uniform!T(rnd);
65     }
66     private void cryptWithKey() pure nothrow @safe @nogc {
67         _value += _cryptedKey;
68     }
69     private void decryptWithKey() pure nothrow @safe @nogc {
70         _value -= _cryptedKey;
71     }
72 }
73 ///
74 char[] encrypt(char[] input, char shift) pure nothrow @safe { // byte?
75 	auto result = input.dup;
76 	result[] += shift;
77 	return result;
78 }
79 ///
80 char[] decrypt(char[] input, char shift) pure nothrow @safe { // byte?
81 	auto result = input.dup;
82 	result[] -= shift;
83 	return result;
84 }