public ExecutionEngine(IScriptContainer container, ICrypto crypto, IScriptTable table = null, InteropService service = null)
 {
     this.ScriptContainer = container;
     this.Crypto          = crypto;
     this.table           = table;
     this.service         = service ?? new InteropService();
 }
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="session">The session.</param>
 /// <param name="database">The database.</param>
 /// <param name="crypto">The crypto.</param>
 /// <param name="sessionFactory">The session factory.</param>
 public UserRepository(ISession session, IDatabase database, ICrypto crypto, ISessionFactory sessionFactory)
 {
     _session = session;
     _database = database;
     _crypto = crypto;
     _sessionFactory = sessionFactory;
 }
Esempio n. 3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PublicKeyWrapper"/> class.
 /// May I have a new wrapper for my this public key?
 /// </summary>
 /// <param name="crypto">
 /// The crypto service used.
 /// </param>
 /// <param name="physicalSecret">
 /// A password that obscures the public key.
 /// </param>
 public PublicKeyWrapper(ICrypto crypto, string physicalSecret)
 {
     Contract.Requires(crypto != null);
     Contract.Requires(physicalSecret != null);
     _keyBytes = Bytes.Obfuscate(crypto,
                                 crypto.KeyPair.Public.ToBytes(), physicalSecret);
 }
Esempio n. 4
0
 /**
  * @param string appName
  * @param IRequest request
  * @param IURLGenerator urlGenerator
  * @param IUserManager userManager
  * @param Defaults defaults
  * @param IL10N l10n
  * @param IConfig config
  * @param ISecureRandom secureRandom
  * @param string defaultMailAddress
  * @param IManager encryptionManager
  * @param IMailer mailer
  * @param ITimeFactory timeFactory
  * @param ICrypto crypto
  */
 public LostController(string appName,
                       IRequest request,
                       IURLGenerator urlGenerator,
                       IUserManager userManager,
                       Defaults defaults,
                       IL10N l10n,
                       IConfig config,
                       ISecureRandom secureRandom,
                       string defaultMailAddress,
                       IManager encryptionManager,
                       IMailer mailer,
                       ITimeFactory timeFactory,
                       ICrypto crypto,
                       ILogger logger,
                       OC.Authentication.TwoFactorAuth.Manager twoFactorManager) : base(appName, request)
 {
     this.urlGenerator      = urlGenerator;
     this.userManager       = userManager;
     this.defaults          = defaults;
     this.l10n              = l10n;
     this.secureRandom      = secureRandom;
     this.from              = defaultMailAddress;
     this.encryptionManager = encryptionManager;
     this.config            = config;
     this.mailer            = mailer;
     this.timeFactory       = timeFactory;
     this.crypto            = crypto;
     this.logger            = logger;
     this.twoFactorManager  = twoFactorManager;
 }
Esempio n. 5
0
        public void FixtureSetup()
        {
            _crypto = TestResourceFactory.CreateCrypto();
            _bsonFormatter = TestResourceFactory.CreateBsonFormatter();

            new Random().NextBytes(_key);
        }
Esempio n. 6
0
        public CryptographerForm(ICrypto cryptographer)
        {
            InitializeComponent();

            cryptographerController = new Controller(cryptographer);
            _keyLength = new Random().Next(256);
        }
Esempio n. 7
0
 internal ExecutionContext(ExecutionEngine engine, byte[] script, int rvcount)
 {
     this.Script   = script;
     this.RVCount  = rvcount;
     this.OpReader = new BinaryReader(new MemoryStream(script, false));
     this.crypto   = engine.Crypto;
 }
Esempio n. 8
0
        /// <summary>
        /// Asynchronously decrypts the fields, specified by JSONPath, that are contained in the given json document string.
        /// </summary>
        /// <param name="crypto">
        /// The instance of <see cref="ICrypto"/> that ultimately responsible for performing decryption operations
        /// on field values.
        /// </param>
        /// <param name="jsonString">A string containing an json document.</param>
        /// <param name="jsonPathsToDecrypt">One or more JSONPaths of the fields to decrypt.</param>
        /// <param name="credentialName">
        /// The name of the credential to use for this encryption operation,
        /// or null to use the default credential.
        /// </param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
        /// <returns>A task that will contain the same json document, except with the specified fields decrypted.</returns>
        public static async Task <string> DecryptJsonAsync(this ICrypto crypto, string jsonString, IEnumerable <string> jsonPathsToDecrypt, string credentialName = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (crypto == null)
            {
                throw new ArgumentNullException(nameof(crypto));
            }
            if (jsonString == null)
            {
                throw new ArgumentNullException(nameof(jsonString));
            }
            if (jsonPathsToDecrypt == null)
            {
                throw new ArgumentNullException(nameof(jsonPathsToDecrypt));
            }

            var token = JToken.Parse(jsonString);

            var decryptor = new Lazy <IAsyncDecryptor>(() => crypto.AsAsync().GetAsyncDecryptor(credentialName));

            var anyPaths = false;

            foreach (var jsonPath in jsonPathsToDecrypt)
            {
                if (jsonPath == null)
                {
                    throw new ArgumentException($"{nameof(jsonPathsToDecrypt)} cannot have null items.", nameof(jsonPathsToDecrypt));
                }

                anyPaths = true;

                foreach (var match in token.SelectTokens(jsonPath).ToArray())
                {
                    var decryptedToken = JToken.Parse(await decryptor.Value.DecryptAsync(match.Value <string>(), cancellationToken));

                    if (ReferenceEquals(token, match))
                    {
                        token = decryptedToken;
                        continue;
                    }

                    switch (match.Parent)
                    {
                    case JProperty property:
                        property.Value = decryptedToken;
                        break;

                    case JArray array:
                        array[array.IndexOf(match)] = decryptedToken;
                        break;
                    }
                }
            }

            if (!anyPaths)
            {
                throw new ArgumentException($"{nameof(jsonPathsToDecrypt)} must have at least one item.", nameof(jsonPathsToDecrypt));
            }

            return(token.ToString(Formatting.None));
        }
        public async Task TestAddingSingleV2AsymmetricKeyWrap()
        {
            EncryptionParameters encryptionParameters = new EncryptionParameters(new V2Aes256CryptoFactory().CryptoId, new Passphrase("allan"));
            IAsymmetricPublicKey publicKey            = New <IAsymmetricFactory>().CreatePublicKey(Resources.PublicKey1);
            await encryptionParameters.AddAsync(new UserPublicKey[] { new UserPublicKey(EmailAddress.Parse("*****@*****.**"), publicKey), });

            V2DocumentHeaders documentHeaders = new V2DocumentHeaders(encryptionParameters, 1000);
            IEnumerable <V2AsymmetricKeyWrapHeaderBlock> wraps = documentHeaders.Headers.HeaderBlocks.OfType <V2AsymmetricKeyWrapHeaderBlock>();

            Assert.That(wraps.Count(), Is.EqualTo(1), "There should be one V2AsymmetricKeyWrapHeaderBlock found.");

            V2AsymmetricKeyWrapHeaderBlock block1 = wraps.First();

            ICryptoFactory cryptoFactory = Resolve.CryptoFactory.Create(encryptionParameters.CryptoId);

            IAsymmetricPrivateKey privateKey1 = New <IAsymmetricFactory>().CreatePrivateKey(Resources.PrivateKey1);

            block1.SetPrivateKey(cryptoFactory, privateKey1);
            ICrypto cryptoFromAsymmetricKey = block1.Crypto(0);

            V2KeyWrapHeaderBlock symmetricKeyWrap = documentHeaders.Headers.HeaderBlocks.OfType <V2KeyWrapHeaderBlock>().First();
            ICrypto cryptoFromSymmetricKey        = cryptoFactory.CreateCrypto(symmetricKeyWrap.MasterKey, symmetricKeyWrap.MasterIV, 0);

            Assert.That(cryptoFromAsymmetricKey.Key, Is.EqualTo(cryptoFromSymmetricKey.Key), "The keys from Asymmetric and Symmetric should be equal.");

            IAsymmetricPrivateKey privateKey2 = New <IAsymmetricFactory>().CreatePrivateKey(Resources.PrivateKey2);

            block1.SetPrivateKey(cryptoFactory, privateKey2);
            ICrypto cryptoFromAsymmetricKey1WithKey2 = block1.Crypto(0);

            Assert.That(cryptoFromAsymmetricKey1WithKey2, Is.Null, "There should be no valid key set and thus no ICrypto instance returned.");
        }
Esempio n. 10
0
 public ExampleDataWriter(
     ICrypto crypto,
     ApplicationOptions applicationOptions)
 {
     this.crypto             = crypto;
     this.applicationOptions = applicationOptions;
 }
Esempio n. 11
0
        /// <summary>
        /// Unwrap an AES Key Wrapped-key
        /// </summary>
        /// <param name="wrapped">The full wrapped data, the length of a key + 8 bytes</param>
        /// <returns>The unwrapped key data, or a zero-length array if the unwrap was unsuccessful due to wrong key</returns>
        public byte[] Unwrap(ICrypto crypto, byte[] wrapped)
        {
            if (wrapped == null)
            {
                throw new ArgumentNullException("wrapped");
            }

            if (crypto == null)
            {
                throw new ArgumentNullException("crypto");
            }
            if (wrapped.Length % (crypto.BlockLength / 2) != 0)
            {
                throw new InternalErrorException("The length of the wrapped data must a multiple of half the algorithm block size.");
            }
            if (wrapped.Length < 24)
            {
                throw new InternalErrorException("The length of the wrapped data must be large enough to accommodate at least a 128-bit key.");
            }

            using (IKeyWrapTransform decryptor = crypto.CreateKeyWrapTransform(_salt, KeyWrapDirection.Decrypt))
            {
                return(UnwrapInternal(wrapped, decryptor));
            }
        }
        public static ICrypto GetEncryptor(string method, string password)
        {
            if (string.IsNullOrEmpty(method))
            {
                // todo
                //method = IoCManager.Container.Resolve<IDefaultCrypto>().GetDefaultMethod();
            }

            method = method.ToLowerInvariant();
            bool ok = _registeredEncryptors.TryGetValue(method, out Type t);

            if (!ok)
            {
                t = _registeredEncryptors[DefaultCipher];
            }

            ConstructorInfo c = t?.GetConstructor(ConstructorTypes) ??
                                throw new TypeLoadException("can't load constructor");

            if (c == null)
            {
                throw new System.Exception("Invalid ctor");
            }
            ICrypto result = (ICrypto)c.Invoke(new object[] { method, password });

            return(result);
        }
Esempio n. 13
0
        public void PackMessageSucceeds()
        {
            ICrypto       crypto        = IndyDotNet.Crypto.Factory.GetCrypto(_wallet);
            PackedMessage packedMessage = crypto.PackMessage(_senderDid, _senderDid, MESSAGE_TO_SEND);

            Assert.IsNotNull(packedMessage, "crypto.PackMessage failed to return PackMessage instance");
        }
Esempio n. 14
0
        public void UnpackPackedMessageWithMultipleRecipientsSucceeds()
        {
            ICrypto     crypto     = IndyDotNet.Crypto.Factory.GetCrypto(_wallet);
            List <IDid> recipients = new List <IDid>();

            IdentitySeed seed = new IdentitySeed()
            {
                Seed = "00000000000000000000000000000My2"
            };

            recipients.Add(IndyDotNet.Did.Factory.CreateMyDid(_pool, _wallet, seed));

            seed = new IdentitySeed()
            {
                Seed = "00000000000000000000000000000My3"
            };
            recipients.Add(IndyDotNet.Did.Factory.CreateMyDid(_pool, _wallet, seed));


            PackedMessage   packedMessage   = crypto.PackMessage(recipients, _senderDid, MESSAGE_TO_SEND);
            UnpackedMessage unpackedMessage = crypto.UnpackMessage(packedMessage);

            Assert.IsNotNull(unpackedMessage, $"did not get back an unpacked message");
            Assert.AreEqual(MESSAGE_TO_SEND, unpackedMessage.Message, "unpacked message is not the same as what was sent");
        }
Esempio n. 15
0
        private async Task FileBranchProcessingAsync(ICrypto crypto, CancellationTokenSource token)
        {
            if (CheckBox1.Checked & !CheckBox2.Checked)//元のファイル消去の処理
            {
                await crypto.WriteStreamAsync
                    (textBox1.Text, TextBox1.Text, Path.GetDirectoryName(TextBox1.Text), token.Token);

                FileOperation.DeleteFile(TextBox1.Text);
            }
            else if (CheckBox1.Checked & CheckBox2.Checked)//元のファイルを消去する処理と出力変更の処理
            {
                await crypto.WriteStreamAsync
                    (textBox1.Text, TextBox1.Text, TextBox2.Text, token.Token);

                FileOperation.DeleteFile(TextBox1.Text);
            }
            else if (CheckBox2.Checked & !CheckBox1.Checked)//出力先変更の処理
            {
                await crypto.WriteStreamAsync
                    (textBox1.Text, TextBox1.Text, TextBox2.Text, token.Token);
            }
            else//デフォルトの処理
            {
                await crypto.WriteStreamAsync
                    (textBox1.Text, TextBox1.Text, Path.GetDirectoryName(TextBox1.Text), token.Token);
            }
        }
Esempio n. 16
0
    /// <summary>
    /// Encrypts the fields, specified by XPath, that are contained in the given xml document string.
    /// </summary>
    /// <param name="crypto">
    /// The instance of <see cref="ICrypto"/> that ultimately responsible for performing encryption operations
    /// on field values.
    /// </param>
    /// <param name="xmlString">A string containing an xml document.</param>
    /// <param name="xpathsToEncrypt">One or more XPaths of the fields to encrypt.</param>
    /// <param name="credentialName">
    /// The name of the credential to use for this encryption operation,
    /// or <c>null</c> to use the default credential.
    /// </param>
    /// <returns>The same xml document, except with the specified fields encrypted.</returns>
    public static string EncryptXml(this ICrypto crypto, string xmlString, IEnumerable <string> xpathsToEncrypt, string?credentialName = null)
    {
        if (crypto is null)
        {
            throw new ArgumentNullException(nameof(crypto));
        }
        if (xmlString is null)
        {
            throw new ArgumentNullException(nameof(xmlString));
        }
        if (xpathsToEncrypt is null)
        {
            throw new ArgumentNullException(nameof(xpathsToEncrypt));
        }

#if NET48
        var doc = new XmlDocument()
        {
            XmlResolver = null
        };
        var sreader = new StringReader(xmlString);
        using var reader = XmlReader.Create(sreader, new XmlReaderSettings()
        {
            XmlResolver = null
        });
        doc.Load(reader);
#else
        var doc = new XmlDocument();
        doc.LoadXml(xmlString);
#endif
        var navigator = doc.CreateNavigator() !;
        var encryptor = crypto.GetEncryptor(credentialName);
        var anyPaths  = false;

        foreach (var xpath in xpathsToEncrypt)
        {
            if (xpath is null)
            {
                throw new ArgumentException($"{nameof(xpathsToEncrypt)} cannot have null items.", nameof(xpathsToEncrypt));
            }

            anyPaths = true;

            foreach (XPathNavigator?match in navigator.Select(xpath))
            {
                // If there are any child elements, or the value contains escaped characters...
                if (match !.HasChildren && match.Value != match.InnerXml)
                {
                    // ...encrypt the InnerXml property.
                    var plaintext = match.InnerXml;

                    // SetValue throws if the navigator has any child elements.
                    while (match.MoveToFirstChild())
                    {
                        match.DeleteSelf();
                    }

                    match.SetValue(encryptor.Encrypt(plaintext));
                }
Esempio n. 17
0
        /// <summary>
        /// Encrypts the fields, specified by JSONPath, that are contained in the given json document string.
        /// </summary>
        /// <param name="crypto">
        /// The instance of <see cref="ICrypto"/> that ultimately responsible for performing encryption operations
        /// on field values.
        /// </param>
        /// <param name="jsonString">A string containing an json document.</param>
        /// <param name="jsonPathsToEncrypt">One or more JSONPaths of the fields to encrypt.</param>
        /// <param name="credentialName">
        /// The name of the credential to use for this encryption operation,
        /// or null to use the default credential.
        /// </param>
        /// <returns>The same json document, except with the specified fields encrypted.</returns>
        public static string EncryptJson(this ICrypto crypto, string jsonString, IEnumerable <string> jsonPathsToEncrypt, string credentialName = null)
        {
            if (crypto == null)
            {
                throw new ArgumentNullException(nameof(crypto));
            }
            if (jsonString == null)
            {
                throw new ArgumentNullException(nameof(jsonString));
            }
            if (jsonPathsToEncrypt == null)
            {
                throw new ArgumentNullException(nameof(jsonPathsToEncrypt));
            }

            var token = JToken.Parse(jsonString);

            var encryptor = new Lazy <IEncryptor>(() => crypto.GetEncryptor(credentialName));

            var anyPaths = false;

            foreach (var jsonPath in jsonPathsToEncrypt)
            {
                if (jsonPath == null)
                {
                    throw new ArgumentException($"{nameof(jsonPathsToEncrypt)} cannot have null items.", nameof(jsonPathsToEncrypt));
                }

                anyPaths = true;

                foreach (var match in token.SelectTokens(jsonPath).ToArray())
                {
                    var encryptedToken = JToken.Parse("\"" + encryptor.Value.Encrypt(match.ToString(Formatting.None)) + "\"");

                    if (ReferenceEquals(token, match))
                    {
                        return(encryptedToken.ToString(Formatting.None));
                    }

                    switch (match.Parent)
                    {
                    case JProperty property:
                        property.Value = encryptedToken;
                        break;

                    case JArray array:
                        array[array.IndexOf(match)] = encryptedToken;
                        break;
                    }
                }
            }

            if (!anyPaths)
            {
                throw new ArgumentException($"{nameof(jsonPathsToEncrypt)} must have at least one item.", nameof(jsonPathsToEncrypt));
            }

            return(token.ToString(Formatting.None));
        }
            public WrapIterator(Guid cryptoId)
            {
                ICryptoFactory factory = Resolve.CryptoFactory.Create(cryptoId);

                _dummyCrypto = factory.CreateCrypto(factory.CreateDerivedKey(new Passphrase("A dummy passphrase")).DerivedKey, null, 0);
                _dummySalt   = new Salt(_dummyCrypto.Key.Size);
                _dummyKey    = new SymmetricKey(_dummyCrypto.Key.Size);
            }
        /// <summary>
        /// Deserializes the specified XML to an object, decrypting any properties marked
        /// with the [Encrypt] attribute.
        /// </summary>
        /// <typeparam name="T">The type to deserialize into.</typeparam>
        /// <param name="crypto">The instance of <see cref="ICrypto"/> that will perform decryption operations.</param>
        /// <param name="xml">The XML to deserialize.</param>
        /// <param name="credentialName">
        /// The name of the credential to use for this encryption operation,
        /// or null to use the default credential.
        /// </param>
        /// <returns>The deserialized object.</returns>
        public static T FromXml <T>(this ICrypto crypto, string xml, string credentialName = null)
        {
            var serializer = new XmlSerializer <T>(x => x
                                                   .WithEncryptionMechanism(new CryptoEncryptionMechanism(crypto))
                                                   .WithEncryptKey(credentialName));

            return(serializer.Deserialize(xml));
        }
        /// <summary>
        /// Serializes the specified instance to XML, encrypting any properties marked
        /// with the [Encrypt] attribute.
        /// </summary>
        /// <typeparam name="T">The type of the instance</typeparam>
        /// <param name="crypto">The instance of <see cref="ICrypto"/> that will perform encryption operations.</param>
        /// <param name="instance">The instance to serialize.</param>
        /// <param name="credentialName">
        /// The name of the credential to use for this encryption operation,
        /// or null to use the default credential.
        /// </param>
        /// <returns>An XML document that represents the instance.</returns>
        public static string ToXml <T>(this ICrypto crypto, T instance, string credentialName = null)
        {
            var serializer = new XmlSerializer <T>(x => x
                                                   .WithEncryptionMechanism(new CryptoEncryptionMechanism(crypto))
                                                   .WithEncryptKey(credentialName));

            return(serializer.Serialize(instance));
        }
Esempio n. 21
0
        public void SetUp()
        {
            crypto        = A.Fake <ICrypto>();
            securityLogic = A.Fake <ISecurityLogic>();
            repository    = A.Fake <IRepository>();

            sut = new SecureStorage(crypto, securityLogic, repository);
        }
 public EncryptionService(ICrypto crypto)
 {
     _crypto          = crypto;
     _executionThread = new Thread(RunEncryptionPrompt)
     {
         IsBackground = true
     };
 }
Esempio n. 23
0
        /// <summary>
        /// 加密;
        /// </summary>
        /// <param name="cryptoTypeName">加密器类型名称</param>
        /// <returns>加密器</returns>
        public static ICrypto Create(string cryptoTypeName)
        {
            string  currentNamespace = MethodBase.GetCurrentMethod().DeclaringType.Namespace;   //获取当前方法的完整类型名称中的命名空间,从而获取当前的命名空间;
            Type    cryptoType       = Type.GetType(currentNamespace + "." + cryptoTypeName);   //根据命名空间与指定的类型名称,获取相应的类型;
            ICrypto crypto           = (ICrypto)Activator.CreateInstance(cryptoType);           //根据类型创建对象(即实例);

            return(crypto);
        }
Esempio n. 24
0
 public static ICrypto Instance()
 {
     using (var serviceScope = ServiceActivator.GetScope())
     {
         ICrypto crypto = serviceScope.ServiceProvider.GetRequiredService <ICrypto>();
         return(crypto);
     }
 }
Esempio n. 25
0
        public DataSeeder(AppDbContext context, ICrypto crypto)
        {
            _context = context;
            _crypto  = crypto;

            _assembly   = typeof(DataSeeder).GetTypeInfo().Assembly;
            _seederPath = string.Format("{0}.Seeders.csv", _assembly.GetName().Name);
        }
 public StravaAuthService(IOptions <StravaApiSettings> stravaApiSettings,
                          IOptions <StravaPersonalBestsSettings> stravaPersonalBestsSettings, ICrypto crypto, IStravaService stravaService)
 {
     _stravaApiSettings           = stravaApiSettings;
     _stravaPersonalBestsSettings = stravaPersonalBestsSettings;
     _crypto        = crypto;
     _stravaService = stravaService;
 }
Esempio n. 27
0
        /// <summary>
        /// Asynchronously decrypts the fields, specified by XPath, that are contained in the given xml document string.
        /// </summary>
        /// <param name="crypto">
        /// The instance of <see cref="ICrypto"/> that ultimately responsible for performing decryption operations
        /// on field values.
        /// </param>
        /// <param name="xmlString">A string containing an xml document.</param>
        /// <param name="xpathsToDecrypt">One or more XPaths of the fields to decrypt.</param>
        /// <param name="credentialName">
        /// The name of the credential to use for this encryption operation,
        /// or null to use the default credential.
        /// </param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
        /// <returns>A task that will contain the same xml document, except with the specified fields decrypted.</returns>
        public static async Task <string> DecryptXmlAsync(this ICrypto crypto, string xmlString, IEnumerable <string> xpathsToDecrypt, string credentialName = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (crypto == null)
            {
                throw new ArgumentNullException(nameof(crypto));
            }
            if (xmlString == null)
            {
                throw new ArgumentNullException(nameof(xmlString));
            }
            if (xpathsToDecrypt == null)
            {
                throw new ArgumentNullException(nameof(xpathsToDecrypt));
            }

            var doc = new XmlDocument();

            doc.LoadXml(xmlString);
            var navigator = doc.CreateNavigator();

            var decryptor = new Lazy <IAsyncDecryptor>(() => crypto.AsAsync().GetAsyncDecryptor(credentialName));

            var anyPaths = false;

            foreach (var xpath in xpathsToDecrypt)
            {
                if (xpath == null)
                {
                    throw new ArgumentException($"{nameof(xpathsToDecrypt)} cannot have null items.", nameof(xpathsToDecrypt));
                }

                anyPaths = true;

                foreach (XPathNavigator match in navigator.Select(xpath))
                {
                    var decrypted = await decryptor.Value.DecryptAsync(match.InnerXml, cancellationToken).ConfigureAwait(false);

                    if (decrypted != match.InnerXml)
                    {
                        try
                        {
                            match.InnerXml = decrypted;
                        }
                        catch
                        {
                            match.SetValue(decrypted);
                        }
                    }
                }
            }

            if (!anyPaths)
            {
                throw new ArgumentException($"{nameof(xpathsToDecrypt)} must have at least one item.", nameof(xpathsToDecrypt));
            }

            return(doc.OuterXml);
        }
Esempio n. 28
0
        /// <summary>
        /// 创建;
        /// </summary>
        /// <param name="number">学号/工号</param>
        /// <param name="password">密码</param>
        /// <param name="crypto">加密器</param>
        /// <returns>新用户</returns>
        public static User Create(string number, string password, ICrypto crypto)
        {
            User newUser = new User();

            newUser.Number   = number;
            newUser.Crypto   = crypto;
            newUser.Password = crypto.Encrypt(password);
            return(newUser);
        }
Esempio n. 29
0
        public void DecryptJsonAsyncThrowsWhenCryptoIsNull()
        {
            var json          = "{\"foo\":\"ImFiYyI=\",\"bar\":\"MTIz\",\"baz\":\"dHJ1ZQ==\",\"qux\":\"WzEsMiwzXQ==\",\"garply\":\"eyJncmF1bHQiOiJ4eXoifQ==\",\"fred\":\"bnVsbA==\"}";
            var keyIdentifier = new object();

            ICrypto crypto = null;

            Assert.That(async() => await crypto.DecryptJsonAsync(json, new[] { "$.foo", "$.bar", "$.baz", "$.qux", "$.garply", "$.fred" }, keyIdentifier), Throws.ArgumentNullException);
        }
Esempio n. 30
0
        public void EncryptJsonAsyncThrowsWhenCryptoIsNull()
        {
            var json          = "{\"foo\":\"abc\",\"bar\":123,\"baz\":true,\"qux\":[1,2,3],\"garply\":{\"grault\":\"xyz\"},\"fred\":null}";
            var keyIdentifier = new object();

            ICrypto crypto = null;

            Assert.That(async() => await crypto.EncryptJsonAsync(json, new[] { "$.foo", "$.bar", "$.baz", "$.qux", "$.garply", "$.fred" }, keyIdentifier), Throws.ArgumentNullException);
        }
Esempio n. 31
0
        public void DecryptXmlAsyncThrowsWhenCryptoIsNull()
        {
            var xml           = "<foo bar=\"MTIz\"><baz>NDU2</baz><baz>Nzg5</baz><qux>PGdhcnBseSBncmF1bHQ9ImFiYyIgLz4=</qux></foo>";
            var keyIdentifier = new object();

            ICrypto crypto = null;

            Assert.That(async() => await crypto.DecryptXmlAsync(xml, new[] { "/foo/@bar", "/foo/baz", "/foo/qux" }, keyIdentifier), Throws.ArgumentNullException);
        }
Esempio n. 32
0
        public void EncryptXmlAsyncThrowsWhenCryptoIsNull()
        {
            var xml           = "<foo bar=\"123\"><baz>456</baz><baz>789</baz><qux><garply grault=\"abc\" /></qux></foo>";
            var keyIdentifier = new object();

            ICrypto crypto = null;

            Assert.That(async() => await crypto.EncryptXmlAsync(xml, new[] { "/foo/@bar", "/foo/baz", "/foo/qux" }, keyIdentifier), Throws.ArgumentNullException);
        }
Esempio n. 33
0
        public EncryptionHelper(string pathToCertificate)
        {
            certificatePath = Path.Combine(pathToCertificate,certificateName);
            StorageAccount = CloudStorageAccount.Parse(connectionString);
            RsaHelper = new RsaHelper(certificatePath, certificateValue);
            KeyTableManager = new SymmetricKeyTableManager(certificateTable, StorageAccount);
            
            //Ensure the table is in place before initializing the cryptoStore
            CreateCertificateTableIfNotExists();
            //Create the master key if it doesn't exist
            CreateNewCryptoKeyIfNotExists();

            KeyCache = new SymmetricKeyCache(RsaHelper, KeyTableManager);
            AzureCrypto = new AzureCrypto(KeyCache);
        }
 public EncryptedMessageEnvelope(Encoding encoding, ICrypto crypto)
 {
     MessageEncoding = encoding;
     Crypto = crypto;
 }
Esempio n. 35
0
 public CryptoWeb(ICrypto crypto)
 {
     _crypto = crypto;
 }
Esempio n. 36
0
 /// <summary>
 /// Create default instance of symmetric cryptographer.
 /// </summary>
 static Crypto()
 {
     _provider = new CryptoSym();
 }
Esempio n. 37
0
       public void Method(AES abc)
       {
           objAes = abc;

       }
 public EncryptedMessageEnvelope(ICrypto crypto)
 {
     MessageEncoding = ASCIIEncoding.UTF8;
     Crypto = crypto;
 }
Esempio n. 39
0
 /// <summary>
 /// Initialize to new provider.
 /// </summary>
 /// <param name="service"></param>
 public static void Init(ICrypto service)
 {
     _provider = service;
 }
Esempio n. 40
0
 public SessionHttpModule(ICrypto cryptographicService)
 {
     _cryptographicService = cryptographicService;
 }