public void EncryptedStringEqualityTests()
        {
            EncryptedString nullString = null;
            var             empty      = new EncryptedString();
            var             encryptedA = Encrypt(ClearText);
            var             encryptedB = Encrypt(ClearText);
            var             encryptedC = Encrypt(ClearText.ToLowerInvariant());

            Assert.IsFalse(ReferenceEquals(nullString, empty));
            Assert.IsFalse(ReferenceEquals(nullString, encryptedA));
            Assert.IsFalse(ReferenceEquals(nullString, encryptedB));
            Assert.IsFalse(ReferenceEquals(empty, encryptedA));
            Assert.IsFalse(ReferenceEquals(empty, encryptedB));
            Assert.IsFalse(ReferenceEquals(encryptedA, encryptedB));

            Assert.IsTrue(nullString != empty);
            Assert.IsTrue(nullString != encryptedA);
            Assert.IsTrue(empty != nullString);
            Assert.IsTrue(encryptedA != nullString);

            Assert.IsTrue(empty != encryptedA);
            Assert.IsTrue(encryptedA != empty);

            Assert.IsTrue(encryptedA == encryptedB);
            Assert.IsTrue(encryptedA != encryptedC);

            Assert.AreEqual <object>(encryptedA, encryptedB);
            Assert.AreEqual <object>(encryptedA, encryptedB.ToArray());
            Assert.AreEqual <object>(encryptedA, encryptedB.ToString());

            Assert.AreNotEqual <object>(encryptedA, empty);
            Assert.AreNotEqual <object>(encryptedA, empty.ToArray());
            Assert.AreNotEqual <object>(encryptedA, empty.ToString());
            Assert.AreNotEqual <object>(encryptedA, 5);
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                return(null);
            }

            if (reader.TokenType == JsonToken.String)
            {
                try
                {
                    var value = new EncryptedString(new Base64String((string)reader.Value));
                    return(value);
                }
                catch (Base64StringConversionException ex)
                {
                    throw new RequestValidationException("Failed to parse Encrypted string as Base64String", reader.Value, ex, reader.Path);
                }
                catch (Exception ex)
                {
                    throw new JsonSerializationException($"Error parsing EncryptedString: [{reader.Value}] at path [{reader.Path}]", ex);
                }
            }

            throw new JsonSerializationException($"Unexpected token or value when parsing EncryptedString. Token [{reader.TokenType}], value [{reader.Value}]");
        }
        public void EncryptedStringHashTest()
        {
            var encryptedBytes = Encrypt(ClearText).ToArray();
            var secureString   = new EncryptedString(encryptedBytes);

            Assert.AreEqual(encryptedBytes.GetHashCode(), secureString.GetHashCode());
        }
        private string Decrypt(EncryptedString text)
        {
            var decrypted = Cryptography.Decrypt(text, _key);

            Assert.AreNotEqual(text, decrypted);
            return(decrypted);
        }
        public async Task Can_sign_transaction()
        {
            //ARRANGE
            var privateKeys = new List <EncryptedString>
            {
                EncryptedString.Encrypt(MyPublicKey, MyPrivateKey.DecodeToString()),
                EncryptedString.Encrypt(MyPublicKey, MyPrivateKey2.DecodeToString()),
            };

            var transactionId     = new TransactionId("TransactionId");
            var signedTransaction = "From.x01.To.x02.Amount.100.Signature.F1T2A100";

            var client = PrepareClient <AppSettings>((options) =>
            {
                Mock <IAddressGenerator> addressGenerator   = new Mock <IAddressGenerator>();
                Mock <ITransactionSigner> transactionSigner = new Mock <ITransactionSigner>();

                transactionSigner.Setup(x => x.SignAsync(It.IsAny <IReadOnlyCollection <string> >(), It.IsAny <Base64String>()))
                .ReturnsAsync(new SignTransactionResponse(Base64String.Encode(signedTransaction), transactionId));

                options.IntegrationName          = $"{nameof(SignServiceClientTests)}+{nameof(Can_sign_transaction)}";
                options.AddressGeneratorFactory  = (context) => addressGenerator.Object;
                options.TransactionSignerFactory = (context) => transactionSigner.Object;
            });

            //ACT
            var request = new SignTransactionRequest(privateKeys, Base64String.Encode(signedTransaction));
            SignTransactionResponse result = await client.SignTransactionAsync(request);

            //ASSERT
            Assert.True(result != null);
            Assert.True(result.TransactionId == transactionId);
            Assert.True(result.SignedTransaction.DecodeToString() == signedTransaction);
        }
Ejemplo n.º 6
0
        public static EncryptedString ReadEncryptedString(this BinaryReader self)
        {
            ulong           value = self.ReadUInt64();
            EncryptedString id    = new EncryptedString(value);

            return(id);
        }
Ejemplo n.º 7
0
        public static string Decrypt(EncryptedString encryptedtext)
        {
            string s     = encryptedtext;
            int    ident = (byte)s[0] - 32;
            int    assoc = (byte)s[s.Length - 1] - 32;

            return(Translate(s.Substring(1, s.Length - 2), cipherPad[assoc], cipherPad[ident]));
        }
        public void AddCommandArguments(string ien, string sig)
        {
            EncryptedString esig = VistAHash.Encrypt(sig);

            this.CommandArgs = new object[] { ien, esig };

            //this.CommandArgs = new object[] { ien, sig };
        }
Ejemplo n.º 9
0
        public string Can_create_from_encrypted_text(string privateKey, string encryptedString)
        {
            var value = new EncryptedString(new Base64String(encryptedString));

            var decryptedString = value.DecryptToString(new Base64String(privateKey));

            return(decryptedString);
        }
        public void AddCommandArguments(string origVerifyCode, string newVerifyCode, string confirmNewVerifyCode)
        {
            EncryptedString es1 = VistAHash.Encrypt(origVerifyCode);
            EncryptedString es2 = VistAHash.Encrypt(newVerifyCode);
            EncryptedString es3 = VistAHash.Encrypt(confirmNewVerifyCode);

            string argsFormat = "{0}^{1}^{2}";

            this.CommandArgs = new object[] { string.Format(argsFormat, es1, es2, es3) };
        }
Ejemplo n.º 11
0
        public static void WriteEncryptedString(this BinaryWriter self, EncryptedString id, bool xbox = false)
        {
            ulong value = id.Encrypted;

            if (xbox)
            {
                value = Util.ReverseBytes(value);
            }
            self.Write(value);
        }
        private string Decrypt_StreamReadToEnd(EncryptedString text)
        {
            string decrypted;

            using (var stream = DecryptingStream.Read(text, _key))
                decrypted = stream.ReadToEnd();

            Assert.AreNotEqual(text, decrypted);
            return(decrypted);
        }
Ejemplo n.º 13
0
        private EncryptedString GetAVParameter(string accessCode, string verifyCode)
        {
            EncryptedString returnVal;

            EncryptedString firstPass = VistAHash.Encrypt(accessCode + ";" + verifyCode);

            returnVal = new EncryptedString(firstPass);

            return(returnVal);
        }
Ejemplo n.º 14
0
        public void Can_encrypt_and_decrypt(string publicKey, string privateKey, string stringToEncrypt)
        {
            var value = EncryptedString.Encrypt(new Base64String(publicKey), stringToEncrypt);

            Assert.AreNotEqual(stringToEncrypt, value.EncryptedValue);

            var decryptedString = value.DecryptToString(new Base64String(privateKey));

            Assert.AreEqual(stringToEncrypt, decryptedString);
        }
Ejemplo n.º 15
0
        public void StoreEncryptedString(EncryptedString value)
        {
            var writer = new ByteBufferWriter();

            writer.WriteString(value);
            var plain   = writer.Data.AsSyncReadOnlySpan();
            var encSize = _symmetricCipher.CalcEncryptedSizeFor(plain);
            var enc     = new byte[encSize];

            _symmetricCipher.Encrypt(plain, enc);
            _writer.WriteByteArray(enc);
        }
Ejemplo n.º 16
0
        public void WriteOrderedEncryptedString(ref SpanWriter outerWriter, EncryptedString value)
        {
            var writer = new SpanWriter();

            writer.WriteString(value);
            var cipher  = _transaction.Owner.GetSymmetricCipher();
            var plain   = writer.GetSpan();
            var encSize = cipher.CalcOrderedEncryptedSizeFor(plain);
            var enc     = new byte[encSize];

            cipher.OrderedEncrypt(plain, enc);
            outerWriter.WriteByteArray(enc);
        }
Ejemplo n.º 17
0
        public void WriteEncryptedString(EncryptedString value)
        {
            var writer = new ByteBufferWriter();

            writer.WriteString(value);
            var cipher  = _serviceClient?.GetSymmetricCipher() ?? _serviceServer?.GetSymmetricCipher();
            var plain   = writer.Data.AsSyncReadOnlySpan();
            var encSize = cipher !.CalcEncryptedSizeFor(plain);
            var enc     = new byte[encSize];

            cipher.Encrypt(plain, enc);
            _writer.WriteByteArray(enc);
        }
Ejemplo n.º 18
0
        public void WriteOrderedEncryptedString(EncryptedString value)
        {
            var writer = new ByteBufferWriter();

            writer.WriteString(value);
            var cipher  = _transaction.Owner.GetSymmetricCipher();
            var plain   = writer.Data.AsSyncReadOnlySpan();
            var encSize = cipher.CalcOrderedEncryptedSizeFor(plain);
            var enc     = new byte[encSize];

            cipher.OrderedEncrypt(plain, enc);
            _writer.WriteByteArray(enc);
        }
        private string Decrypt_StreamRead(EncryptedString text)
        {
            var decrypted = string.Empty;

            using (var stream = DecryptingStream.Read(text, _key))
            {
                var newlyDecrypted = stream.Read(5);
                while (newlyDecrypted != null)
                {
                    decrypted     += newlyDecrypted;
                    newlyDecrypted = stream.Read(5);
                }
            }
            Assert.AreNotEqual(text, decrypted);
            return(decrypted);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SdeDirectDbUserConnectionProvider"/> class.
        /// </summary>
        /// <param name="databaseType">Type of the database.</param>
        /// <param name="databaseName">Name of the database.</param>
        /// <param name="userName">Name of the user.</param>
        /// <param name="plainTextPassword">The plain text password.</param>
        /// <param name="repositoryName">Name of the SDE repository owner.</param>
        public SdeDirectDbUserConnectionProvider(DatabaseType databaseType,
                                                 [NotNull] string databaseName,
                                                 [NotNull] string userName,
                                                 [NotNull] string plainTextPassword,
                                                 [NotNull] string repositoryName)
            : base(GetDefaultName(databaseName, repositoryName, userName),
                   databaseType, databaseName, repositoryName)
        {
            Assert.ArgumentNotNullOrEmpty(userName, nameof(userName));
            Assert.ArgumentNotNull(plainTextPassword, nameof(plainTextPassword));

            _userName          = userName;
            _encryptedPassword = new EncryptedString
            {
                PlainTextValue = plainTextPassword
            };
        }
Ejemplo n.º 21
0
        public void UserWithEmptyPasswordIsNotValid()
        {
            // Arrange
            var encryptionService = new Mock <IEncryptionService>();

            encryptionService.Setup(e => e.Encrypt(It.IsAny <string>())).Returns(new byte[] {});

            var user = new User();

            user.Username = "******";
            user.Password = EncryptedString.Create(string.Empty, encryptionService.Object);

            // Act
            bool isValid = user.IsValid;

            // Assert
            Assert.IsFalse(isValid);
        }
Ejemplo n.º 22
0
        public void UserIsValid()
        {
            // Arrange
            var encryptionService = new Mock <IEncryptionService>();

            encryptionService.Setup(e => e.Encrypt(It.IsAny <string>())).Returns(new byte[] { 1, 2, 3, 4 });

            var user = new User();

            user.Username = "******";
            user.Password = EncryptedString.Create("password", encryptionService.Object);

            // Act
            bool isValid = user.IsValid;

            // Assert
            Assert.IsTrue(isValid);
        }
        public void Should_throw_an_exception()
        {
            var service = new FakeEncryptionService(new EncryptedValue
            {
                EncryptedBase64Value = "EncryptedBase64Value",
                Base64Iv             = "Base64Iv"
            });

            var value = new EncryptedString
            {
                Value = "The real value"
            };

            // ReSharper disable once InvokeAsExtensionMethod
            var exception = Assert.Throws <Exception>(() => EncryptedStringConversions.DecryptValue(service, value, null));

            Assert.AreEqual("Encrypted property is missing encryption data", exception.Message);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// The post.
        /// </summary>
        /// <param name="item">
        /// The item.
        /// </param>
        /// <returns>
        /// The <see cref="HttpResponseMessage"/>.
        /// </returns>
        /// <remarks>
        /// POST users
        /// </remarks>
        public HttpResponseMessage Post(PostUser item)
        {
            var user = new User()
            {
                Username = item.Username,
                Password = EncryptedString.Create(item.Password, _encryptionService)
            };

            if (user.IsValid)
            {
                _userDataMapper.Insert(user);

                GetUser createdItem = _mapper.Map <User, GetUser>(user);
                return(CreatedHttpResponse(createdItem.ID, createdItem));
            }

            return(Request.CreateResponse(HttpStatusCode.BadRequest, user.ValidationErrors));
        }
Ejemplo n.º 25
0
 public Vehicle(Vehicle copy)
 {
     Index                  = copy.Index;
     ID                     = copy.ID;
     ParentID               = copy.ParentID;
     WheelType              = copy.WheelType;
     CarName                = copy.CarName;
     CarBrand               = copy.CarBrand;
     DamageLimit            = copy.DamageLimit;
     Flags                  = copy.Flags;
     BoostLength            = copy.BoostLength;
     VehicleRank            = copy.VehicleRank;
     BoostCapacity          = copy.BoostCapacity;
     DisplayStrength        = copy.DisplayStrength;
     padding0               = copy.padding0;
     AttribSysCollectionKey = copy.AttribSysCollectionKey;
     ExhaustName            = copy.ExhaustName;
     ExhaustID              = copy.ExhaustID;
     EngineID               = copy.EngineID;
     EngineName             = copy.EngineName;
     ClassUnlockStreamHash  = copy.ClassUnlockStreamHash;
     padding1               = copy.padding1;
     CarShutdownStreamID    = copy.CarShutdownStreamID;
     CarReleasedStreamID    = copy.CarReleasedStreamID;
     AIMusicHash            = copy.AIMusicHash;
     AIExhaustIndex         = copy.AIExhaustIndex;
     AIExhaustIndex2        = copy.AIExhaustIndex2;
     AIExhaustIndex3        = copy.AIExhaustIndex3;
     padding2               = copy.padding2;
     Unknown                = copy.Unknown;
     Category               = copy.Category;
     VehicleAndBoostType    = copy.VehicleAndBoostType;
     VehicleType            = copy.VehicleType;
     BoostType              = copy.BoostType;
     FinishType             = copy.FinishType;
     MaxSpeedNoBoost        = copy.MaxSpeedNoBoost;
     MaxSpeedBoost          = copy.MaxSpeedBoost;
     Color                  = copy.Color;
     ColorType              = copy.ColorType;
     DisplaySpeed           = copy.DisplaySpeed;
     DisplayBoost           = copy.DisplayBoost;
     padding3               = copy.padding3;
 }
        public void WriteTests()
        {
            Console.WriteLine("Cleartext: " + ClearText);

            using (var stream = EncryptingStream.Write(_mockEncryptedFile, _key))
                stream.Write(ClearText);

            var encrypted = new EncryptedString(_mockEncryptedFile.ToArray());

            Console.WriteLine("Encrypted: " + encrypted);

            using (var stream = DecryptingStream.Write(_mockFile, _key))
                stream.Write(encrypted);

            var decrypted = new Data(_mockFile).ToUtf8();

            Console.WriteLine("Decrypted: " + decrypted);
            Assert.AreEqual(ClearText, decrypted);
        }
        public void EncryptedStringOperatorTest()
        {
            EncryptedString nullString = null;
            var             empty      = new EncryptedString();
            var             encryptedA = Encrypt(ClearText);
            var             encryptedC = Encrypt(ClearText.ToLowerInvariant());

            var added         = encryptedA + encryptedC;
            var addedToString = added.ToString();

            Assert.AreEqual(added, new EncryptedString(addedToString));

            Assert.AreEqual(encryptedA, encryptedA + empty);
            Assert.AreEqual(encryptedA, empty + encryptedA);
            Assert.AreEqual(encryptedA, encryptedA + nullString);
            Assert.AreEqual(encryptedA, nullString + encryptedA);

            Assert.AreEqual(empty, nullString + nullString);
            Assert.AreEqual(empty, empty + empty);
        }
Ejemplo n.º 28
0
        public IActionResult PostEncrypt([FromBody] EncryptedString encryptedString)
        {
            LoginDto loginDto;

            try
            {
                string origintext = Encryptor.DecryptString_Aes(encryptedString.ciphertext, Encryptor.key);
                loginDto = JsonConvert.DeserializeObject <LoginDto>(origintext);
            }
            catch (Exception e)
            {
                return(BadRequest(e));
            }
            if (loginDto != null)
            {
                Login login = Mapper.Map <Login>(loginDto);
                if (_loginRepository.VerifyLogin(login))
                {
                    var logininfo = _loginRepository.GetLoginInfo(loginDto.UserName);
                    _unitOfWork.ChangeDatabase(logininfo.Company);
                    var userinfo = _userRepository.GetUserInfo(loginDto.UserName);
                    if (userinfo == null)
                    {
                        return(StatusCode(500, "用户信息缺失"));
                    }
                    var tokeninfo = Mapper.Map <Login, LoginCreateDto>(logininfo);
                    Mapper.Map(userinfo, tokeninfo);
                    try
                    {
                        return(new ObjectResult(TokenOperator.GenerateToken(tokeninfo)));
                    }
                    catch (Exception e)
                    {
                        return(StatusCode(500, "生成令牌时出错:" + e.Message));
                    }
                }
            }
            return(BadRequest());
        }
Ejemplo n.º 29
0
        public void Encrypt()
        {
            string value = "MyPieceOfText";

            Console.WriteLine("String is:" + value);

            EncryptedString encrypter = new EncryptedString(CatalogueRepository);

            Assert.IsFalse(encrypter.IsStringEncrypted(value));

            //should do pass through encryption
            encrypter.Value = value;
            Assert.AreNotEqual(value, encrypter.Value);
            Assert.AreEqual(value, encrypter.GetDecryptedValue());

            Console.WriteLine("Encrypted (stock) is:" + encrypter.Value);
            Console.WriteLine("Decrypted (stock) is:" + encrypter.GetDecryptedValue());

            var keyLocation = new PasswordEncryptionKeyLocation(CatalogueRepository);

            keyLocation.CreateNewKeyFile(Path.Combine(TestContext.CurrentContext.TestDirectory, "my.key"));
            var p = keyLocation.OpenKeyFile();

            CatalogueRepository.EncryptionManager.ClearAllInjections();

            var s         = CatalogueRepository.EncryptionManager.GetEncrypter();
            var exception = Assert.Throws <CryptographicException>(() => s.Decrypt(encrypter.Value));

            Assert.IsTrue(exception.Message.StartsWith("Could not decrypt an encrypted string, possibly you are trying to decrypt it after having changed the PrivateKey "));

            string encrypted = s.Encrypt(value);

            Console.WriteLine("Encrypted (with key) is:" + encrypted);
            Console.WriteLine("Decrypted (with key) is:" + s.Decrypt(encrypted));

            Assert.IsTrue(encrypter.IsStringEncrypted(encrypted));

            keyLocation.DeleteKey();
        }
Ejemplo n.º 30
0
        public void AddCommandArguments(string accessCode, string verifyCode)
        {
            EncryptedString avParameter = GetAVParameter(accessCode, verifyCode);

            this.CommandArgs = new object[] { avParameter };
        }