Beispiel #1
0
        public void Core_Security_Cryptography_DesEncryptor()
        {
            var rawData   = "Hello, I am raw";
            var encryptor = new DesEncryptor(rawData);
            var encrypted = encryptor.Encrypt(rawData);

            Assert.IsTrue(rawData != encrypted);
            Assert.IsTrue(encryptor.Decrypt(encrypted) == rawData);
        }
        public string Encrypt(string text, string?salt = null)
        {
            var isSaltEmpty     = string.IsNullOrWhiteSpace(salt);
            var saltDescription = isSaltEmpty ? $"empty {nameof(salt)}" : $"{nameof(salt)} '{salt}'";

            _logger.LogInformation($"Encryption of {nameof(text)} '{text}' with {saltDescription} requested.");

            string hash;
            string textAndSalt;

            if (isSaltEmpty)
            {
                hash        = DesEncryptor.Encrypt(text);
                salt        = hash.Substring(0, 2);
                textAndSalt = text + salt;
            }
            else
            {
                textAndSalt = text + salt;
                if (_cache.TryGetValue <string>(textAndSalt, out var cachedHash))
                {
                    _logger.LogInformation($"Encrypted value of the {nameof(text)} '{text}' " +
                                           $"was found in cache; the value is '{cachedHash}'.");

                    return(cachedHash);
                }

                hash = DesEncryptor.Encrypt(text, salt);
            }

            _cache.GetOrCreate(textAndSalt, cacheEntry =>
            {
                cacheEntry.Size = 13;
                return(hash);
            });

            _logger.LogInformation($"Encryption of {nameof(text)} '{text}' with {saltDescription} succeeded. " +
                                   $"Encrypted value is '{hash}'.");

            return(hash);
        }
Beispiel #3
0
        public string Encrypt(string text, string?salt = null)
        {
            var isSaltEmpty     = string.IsNullOrWhiteSpace(salt);
            var saltDescription = isSaltEmpty ? $"empty {nameof(salt)}" : $"{nameof(salt)} '{salt}'";

            _logger.LogInformation($"Encryption of {nameof(text)} '{text}' with {saltDescription} requested.");

            string hash = isSaltEmpty
                ? DesEncryptor.Encrypt(text)
                : DesEncryptor.Encrypt(text, salt);

            _cache.GetOrCreate(hash, cacheEntry =>
            {
                var trimmedText = text.Length <= 8 ? text : text.Substring(0, 8);
                cacheEntry.Size = trimmedText.Length;
                return(trimmedText);
            });

            _logger.LogInformation($"Encryption of {nameof(text)} '{text}' with {saltDescription} succeeded. " +
                                   $"Encrypted value is '{hash}'.");

            return(hash);
        }