Exemplo n.º 1
0
        static (byte[] key, byte[] iv) GetMachineSecretKey()
        {
            var guid = GetMachineSecretKeyGuid();
            var r    = AESUtils.GetParameters(guid.ToByteArray());

            return(r);
        }
Exemplo n.º 2
0
        public LocalDataProtectionProviderBase(
            IProtectedData protectedData,
            IDataProtectionProvider dataProtectionProvider)
        {
            this.protectedData          = protectedData;
            this.dataProtectionProvider = dataProtectionProvider;
            switch (DI.Platform)
            {
            case Platform.Windows:
                if (Environment.OSVersion.Version.Major >= 10)
                {
                    defaultELocalDataProtectionType = LocalDataProtectionType.Win10WithAesOFB;
                }
                else
                {
                    defaultELocalDataProtectionType = LocalDataProtectionType.ProtectedDataWithAesOFB;
                }
                break;

            case Platform.Linux:
                defaultELocalDataProtectionType = LocalDataProtectionType.AesOFB;
                break;

            default:
                defaultELocalDataProtectionType = LocalDataProtectionType.None;
                break;
            }
            _aes = new Lazy <Aes>(() =>
            {
                (byte[] key, byte[] iv) = MachineSecretKey;
                var r = AESUtils.Create(key, iv, CipherMode.CFB, PaddingMode.PKCS7);
                return(r);
            });
        }
Exemplo n.º 3
0
        protected override CefReturnValue OnBeforeResourceLoad(CefBrowser browser, CefFrame frame, CefRequest request, CefRequestCallback callback)
        {
            var sc = DI.Get <CloudServiceClientBase>();

            if (request.Url.StartsWith(sc.ApiBaseUrl, StringComparison.OrdinalIgnoreCase))
            {
                var conn_helper = DI.Get <IApiConnectionPlatformHelper>();
                request.SetHeaderByName(Headers.Request.AppVersion, sc.Settings.AppVersionStr, true);
                if (webView.IsSecurity)
                {
                    if (webView.Aes == null)
                    {
                        webView.Aes = AESUtils.Create();
                    }
                    var skey_bytes = webView.Aes.ToParamsByteArray();
                    var skey_str   = conn_helper.RSA.EncryptToString(skey_bytes);
                    request.SetHeaderByName(Headers.Request.SecurityKey, skey_str, true);
                }
                Func <Task <JWTEntity?> > getAuthTokenAsync = () => conn_helper.Auth.GetAuthTokenAsync().AsTask();
                var authToken       = getAuthTokenAsync.RunSync();
                var authHeaderValue = conn_helper.GetAuthenticationHeaderValue(authToken);
                if (authHeaderValue != null)
                {
                    var authHeaderValueStr = authHeaderValue.ToString();
                    request.SetHeaderByName("Authorization", authHeaderValueStr, true);
                }
            }
            var returnValue = base.OnBeforeResourceLoad(browser, frame, request, callback);

            return(returnValue);
        }
Exemplo n.º 4
0
        private byte[] ApplyProperDeciphering(byte[] receiveBuffer)
        {
            try
            {
                switch (State)
                {
                case (ProtocolState.WaitingSession):
                    List <string> targetFields = new List <string> {
                        "key", "iv"
                    };
                    XmlDocument document = ConvertUtils.ByteArrayToXMLDocument(receiveBuffer);
                    return(ConvertUtils.XmlDocumentToByteArray(RsaUtils.DecipherXmlDocument(document, GetDefaultKeyContainer(), targetFields)));

                case (ProtocolState.GotSession):
                    return(AESUtils.DecipherByteArray(receiveBuffer, server.GetSessionKey(), server.GetNextIV()));

                case (ProtocolState.GotSecret):
                    return(AESUtils.DecipherByteArray(receiveBuffer, server.GetSessionKey(), server.GetNextIV()));

                case (ProtocolState.FailOnce):
                    return(AESUtils.DecipherByteArray(receiveBuffer, server.GetSessionKey(), server.GetNextIV()));

                case (ProtocolState.FailTwice):
                    return(AESUtils.DecipherByteArray(receiveBuffer, server.GetSessionKey(), server.GetNextIV()));

                default:
                    return(null);
                }
            }
            catch (Exception)
            {
                return(null);
            }
        }
Exemplo n.º 5
0
        public void LocalEncrypt()
        {
            var value = DateTime.Now.ToString() + " 🔮🎮";

            var key_str = Environment.MachineName;

            (var key, var iv) = AESUtils.GetParameters(key_str);

            var aes_ofb = AESUtils.Create(mode: CipherMode.CFB);

            aes_ofb.Key = key;
            aes_ofb.IV  = iv;

            var data = AESUtils.EncryptToByteArray(aes_ofb, value);

            var value1 = AESUtils.DecryptToString(aes_ofb, data);

            Assert.IsTrue(value == value1);

            var aes_ofb_1 = AESUtils.Create(mode: CipherMode.CFB);

            aes_ofb_1.Key = key;
            aes_ofb_1.IV  = iv;

            var value2 = AESUtils.DecryptToString(aes_ofb, data);
            var value3 = AESUtils.DecryptToString(aes_ofb_1, data);

            Assert.IsTrue(value2 == value3);

            Assert.IsTrue(value1 == value3);
        }
Exemplo n.º 6
0
        public void MultipleEncrypt()
        {
            var aes_cbc_1 = AESUtils.Create();
            var aes_cfb_1 = AESUtils.Create(mode: CipherMode.CFB);
            var aes_cbc_2 = AESUtils.Create();

            var value = DateTime.Now.ToString() + " 🔮🎮";

            var bytes_1 = AESUtils.EncryptToByteArray(aes_cbc_1, value);
            var bytes_2 = AESUtils.Encrypt(aes_cfb_1, bytes_1);
            var bytes_3 = AESUtils.Encrypt(aes_cbc_2, bytes_2);
            var bytes_4 = bytes_3;

            var d_bytes_4 = bytes_4;

#pragma warning disable CA1416 // 验证平台兼容性
#if !ANDROID && !__ANDROID__ && !__MOBILE__
            if (DI.Platform == Platform.Windows)
            {
                bytes_4 = ProtectedData.Protect(bytes_3, null, DataProtectionScope.LocalMachine);

                d_bytes_4 = ProtectedData.Unprotect(bytes_4, null, DataProtectionScope.LocalMachine);
            }
#endif
#pragma warning restore CA1416 // 验证平台兼容性

            var d_bytes_3 = AESUtils.Decrypt(aes_cbc_2, d_bytes_4);
            var d_bytes_2 = AESUtils.Decrypt(aes_cfb_1, d_bytes_3);
            var d_value   = AESUtils.DecryptToString(aes_cbc_1, d_bytes_2);

            TestContext.WriteLine(d_value);
        }
Exemplo n.º 7
0
 public LocalDataProtectionProviderBase(
     IProtectedData protectedData,
     IDataProtectionProvider dataProtectionProvider)
 {
     this.protectedData          = protectedData;
     this.dataProtectionProvider = dataProtectionProvider;
     if (OperatingSystem2.IsWindows)
     {
         if (OperatingSystem2.IsWindows10AtLeast)
         {
             defaultELocalDataProtectionType = LocalDataProtectionType.Win10WithAesCFB;
         }
         else
         {
             defaultELocalDataProtectionType = LocalDataProtectionType.ProtectedDataWithAesCFB;
         }
     }
     else
     {
         defaultELocalDataProtectionType = LocalDataProtectionType.AesCFB;
     }
     _aes = new Lazy <Aes>(() =>
     {
         (var key, var iv) = MachineSecretKey;
         // https://github.com/dotnet/runtime/issues/42214#issuecomment-698495584
         // AES CFB in Windows 7 catch Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: Unknown error (0xc10000bb)
         // AES CFB in Android catch CryptographicException: Bad PKCS7 padding. Invalid length
         var mode = OperatingSystem2.IsAndroid ? CipherMode.CBC : CipherMode.CFB;
         var r    = AESUtils.Create(key, iv, mode, PaddingMode.PKCS7);
         return(r);
     });
 }
Exemplo n.º 8
0
        public void Test4(string keyHex, string ivHex, string hex1, string hex2)
        {
            var key = keyHex.FromHex();
            var iv  = ivHex.FromHex();

            Test4(new AESCBCCrypto(key, iv), hex1, hex2);
            Test4(new CBCBlockMode(AESUtils.CreateECB(key), iv), hex1, hex2);
        }
Exemplo n.º 9
0
    public void Test(string keyHex, string nonceHex, string associatedDataHex, string tagHex, string plainHex, string cipherHex)
    {
        var key = keyHex.FromHex();

        Test(new DefaultAesGcmCrypto(key), nonceHex, associatedDataHex, tagHex, plainHex, cipherHex);
        Test(new BcAesGcmCrypto(key), nonceHex, associatedDataHex, tagHex, plainHex, cipherHex);
        Test(new GcmCryptoMode(AESUtils.CreateECB(key)), nonceHex, associatedDataHex, tagHex, plainHex, cipherHex);
        Test(AEADCryptoCreate.AesGcm(key), nonceHex, associatedDataHex, tagHex, plainHex, cipherHex);
    }
Exemplo n.º 10
0
 public void Setup()
 {
     byte[] random = RandomNumberGenerator.GetBytes(4);
     _randombytes   = random.ToArray();
     _randombytes2  = random.ToArray();
     _randombytes3  = random.ToArray();
     _randombytes4  = random.ToArray();
     _randombytes16 = RandomNumberGenerator.GetBytes(16);
     _aes           = AESUtils.CreateECB(_randombytes16);
 }
Exemplo n.º 11
0
        public void Setup()
        {
            var random = Utils.RandBytes(4);

            _randombytes   = random.ToArray();
            _randombytes2  = random.ToArray();
            _randombytes3  = random.ToArray();
            _randombytes4  = random.ToArray();
            _randombytes16 = Utils.RandBytes(16).ToArray();
            _aes           = AESUtils.CreateECB(_randombytes16);
        }
Exemplo n.º 12
0
        private byte[] GenerateThenSignAndCipherXmlDocument(Dictionary <string, string> xmlElementsDictionary, string key, string iv)
        {
            XmlDocument document = XmlUtils.FormXmlDocument(xmlElementsDictionary);

            if (State.Equals(ProtocolState.WaitingSession))
            {
                return(ConvertUtils.XmlDocumentToByteArray(document));
            }

            document = XmlUtils.SignXmlWithSymmetricKey(document, key);
            return(AESUtils.CipherXmlDocument(document, key, iv));
        }
Exemplo n.º 13
0
 public static void SaveFrom(ISaveData instance)
 {
     if (instance != null)
     {
         if (!Directory.Exists(_folder))
         {
             Directory.CreateDirectory(_folder);
         }
         var fileName = AddOrChangeFileName(instance.SaveTag());
         File.WriteAllBytes(GetPath(fileName), AESUtils.AESEncrypt(instance.SaveAsJson()));
     }
 }
        /// <summary>
        /// 开始第三方快速登录、注册、绑定
        /// </summary>
        /// <param name="vm"></param>
        /// <param name="channel"></param>
        /// <returns></returns>
        public static async Task StartAsync(WindowViewModel vm, FastLoginChannel channel, bool isBind)
        {
            var app = IApplication.Instance;

            StartServer(app);
            var conn_helper = DI.Get <IApiConnectionPlatformHelper>();
            var apiBaseUrl  = ICloudServiceClient.Instance.ApiBaseUrl;

#if DEBUG
            if (UseLoopbackTest)
            {
                apiBaseUrl = "https://127.0.0.1:28110";
            }
#endif

            ThirdPartyLoginHelper.isBind = isBind;
            ThirdPartyLoginHelper.vm     = vm;
            Disposable.Create(() =>
            {
                if (vm == ThirdPartyLoginHelper.vm)
                {
                    ThirdPartyLoginHelper.vm = null;
                }
            }).AddTo(vm);
            if (tempAes == null)
            {
                tempAes = AESUtils.Create();                  // 每次创建新的之前的会失效
            }
            var skey_bytes           = tempAes.ToParamsByteArray();
            var skey_str             = conn_helper.RSA.EncryptToString(skey_bytes);
            var csc                  = DI.Get <CloudServiceClientBase>();
            var padding              = RSAUtils.DefaultPadding;
            var access_token         = string.Empty;
            var access_token_expires = string.Empty;
            if (isBind)
            {
                var authToken = await conn_helper.Auth.GetAuthTokenAsync();

                var authHeaderValue = conn_helper.GetAuthenticationHeaderValue(authToken);
                if (authHeaderValue != null)
                {
                    var authHeaderValueStr = authHeaderValue.ToString();
                    access_token = tempAes.Encrypt(authHeaderValueStr);
                    var now = DateTime.UtcNow;
                    access_token_expires = tempAes.Encrypt(now.ToString(DateTimeFormat.RFC1123));
                }
            }
            // &version={version}
            //var version = csc.Settings.AppVersionStr;
            var ver = _ThisAssembly.Version.Base64UrlEncode();
            var url = $"{apiBaseUrl}/ExternalLoginDetection/{(int)channel}?port={port}&sKey={skey_str}&sKeyPadding={padding.OaepHashAlgorithm}&ver={ver}&isBind={isBind}&access_token_expires={access_token_expires}&access_token={access_token}";
            await Browser2.OpenAsync(url);
        }
Exemplo n.º 15
0
        static byte[] E___(Aes[] aes, byte[] value)
        {
            if (value.Length == 0)
            {
                return(value);
            }
            var len    = aes.Length - 1;
            var data_e = AESUtils.Encrypt(aes[len], value);
            var data_r = BitConverter.GetBytes(len).Concat(data_e).ToArray();

            return(data_r);
        }
Exemplo n.º 16
0
 static void ClearFilesByIndexFile(string path)
 {
     if (File.Exists(path))
     {
         var json = AESUtils.AESDecrypt(File.ReadAllBytes(path));
         var data = JsonMapper.ToObject(json);
         foreach (var key in data.Keys)
         {
             File.Delete(GetPath(data.TryGetString(key)));
         }
         File.Delete(path);
     }
 }
Exemplo n.º 17
0
        // 指定特定存档对象,将其替代原有对象(如果有的话),并从文件读取到这个对象
        public static void LoadTo(ISaveData instance)
        {
            var saveTag = instance.SaveTag();

            if (_fileNames.ContainsKey(saveTag))
            {
                var path = GetPath(_fileNames[saveTag]);
                if (File.Exists(path))
                {
                    instance.LoadFromJson(AESUtils.AESDecrypt(File.ReadAllBytes(path)));
                }
            }
        }
Exemplo n.º 18
0
        // 存储索引到文件
        static void SaveFileNames()
        {
            var      indexFilePath = GetPath(_saveFile);
            JsonData data          = new JsonData();

            foreach (var pair in _fileNames)
            {
                data[pair.Key] = pair.Value;
            }
            var json = data.ToJson();

            File.WriteAllBytes(indexFilePath, AESUtils.AESEncrypt(json));
        }
        public static void SsAes128(string password, ReadOnlySpan <byte> source, Span <byte> destination)
        {
            var buffer = ArrayPool <byte> .Shared.Rent(16);

            try
            {
                buffer.AsSpan(0, 16).SsDeriveKey(password);
                using var aes = AESUtils.CreateECB(buffer);
                aes.Encrypt(source, destination);
            }
            finally
            {
                ArrayPool <byte> .Shared.Return(buffer);
            }
        }
Exemplo n.º 20
0
        // 从文件读取索引
        static void LoadFileNames()
        {
            var indexFilePath = GetPath(_saveFile);

            if (File.Exists(indexFilePath))
            {
                byte[] bytes = File.ReadAllBytes(indexFilePath);
                if (bytes.Length > 0)
                {
                    var json = AESUtils.AESDecrypt(bytes);
                    var data = JsonMapper.ToObject(json);
                    foreach (var key in data.Keys)
                    {
                        _fileNames.Add(key, data.TryGetString(key));
                    }
                }
            }
        }
Exemplo n.º 21
0
        protected override CefReturnValue OnBeforeResourceLoad(CefBrowser browser, CefFrame frame, CefRequest request, CefRequestCallback callback)
        {
            var sc = DI.Get <CloudServiceClientBase>();

            if (request.Url.StartsWith(sc.ApiBaseUrl, StringComparison.OrdinalIgnoreCase))
            {
                request.SetHeaderByName(Headers.Request.AppVersion, sc.Settings.AppVersionStr, true);
                if (webView.IsSecurity)
                {
                    if (webView.Aes == null)
                    {
                        webView.Aes = AESUtils.Create();
                    }
                    var skey_bytes  = webView.Aes.ToParamsByteArray();
                    var conn_helper = DI.Get <IApiConnectionPlatformHelper>();
                    var skey_str    = conn_helper.RSA.EncryptToString(skey_bytes);
                    request.SetHeaderByName(Headers.Request.SecurityKey, skey_str, true);
                }
            }
            var returnValue = base.OnBeforeResourceLoad(browser, frame, request, callback);

            return(returnValue);
        }
Exemplo n.º 22
0
        public LocalDataProtectionProviderBase(
            IProtectedData protectedData,
            IDataProtectionProvider dataProtectionProvider)
        {
            this.protectedData          = protectedData;
            this.dataProtectionProvider = dataProtectionProvider;
            switch (DI.Platform)
            {
            case Platform.Windows:
                if (Environment.OSVersion.Version.Major >= 10)
                {
                    defaultELocalDataProtectionType = LocalDataProtectionType.Win10WithAesOFB;
                }
                else
                {
                    defaultELocalDataProtectionType = LocalDataProtectionType.ProtectedDataWithAesOFB;
                }
                break;

            case Platform.Linux:
                defaultELocalDataProtectionType = LocalDataProtectionType.AesOFB;
                break;

            default:
                defaultELocalDataProtectionType = LocalDataProtectionType.None;
                break;
            }
            _aes = new Lazy <Aes>(() =>
            {
                (byte[] key, byte[] iv) = MachineSecretKey;
                // https://github.com/dotnet/runtime/issues/42214#issuecomment-698495584
                // AES CFB in Windows 7 catch Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: Unknown error (0xc10000bb)
                var r = AESUtils.Create(key, iv, CipherMode.CFB, PaddingMode.PKCS7);
                return(r);
            });
        }
Exemplo n.º 23
0
 private string NewNextIV()
 {
     return(ConvertUtils.ByteArrayToBase64String(AESUtils.GenerateIV()));
 }
Exemplo n.º 24
0
 public virtual byte[]? DB(byte[]?value) => AESUtils.Decrypt_Nullable(settings.Aes, value);
Exemplo n.º 25
0
 public virtual string?D(byte[]?value) => AESUtils.DecryptToString_Nullable(settings.Aes, value);
Exemplo n.º 26
0
 public virtual byte[]? E(string?value) => AESUtils.EncryptToByteArray_Nullable(settings.Aes, value);
Exemplo n.º 27
0
 public void X86Decrypt()
 {
     TestDecrypt(AESUtils.CreateECB(_randomKey), _randombytes.Span);
 }
Exemplo n.º 28
0
 public GeneralLocalDataProtectionProvider(ILocalDataProtectionProvider.IProtectedData protectedData, ILocalDataProtectionProvider.IDataProtectionProvider dataProtectionProvider) : base(protectedData, dataProtectionProvider)
 {
     MachineSecretKey = AESUtils.GetParameters(Environment.MachineName);
 }
Exemplo n.º 29
0
 public void AESCBCEncrypt()
 {
     TestEncrypt(AESUtils.CreateCBC(_randomKey16, _randomIv16), _randombytes.Span);
 }
Exemplo n.º 30
0
 public void AESEncrypt()
 {
     TestEncrypt(AESUtils.CreateECB(_randomKey16), _randombytes.Span);
 }