|
| 1 | +using System; |
| 2 | +using System.Text; |
| 3 | +using System.Security.Cryptography; |
| 4 | +using SafeCrypt.src.Helpers; |
| 5 | +using SafeCrypt.src.Encryption.AesEncryption.Models; |
| 6 | + |
| 7 | +namespace SafeCrypt.src.Encrypt.AesEncryption |
| 8 | +{ |
| 9 | + public class Encrypting : BaseAesEncryption |
| 10 | + { |
| 11 | + public byte[] Encrypt(byte[] data, byte[] secretKey, byte[] iv) |
| 12 | + => EncryptAES(data, secretKey, iv); |
| 13 | + |
| 14 | + |
| 15 | + public byte[] Encrypt(string data, string secretKey, string iv) |
| 16 | + { |
| 17 | + NullChecks(data, secretKey, iv); |
| 18 | + |
| 19 | + var aesKey = secretKey.ConvertKeysToBytes(); |
| 20 | + var aesIv = iv.ConvertKeysToBytes(); |
| 21 | + |
| 22 | + var aesData = data.HexadecimalStringToByteArray(); |
| 23 | + return EncryptAES(aesData, aesKey, aesIv); |
| 24 | + } |
| 25 | + |
| 26 | + |
| 27 | + |
| 28 | + public AesEncryptionData Encrypt(string data, string secretKey) |
| 29 | + { |
| 30 | + NullChecks(data, secretKey); |
| 31 | + |
| 32 | + var aesIv = GenerateRandomBytes(16); |
| 33 | + |
| 34 | + var aesKey = Encoding.UTF8.GetBytes(secretKey); |
| 35 | + var aesData = data.HexadecimalStringToByteArray(); |
| 36 | + |
| 37 | + var response = EncryptAES(aesData, aesKey, aesIv); |
| 38 | + |
| 39 | + var responseData = new AesEncryptionData |
| 40 | + { |
| 41 | + Data = response, |
| 42 | + Iv = aesIv |
| 43 | + }; |
| 44 | + |
| 45 | + return responseData; |
| 46 | + } |
| 47 | + |
| 48 | + public string EncryptByteToHexString(byte[] data, byte[] secretKey, byte[] iv) |
| 49 | + { |
| 50 | + var cipherText = EncryptAES(data, secretKey, iv); |
| 51 | + |
| 52 | + return cipherText.ByteArrayToHexString(); |
| 53 | + } |
| 54 | + |
| 55 | + public string EncryptByteToBase64String(byte[] data, byte[] secretKey, byte[] iv) |
| 56 | + { |
| 57 | + var cipherText = EncryptAES(data, secretKey, iv); |
| 58 | + |
| 59 | + return Convert.ToBase64String(cipherText); |
| 60 | + } |
| 61 | + |
| 62 | + public string EncryptByteToString(byte[] data, byte[] secretKey, byte[] iv) |
| 63 | + { |
| 64 | + var cipherText = EncryptAES(data, secretKey, iv); |
| 65 | + |
| 66 | + return cipherText.BytesToString(); |
| 67 | + } |
| 68 | + |
| 69 | + // needs methods that would accept aes mode |
| 70 | + //public byte[] AesEncrypt(byte[] data, byte[] key, byte[] iv, ReturnType returnType) |
| 71 | + //{ |
| 72 | + |
| 73 | + //} |
| 74 | + |
| 75 | + private void NullChecks(string data, string secretKey, string iv = "") |
| 76 | + { |
| 77 | + if (data == null || data.Length <= 0) |
| 78 | + throw new ArgumentNullException(nameof(data)); |
| 79 | + |
| 80 | + if (secretKey == null || secretKey.Length <= 0) |
| 81 | + throw new ArgumentNullException(nameof(secretKey)); |
| 82 | + |
| 83 | + if (iv == null || iv.Length <= 0) |
| 84 | + throw new ArgumentNullException(nameof(iv)); |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | +} |
0 commit comments