static (byte[] key, byte[] iv) GetMachineSecretKey() { var guid = GetMachineSecretKeyGuid(); var r = AESUtils.GetParameters(guid.ToByteArray()); return(r); }
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); }); }
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); }
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); } }
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); }
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); }
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); }); }
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); }
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); }
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); }
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); }
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)); }
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); }
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); }
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); } }
// 指定特定存档对象,将其替代原有对象(如果有的话),并从文件读取到这个对象 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))); } } }
// 存储索引到文件 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); } }
// 从文件读取索引 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)); } } } }
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); }
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); }); }
private string NewNextIV() { return(ConvertUtils.ByteArrayToBase64String(AESUtils.GenerateIV())); }
public virtual byte[]? DB(byte[]?value) => AESUtils.Decrypt_Nullable(settings.Aes, value);
public virtual string?D(byte[]?value) => AESUtils.DecryptToString_Nullable(settings.Aes, value);
public virtual byte[]? E(string?value) => AESUtils.EncryptToByteArray_Nullable(settings.Aes, value);
public void X86Decrypt() { TestDecrypt(AESUtils.CreateECB(_randomKey), _randombytes.Span); }
public GeneralLocalDataProtectionProvider(ILocalDataProtectionProvider.IProtectedData protectedData, ILocalDataProtectionProvider.IDataProtectionProvider dataProtectionProvider) : base(protectedData, dataProtectionProvider) { MachineSecretKey = AESUtils.GetParameters(Environment.MachineName); }
public void AESCBCEncrypt() { TestEncrypt(AESUtils.CreateCBC(_randomKey16, _randomIv16), _randombytes.Span); }
public void AESEncrypt() { TestEncrypt(AESUtils.CreateECB(_randomKey16), _randombytes.Span); }