diff --git a/JNFrame/App.config b/JNFrame/App.config
new file mode 100644
index 00000000..bc95b853
--- /dev/null
+++ b/JNFrame/App.config
@@ -0,0 +1,50 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/JNFrame/Assembly-CSharp-Editor.csproj b/JNFrame/Assembly-CSharp-Editor.csproj
new file mode 100644
index 00000000..4eb2afca
--- /dev/null
+++ b/JNFrame/Assembly-CSharp-Editor.csproj
@@ -0,0 +1,63 @@
+
+
+
+ 9.0
+ <_TargetFrameworkDirectories>non_empty_path_generated_by_unity.rider.package
+ <_FullFrameworkReferenceAssemblyPaths>non_empty_path_generated_by_unity.rider.package
+ true
+
+
+ Debug
+ AnyCPU
+ 10.0.20506
+ 2.0
+
+ {520fb43a-8c94-8ecf-d51a-d5407030f9ec}
+ {E097FAD1-6243-4DAD-9C02-E9B9EFC3FFC1};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
+ Library
+ Properties
+ Assembly-CSharp-Editor
+ v4.7.1
+ 512
+ .
+
+
+ true
+ full
+ false
+ Temp\Bin\Debug\Unity.Rider.Editor\
+ UNITY_EDITOR
+ prompt
+ 4
+ 0169,0649
+ False
+ False
+
+
+ true
+ true
+ false
+ false
+ false
+
+
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.CoreModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.dll
+
+
+
+
+
diff --git a/JNFrame/Assembly-CSharp-firstpass.csproj b/JNFrame/Assembly-CSharp-firstpass.csproj
new file mode 100644
index 00000000..d6e233d1
--- /dev/null
+++ b/JNFrame/Assembly-CSharp-firstpass.csproj
@@ -0,0 +1,2531 @@
+
+
+
+ 9.0
+ <_TargetFrameworkDirectories>non_empty_path_generated_by_unity.rider.package
+ <_FullFrameworkReferenceAssemblyPaths>non_empty_path_generated_by_unity.rider.package
+ true
+
+
+ Debug
+ AnyCPU
+ 10.0.20506
+ 2.0
+
+ {e5544f0c-cd3e-f7be-dc52-046b131df43d}
+ {E097FAD1-6243-4DAD-9C02-E9B9EFC3FFC1};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
+ Library
+ Properties
+ Assembly-CSharp-firstpass
+ v4.7.1
+ 512
+ .
+
+
+ true
+ full
+ false
+ Temp\Bin\Debug\Assembly-CSharp-firstpass\
+ UNITY_2021_3_27;UNITY_2021_3;UNITY_2021;UNITY_5_3_OR_NEWER;UNITY_5_4_OR_NEWER;UNITY_5_5_OR_NEWER;UNITY_5_6_OR_NEWER;UNITY_2017_1_OR_NEWER;UNITY_2017_2_OR_NEWER;UNITY_2017_3_OR_NEWER;UNITY_2017_4_OR_NEWER;UNITY_2018_1_OR_NEWER;UNITY_2018_2_OR_NEWER;UNITY_2018_3_OR_NEWER;UNITY_2018_4_OR_NEWER;UNITY_2019_1_OR_NEWER;UNITY_2019_2_OR_NEWER;UNITY_2019_3_OR_NEWER;UNITY_2019_4_OR_NEWER;UNITY_2020_1_OR_NEWER;UNITY_2020_2_OR_NEWER;UNITY_2020_3_OR_NEWER;UNITY_2021_1_OR_NEWER;UNITY_2021_2_OR_NEWER;UNITY_2021_3_OR_NEWER;PLATFORM_ARCH_64;UNITY_64;UNITY_INCLUDE_TESTS;ENABLE_AR;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_EVENT_QUEUE;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_TEXTURE_STREAMING;ENABLE_VIRTUALTEXTURING;ENABLE_UNET;ENABLE_LZMA;ENABLE_UNITYEVENTS;ENABLE_VR;ENABLE_WEBCAM;ENABLE_UNITYWEBREQUEST;ENABLE_WWW;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_SERVICES_USE_WEBREQUEST;ENABLE_CLOUD_SERVICES_CRASH_REPORTING;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_HUB_LICENSE;ENABLE_WEBSOCKET_CLIENT;ENABLE_DIRECTOR_AUDIO;ENABLE_DIRECTOR_TEXTURE;ENABLE_MANAGED_JOBS;ENABLE_MANAGED_TRANSFORM_JOBS;ENABLE_MANAGED_ANIMATION_JOBS;ENABLE_MANAGED_AUDIO_JOBS;ENABLE_MANAGED_UNITYTLS;INCLUDE_DYNAMIC_GI;ENABLE_SCRIPTING_GC_WBARRIERS;PLATFORM_SUPPORTS_MONO;RENDER_SOFTWARE_CURSOR;ENABLE_VIDEO;ENABLE_ACCELERATOR_CLIENT_DEBUGGING;PLATFORM_STANDALONE;TEXTCORE_1_0_OR_NEWER;PLATFORM_STANDALONE_WIN;UNITY_STANDALONE_WIN;UNITY_STANDALONE;UNITY_UGP_API;ENABLE_RUNTIME_GI;ENABLE_MOVIES;ENABLE_NETWORK;ENABLE_NVIDIA;ENABLE_CRUNCH_TEXTURE_COMPRESSION;ENABLE_UNITY_GAME_SERVICES_ANALYTICS_SUPPORT;ENABLE_OUT_OF_PROCESS_CRASH_HANDLER;ENABLE_CLUSTER_SYNC;ENABLE_CLUSTERINPUT;PLATFORM_UPDATES_TIME_OUTSIDE_OF_PLAYER_LOOP;GFXDEVICE_WAITFOREVENT_MESSAGEPUMP;ENABLE_WEBSOCKET_HOST;ENABLE_MONO;NET_STANDARD_2_0;NET_STANDARD;NET_STANDARD_2_1;NETSTANDARD;NETSTANDARD2_1;ENABLE_PROFILER;DEBUG;TRACE;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_IG;UNITY_EDITOR_64;UNITY_EDITOR_WIN;ENABLE_UNITY_COLLECTIONS_CHECKS;ENABLE_BURST_AOT;UNITY_TEAM_LICENSE;ENABLE_CUSTOM_RENDER_TEXTURE;ENABLE_DIRECTOR;ENABLE_LOCALIZATION;ENABLE_SPRITES;ENABLE_TERRAIN;ENABLE_TILEMAP;ENABLE_TIMELINE;ENABLE_LEGACY_INPUT_MANAGER;TEXTCORE_FONT_ENGINE_1_5_OR_NEWER;CSHARP_7_OR_LATER;CSHARP_7_3_OR_NEWER
+ prompt
+ 4
+ 0169,0649
+ False
+ False
+
+
+ true
+ true
+ false
+ false
+ false
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.AIModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.ARModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.AccessibilityModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.AndroidJNIModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.AnimationModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.AssetBundleModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.AudioModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.ClothModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.ClusterInputModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.ClusterRendererModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.CoreModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.CrashReportingModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.DSPGraphModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.DirectorModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.GIModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.GameCenterModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.GridModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.HotReloadModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.IMGUIModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.ImageConversionModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.InputModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.InputLegacyModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.JSONSerializeModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.LocalizationModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.ParticleSystemModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.PerformanceReportingModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.PhysicsModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.Physics2DModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.ProfilerModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.RuntimeInitializeOnLoadManagerInitializerModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.ScreenCaptureModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.SharedInternalsModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.SpriteMaskModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.SpriteShapeModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.StreamingModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.SubstanceModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.SubsystemsModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.TLSModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.TerrainModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.TerrainPhysicsModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.TextCoreFontEngineModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.TextCoreTextEngineModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.TextRenderingModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.TilemapModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UIModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UIElementsModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UIElementsNativeModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UIWidgetsModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UNETModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UmbraModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UnityAnalyticsModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UnityAnalyticsCommonModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UnityConnectModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UnityCurlModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UnityTestProtocolModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UnityWebRequestModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UnityWebRequestAssetBundleModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UnityWebRequestAudioModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UnityWebRequestTextureModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UnityWebRequestWWWModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.VFXModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.VRModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.VehiclesModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.VideoModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.VirtualTexturingModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.WindModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.XRModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.CoreModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.DeviceSimulatorModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.DiagnosticsModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.GraphViewModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.PackageManagerUIModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.QuickSearchModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.SceneTemplateModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.TextCoreFontEngineModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.TextCoreTextEngineModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.UIBuilderModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.UIElementsModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.UIElementsSamplesModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.UIServiceModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.UnityConnectModule.dll
+
+
+ D:\myproject\unity\JNFrame\Assets\Packages\Google.Protobuf.3.15.8\lib\netstandard2.0\Google.Protobuf.dll
+
+
+ D:\myproject\unity\JNFrame\Assets\Packages\System.Runtime.CompilerServices.Unsafe.4.5.2\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll
+
+
+ D:\myproject\unity\JNFrame\Library\PackageCache\com.unity.visualscripting@1.8.0\Runtime\VisualScripting.Flow\Dependencies\NCalc\Unity.VisualScripting.Antlr3.Runtime.dll
+
+
+ D:\myproject\unity\JNFrame\Library\PackageCache\com.unity.testtools.codecoverage@1.2.3\lib\ReportGenerator\ReportGeneratorMerged.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\ref\2.1.0\netstandard.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\Microsoft.Win32.Primitives.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.AppContext.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Buffers.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Collections.Concurrent.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Collections.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Collections.NonGeneric.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Collections.Specialized.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.ComponentModel.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.ComponentModel.EventBasedAsync.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.ComponentModel.Primitives.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.ComponentModel.TypeConverter.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Console.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Data.Common.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Diagnostics.Contracts.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Diagnostics.Debug.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Diagnostics.FileVersionInfo.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Diagnostics.Process.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Diagnostics.StackTrace.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Diagnostics.TextWriterTraceListener.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Diagnostics.Tools.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Diagnostics.TraceSource.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Diagnostics.Tracing.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Drawing.Primitives.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Dynamic.Runtime.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Globalization.Calendars.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Globalization.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Globalization.Extensions.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.IO.Compression.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.IO.Compression.ZipFile.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.IO.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.IO.FileSystem.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.IO.FileSystem.DriveInfo.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.IO.FileSystem.Primitives.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.IO.FileSystem.Watcher.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.IO.IsolatedStorage.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.IO.MemoryMappedFiles.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.IO.Pipes.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.IO.UnmanagedMemoryStream.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Linq.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Linq.Expressions.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Linq.Parallel.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Linq.Queryable.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Memory.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Net.Http.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Net.NameResolution.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Net.NetworkInformation.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Net.Ping.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Net.Primitives.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Net.Requests.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Net.Security.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Net.Sockets.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Net.WebHeaderCollection.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Net.WebSockets.Client.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Net.WebSockets.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Numerics.Vectors.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.ObjectModel.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Reflection.DispatchProxy.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Reflection.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Reflection.Emit.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Reflection.Emit.ILGeneration.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Reflection.Emit.Lightweight.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Reflection.Extensions.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Reflection.Primitives.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Resources.Reader.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Resources.ResourceManager.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Resources.Writer.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Runtime.CompilerServices.VisualC.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Runtime.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Runtime.Extensions.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Runtime.Handles.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Runtime.InteropServices.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Runtime.InteropServices.RuntimeInformation.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Runtime.Numerics.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Runtime.Serialization.Formatters.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Runtime.Serialization.Json.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Runtime.Serialization.Primitives.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Runtime.Serialization.Xml.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Security.Claims.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Security.Cryptography.Algorithms.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Security.Cryptography.Csp.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Security.Cryptography.Encoding.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Security.Cryptography.Primitives.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Security.Cryptography.X509Certificates.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Security.Principal.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Security.SecureString.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Text.Encoding.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Text.Encoding.Extensions.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Text.RegularExpressions.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Threading.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Threading.Overlapped.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Threading.Tasks.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Threading.Tasks.Extensions.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Threading.Tasks.Parallel.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Threading.Thread.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Threading.ThreadPool.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Threading.Timer.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.ValueTuple.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Xml.ReaderWriter.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Xml.XDocument.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Xml.XmlDocument.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Xml.XmlSerializer.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Xml.XPath.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Xml.XPath.XDocument.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\Extensions\2.0.0\System.Runtime.InteropServices.WindowsRuntime.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\mscorlib.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.ComponentModel.Composition.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.Core.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.Data.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.Drawing.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.IO.Compression.FileSystem.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.Net.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.Numerics.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.Runtime.Serialization.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.ServiceModel.Web.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.Transactions.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.Web.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.Windows.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.Xml.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.Xml.Linq.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.Xml.Serialization.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.VisualScripting.Flow.Editor.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.VSCode.Editor.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.VisualScripting.Shared.Editor.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.TextMeshPro.Editor.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.VisualStudio.Editor.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.Performance.Profile-Analyzer.Editor.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.TestTools.CodeCoverage.Editor.OpenCover.Model.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.Timeline.Editor.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.Timeline.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.VisualScripting.Core.Editor.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.TextMeshPro.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.VisualScripting.State.Editor.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.VisualScripting.SettingsProvider.Editor.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.TestTools.CodeCoverage.Editor.OpenCover.Mono.Reflection.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.VisualScripting.Flow.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\UnityEditor.UI.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.PlasticSCM.Editor.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.Rider.Editor.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.TestTools.CodeCoverage.Editor.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\UnityEngine.UI.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.VisualScripting.State.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.VisualScripting.Core.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.EditorCoroutines.Editor.dll
+
+
+
+
+ {4b964c85-7c9d-2d07-a2e0-8595262e4e96}
+ UniTask.TextMeshPro
+
+
+ {99c4c7d2-ca96-1038-95e0-77e225df2b06}
+ UniTask.DOTween
+
+
+ {39f5acb9-cdbb-9f48-497c-14159a0afd38}
+ UniTask
+
+
+ {6d8bd378-3e5b-6997-5e5e-288243f0f72b}
+ UniTask.Addressables
+
+
+ {7f60f694-1f75-f2f0-5fde-36ccb7fd82d1}
+ UniTask.Linq
+
+
+
+
+
diff --git a/JNFrame/Assembly-CSharp.csproj b/JNFrame/Assembly-CSharp.csproj
new file mode 100644
index 00000000..a389f015
--- /dev/null
+++ b/JNFrame/Assembly-CSharp.csproj
@@ -0,0 +1,801 @@
+
+
+
+ 9.0
+ <_TargetFrameworkDirectories>non_empty_path_generated_by_unity.rider.package
+ <_FullFrameworkReferenceAssemblyPaths>non_empty_path_generated_by_unity.rider.package
+ true
+
+
+ Debug
+ AnyCPU
+ 10.0.20506
+ 2.0
+
+ {3ca4410c-c33b-25ce-55bc-3a432b9830ed}
+ {E097FAD1-6243-4DAD-9C02-E9B9EFC3FFC1};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
+ Library
+ Properties
+ Assembly-CSharp
+ v4.7.1
+ 512
+ .
+
+
+ true
+ full
+ false
+ Temp\Bin\Debug\Assembly-CSharp\
+ UNITY_2021_3_27;UNITY_2021_3;UNITY_2021;UNITY_5_3_OR_NEWER;UNITY_5_4_OR_NEWER;UNITY_5_5_OR_NEWER;UNITY_5_6_OR_NEWER;UNITY_2017_1_OR_NEWER;UNITY_2017_2_OR_NEWER;UNITY_2017_3_OR_NEWER;UNITY_2017_4_OR_NEWER;UNITY_2018_1_OR_NEWER;UNITY_2018_2_OR_NEWER;UNITY_2018_3_OR_NEWER;UNITY_2018_4_OR_NEWER;UNITY_2019_1_OR_NEWER;UNITY_2019_2_OR_NEWER;UNITY_2019_3_OR_NEWER;UNITY_2019_4_OR_NEWER;UNITY_2020_1_OR_NEWER;UNITY_2020_2_OR_NEWER;UNITY_2020_3_OR_NEWER;UNITY_2021_1_OR_NEWER;UNITY_2021_2_OR_NEWER;UNITY_2021_3_OR_NEWER;PLATFORM_ARCH_64;UNITY_64;UNITY_INCLUDE_TESTS;ENABLE_AR;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_EVENT_QUEUE;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_TEXTURE_STREAMING;ENABLE_VIRTUALTEXTURING;ENABLE_UNET;ENABLE_LZMA;ENABLE_UNITYEVENTS;ENABLE_VR;ENABLE_WEBCAM;ENABLE_UNITYWEBREQUEST;ENABLE_WWW;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_SERVICES_USE_WEBREQUEST;ENABLE_CLOUD_SERVICES_CRASH_REPORTING;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_HUB_LICENSE;ENABLE_WEBSOCKET_CLIENT;ENABLE_DIRECTOR_AUDIO;ENABLE_DIRECTOR_TEXTURE;ENABLE_MANAGED_JOBS;ENABLE_MANAGED_TRANSFORM_JOBS;ENABLE_MANAGED_ANIMATION_JOBS;ENABLE_MANAGED_AUDIO_JOBS;ENABLE_MANAGED_UNITYTLS;INCLUDE_DYNAMIC_GI;ENABLE_SCRIPTING_GC_WBARRIERS;PLATFORM_SUPPORTS_MONO;RENDER_SOFTWARE_CURSOR;ENABLE_VIDEO;ENABLE_ACCELERATOR_CLIENT_DEBUGGING;PLATFORM_STANDALONE;TEXTCORE_1_0_OR_NEWER;PLATFORM_STANDALONE_WIN;UNITY_STANDALONE_WIN;UNITY_STANDALONE;UNITY_UGP_API;ENABLE_RUNTIME_GI;ENABLE_MOVIES;ENABLE_NETWORK;ENABLE_NVIDIA;ENABLE_CRUNCH_TEXTURE_COMPRESSION;ENABLE_UNITY_GAME_SERVICES_ANALYTICS_SUPPORT;ENABLE_OUT_OF_PROCESS_CRASH_HANDLER;ENABLE_CLUSTER_SYNC;ENABLE_CLUSTERINPUT;PLATFORM_UPDATES_TIME_OUTSIDE_OF_PLAYER_LOOP;GFXDEVICE_WAITFOREVENT_MESSAGEPUMP;ENABLE_WEBSOCKET_HOST;ENABLE_MONO;NET_STANDARD_2_0;NET_STANDARD;NET_STANDARD_2_1;NETSTANDARD;NETSTANDARD2_1;ENABLE_PROFILER;DEBUG;TRACE;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_IG;UNITY_EDITOR_64;UNITY_EDITOR_WIN;ENABLE_UNITY_COLLECTIONS_CHECKS;ENABLE_BURST_AOT;UNITY_TEAM_LICENSE;ENABLE_CUSTOM_RENDER_TEXTURE;ENABLE_DIRECTOR;ENABLE_LOCALIZATION;ENABLE_SPRITES;ENABLE_TERRAIN;ENABLE_TILEMAP;ENABLE_TIMELINE;ENABLE_LEGACY_INPUT_MANAGER;TEXTCORE_FONT_ENGINE_1_5_OR_NEWER;CSHARP_7_OR_LATER;CSHARP_7_3_OR_NEWER
+ prompt
+ 4
+ 0169,0649
+ False
+ False
+
+
+ true
+ true
+ false
+ false
+ false
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.AIModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.ARModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.AccessibilityModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.AndroidJNIModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.AnimationModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.AssetBundleModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.AudioModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.ClothModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.ClusterInputModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.ClusterRendererModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.CoreModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.CrashReportingModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.DSPGraphModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.DirectorModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.GIModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.GameCenterModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.GridModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.HotReloadModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.IMGUIModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.ImageConversionModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.InputModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.InputLegacyModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.JSONSerializeModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.LocalizationModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.ParticleSystemModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.PerformanceReportingModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.PhysicsModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.Physics2DModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.ProfilerModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.RuntimeInitializeOnLoadManagerInitializerModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.ScreenCaptureModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.SharedInternalsModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.SpriteMaskModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.SpriteShapeModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.StreamingModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.SubstanceModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.SubsystemsModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.TLSModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.TerrainModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.TerrainPhysicsModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.TextCoreFontEngineModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.TextCoreTextEngineModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.TextRenderingModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.TilemapModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UIModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UIElementsModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UIElementsNativeModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UIWidgetsModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UNETModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UmbraModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UnityAnalyticsModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UnityAnalyticsCommonModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UnityConnectModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UnityCurlModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UnityTestProtocolModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UnityWebRequestModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UnityWebRequestAssetBundleModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UnityWebRequestAudioModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UnityWebRequestTextureModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.UnityWebRequestWWWModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.VFXModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.VRModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.VehiclesModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.VideoModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.VirtualTexturingModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.WindModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEngine.XRModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.CoreModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.DeviceSimulatorModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.DiagnosticsModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.GraphViewModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.PackageManagerUIModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.QuickSearchModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.SceneTemplateModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.TextCoreFontEngineModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.TextCoreTextEngineModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.UIBuilderModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.UIElementsModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.UIElementsSamplesModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.UIServiceModule.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\Managed\UnityEngine\UnityEditor.UnityConnectModule.dll
+
+
+ D:\myproject\unity\JNFrame\Assets\Packages\Google.Protobuf.3.15.8\lib\netstandard2.0\Google.Protobuf.dll
+
+
+ D:\myproject\unity\JNFrame\Assets\Packages\System.Runtime.CompilerServices.Unsafe.4.5.2\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll
+
+
+ D:\myproject\unity\JNFrame\Library\PackageCache\com.unity.visualscripting@1.8.0\Runtime\VisualScripting.Flow\Dependencies\NCalc\Unity.VisualScripting.Antlr3.Runtime.dll
+
+
+ D:\myproject\unity\JNFrame\Library\PackageCache\com.unity.testtools.codecoverage@1.2.3\lib\ReportGenerator\ReportGeneratorMerged.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\ref\2.1.0\netstandard.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\Microsoft.Win32.Primitives.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.AppContext.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Buffers.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Collections.Concurrent.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Collections.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Collections.NonGeneric.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Collections.Specialized.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.ComponentModel.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.ComponentModel.EventBasedAsync.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.ComponentModel.Primitives.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.ComponentModel.TypeConverter.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Console.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Data.Common.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Diagnostics.Contracts.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Diagnostics.Debug.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Diagnostics.FileVersionInfo.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Diagnostics.Process.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Diagnostics.StackTrace.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Diagnostics.TextWriterTraceListener.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Diagnostics.Tools.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Diagnostics.TraceSource.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Diagnostics.Tracing.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Drawing.Primitives.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Dynamic.Runtime.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Globalization.Calendars.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Globalization.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Globalization.Extensions.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.IO.Compression.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.IO.Compression.ZipFile.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.IO.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.IO.FileSystem.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.IO.FileSystem.DriveInfo.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.IO.FileSystem.Primitives.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.IO.FileSystem.Watcher.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.IO.IsolatedStorage.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.IO.MemoryMappedFiles.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.IO.Pipes.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.IO.UnmanagedMemoryStream.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Linq.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Linq.Expressions.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Linq.Parallel.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Linq.Queryable.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Memory.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Net.Http.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Net.NameResolution.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Net.NetworkInformation.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Net.Ping.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Net.Primitives.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Net.Requests.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Net.Security.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Net.Sockets.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Net.WebHeaderCollection.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Net.WebSockets.Client.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Net.WebSockets.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Numerics.Vectors.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.ObjectModel.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Reflection.DispatchProxy.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Reflection.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Reflection.Emit.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Reflection.Emit.ILGeneration.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Reflection.Emit.Lightweight.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Reflection.Extensions.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Reflection.Primitives.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Resources.Reader.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Resources.ResourceManager.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Resources.Writer.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Runtime.CompilerServices.VisualC.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Runtime.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Runtime.Extensions.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Runtime.Handles.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Runtime.InteropServices.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Runtime.InteropServices.RuntimeInformation.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Runtime.Numerics.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Runtime.Serialization.Formatters.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Runtime.Serialization.Json.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Runtime.Serialization.Primitives.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Runtime.Serialization.Xml.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Security.Claims.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Security.Cryptography.Algorithms.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Security.Cryptography.Csp.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Security.Cryptography.Encoding.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Security.Cryptography.Primitives.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Security.Cryptography.X509Certificates.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Security.Principal.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Security.SecureString.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Text.Encoding.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Text.Encoding.Extensions.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Text.RegularExpressions.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Threading.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Threading.Overlapped.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Threading.Tasks.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Threading.Tasks.Extensions.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Threading.Tasks.Parallel.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Threading.Thread.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Threading.ThreadPool.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Threading.Timer.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.ValueTuple.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Xml.ReaderWriter.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Xml.XDocument.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Xml.XmlDocument.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Xml.XmlSerializer.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Xml.XPath.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Xml.XPath.XDocument.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\Extensions\2.0.0\System.Runtime.InteropServices.WindowsRuntime.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\mscorlib.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.ComponentModel.Composition.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.Core.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.Data.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.Drawing.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.IO.Compression.FileSystem.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.Net.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.Numerics.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.Runtime.Serialization.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.ServiceModel.Web.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.Transactions.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.Web.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.Windows.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.Xml.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.Xml.Linq.dll
+
+
+ D:\Unity\2021.3.27f1c2\Editor\Data\NetStandard\compat\2.1.0\shims\netfx\System.Xml.Serialization.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.VisualScripting.Flow.Editor.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.VSCode.Editor.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.VisualScripting.Shared.Editor.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.TextMeshPro.Editor.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.VisualStudio.Editor.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.Performance.Profile-Analyzer.Editor.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.TestTools.CodeCoverage.Editor.OpenCover.Model.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.Timeline.Editor.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.Timeline.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.VisualScripting.Core.Editor.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.TextMeshPro.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.VisualScripting.State.Editor.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.VisualScripting.SettingsProvider.Editor.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.TestTools.CodeCoverage.Editor.OpenCover.Mono.Reflection.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.VisualScripting.Flow.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\UnityEditor.UI.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.PlasticSCM.Editor.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.Rider.Editor.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.TestTools.CodeCoverage.Editor.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\UnityEngine.UI.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.VisualScripting.State.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.VisualScripting.Core.dll
+
+
+ D:\myproject\unity\JNFrame\Library\ScriptAssemblies\Unity.EditorCoroutines.Editor.dll
+
+
+
+
+ {e5544f0c-cd3e-f7be-dc52-046b131df43d}
+ Assembly-CSharp-firstpass
+
+
+ {4b964c85-7c9d-2d07-a2e0-8595262e4e96}
+ UniTask.TextMeshPro
+
+
+ {99c4c7d2-ca96-1038-95e0-77e225df2b06}
+ UniTask.DOTween
+
+
+ {39f5acb9-cdbb-9f48-497c-14159a0afd38}
+ UniTask
+
+
+ {6d8bd378-3e5b-6997-5e5e-288243f0f72b}
+ UniTask.Addressables
+
+
+ {7f60f694-1f75-f2f0-5fde-36ccb7fd82d1}
+ UniTask.Linq
+
+
+
+
+
diff --git a/JNFrame/Assets/NuGet.config b/JNFrame/Assets/NuGet.config
new file mode 100644
index 00000000..82fb1c87
--- /dev/null
+++ b/JNFrame/Assets/NuGet.config
@@ -0,0 +1,16 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/JNFrame/Assets/NuGet.config.meta b/JNFrame/Assets/NuGet.config.meta
new file mode 100644
index 00000000..d327f1b6
--- /dev/null
+++ b/JNFrame/Assets/NuGet.config.meta
@@ -0,0 +1,23 @@
+fileFormatVersion: 2
+guid: ce5d180ef4cefe947b2cd08b26c11bc1
+labels:
+- NuGetForUnity
+PluginImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ iconMap: {}
+ executionOrder: {}
+ defineConstraints: []
+ isPreloaded: 0
+ isOverridable: 0
+ isExplicitlyReferenced: 0
+ validateReferences: 1
+ platformData:
+ - first:
+ Any:
+ second:
+ enabled: 1
+ settings: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/NuGet.meta b/JNFrame/Assets/NuGet.meta
new file mode 100644
index 00000000..27037b55
--- /dev/null
+++ b/JNFrame/Assets/NuGet.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: dbf134857daf7df428aa31cdd055514f
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/NuGet/Editor.meta b/JNFrame/Assets/NuGet/Editor.meta
new file mode 100644
index 00000000..3b6fd6bc
--- /dev/null
+++ b/JNFrame/Assets/NuGet/Editor.meta
@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: b3fad56c531ac5a4db190a745f589a8e
+folderAsset: yes
+timeCreated: 1510280304
+licenseType: Free
+DefaultImporter:
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/NuGet/Editor/NugetForUnity.dll b/JNFrame/Assets/NuGet/Editor/NugetForUnity.dll
new file mode 100644
index 00000000..d0103424
Binary files /dev/null and b/JNFrame/Assets/NuGet/Editor/NugetForUnity.dll differ
diff --git a/JNFrame/Assets/NuGet/Editor/NugetForUnity.dll.meta b/JNFrame/Assets/NuGet/Editor/NugetForUnity.dll.meta
new file mode 100644
index 00000000..833aac7d
--- /dev/null
+++ b/JNFrame/Assets/NuGet/Editor/NugetForUnity.dll.meta
@@ -0,0 +1,33 @@
+fileFormatVersion: 2
+guid: 8dc1be91775c4bb469f6b74cef450eaa
+PluginImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ iconMap: {}
+ executionOrder: {}
+ defineConstraints: []
+ isPreloaded: 0
+ isOverridable: 0
+ isExplicitlyReferenced: 0
+ validateReferences: 1
+ platformData:
+ - first:
+ Any:
+ second:
+ enabled: 0
+ settings: {}
+ - first:
+ Editor: Editor
+ second:
+ enabled: 1
+ settings:
+ DefaultValueInitialized: true
+ - first:
+ Windows Store Apps: WindowsStoreApps
+ second:
+ enabled: 0
+ settings:
+ CPU: AnyCPU
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/NuGet/LICENSE b/JNFrame/Assets/NuGet/LICENSE
new file mode 100644
index 00000000..e5e72104
--- /dev/null
+++ b/JNFrame/Assets/NuGet/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2018 Patrick McCarthy
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/JNFrame/Assets/NuGet/LICENSE.meta b/JNFrame/Assets/NuGet/LICENSE.meta
new file mode 100644
index 00000000..9de0ac8d
--- /dev/null
+++ b/JNFrame/Assets/NuGet/LICENSE.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 1d9014b99ad06af428514a5902d29ff3
+timeCreated: 1573248500
+licenseType: Pro
+DefaultImporter:
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/NuGet/README.pdf b/JNFrame/Assets/NuGet/README.pdf
new file mode 100644
index 00000000..e67f9fa5
Binary files /dev/null and b/JNFrame/Assets/NuGet/README.pdf differ
diff --git a/JNFrame/Assets/NuGet/README.pdf.meta b/JNFrame/Assets/NuGet/README.pdf.meta
new file mode 100644
index 00000000..e95001a0
--- /dev/null
+++ b/JNFrame/Assets/NuGet/README.pdf.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 83c5d2001771f15429a88d67e81366d6
+timeCreated: 1517876157
+licenseType: Free
+DefaultImporter:
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/NuGet/Resources.meta b/JNFrame/Assets/NuGet/Resources.meta
new file mode 100644
index 00000000..49a5e3b4
--- /dev/null
+++ b/JNFrame/Assets/NuGet/Resources.meta
@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: 1738075a39a390447b7a620ca6962142
+folderAsset: yes
+timeCreated: 1510280362
+licenseType: Free
+DefaultImporter:
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/NuGet/Resources/defaultIcon.png b/JNFrame/Assets/NuGet/Resources/defaultIcon.png
new file mode 100644
index 00000000..a16cc198
Binary files /dev/null and b/JNFrame/Assets/NuGet/Resources/defaultIcon.png differ
diff --git a/JNFrame/Assets/NuGet/Resources/defaultIcon.png.meta b/JNFrame/Assets/NuGet/Resources/defaultIcon.png.meta
new file mode 100644
index 00000000..d23111ab
--- /dev/null
+++ b/JNFrame/Assets/NuGet/Resources/defaultIcon.png.meta
@@ -0,0 +1,88 @@
+fileFormatVersion: 2
+guid: eec19781926cd2248b7c9abfde8db555
+TextureImporter:
+ fileIDToRecycleName: {}
+ externalObjects: {}
+ serializedVersion: 9
+ mipmaps:
+ mipMapMode: 0
+ enableMipMap: 1
+ sRGBTexture: 1
+ linearTexture: 0
+ fadeOut: 0
+ borderMipMap: 0
+ mipMapsPreserveCoverage: 0
+ alphaTestReferenceValue: 0.5
+ mipMapFadeDistanceStart: 1
+ mipMapFadeDistanceEnd: 3
+ bumpmap:
+ convertToNormalMap: 0
+ externalNormalMap: 0
+ heightScale: 0.25
+ normalMapFilter: 0
+ isReadable: 0
+ streamingMipmaps: 0
+ streamingMipmapsPriority: 0
+ grayScaleToAlpha: 0
+ generateCubemap: 6
+ cubemapConvolution: 0
+ seamlessCubemap: 0
+ textureFormat: -1
+ maxTextureSize: 2048
+ textureSettings:
+ serializedVersion: 2
+ filterMode: -1
+ aniso: -1
+ mipBias: -100
+ wrapU: 1
+ wrapV: 1
+ wrapW: 1
+ nPOTScale: 0
+ lightmap: 0
+ compressionQuality: 50
+ spriteMode: 1
+ spriteExtrude: 1
+ spriteMeshType: 1
+ alignment: 0
+ spritePivot: {x: 0.5, y: 0.5}
+ spritePixelsToUnits: 100
+ spriteBorder: {x: 0, y: 0, z: 0, w: 0}
+ spriteGenerateFallbackPhysicsShape: 1
+ alphaUsage: 1
+ alphaIsTransparency: 1
+ spriteTessellationDetail: -1
+ textureType: 8
+ textureShape: 1
+ singleChannelComponent: 0
+ maxTextureSizeSet: 0
+ compressionQualitySet: 0
+ textureFormatSet: 0
+ platformSettings:
+ - serializedVersion: 2
+ buildTarget: DefaultTexturePlatform
+ maxTextureSize: 2048
+ resizeAlgorithm: 0
+ textureFormat: -1
+ textureCompression: 1
+ compressionQuality: 50
+ crunchedCompression: 0
+ allowsAlphaSplitting: 0
+ overridden: 0
+ androidETC2FallbackOverride: 0
+ spriteSheet:
+ serializedVersion: 2
+ sprites: []
+ outline: []
+ physicsShape: []
+ bones: []
+ spriteID: 215e43cda847e6d44af8b40376eeed8a
+ vertices: []
+ indices:
+ edges: []
+ weights: []
+ spritePackingTag:
+ pSDRemoveMatte: 0
+ pSDShowRemoveMatteOption: 0
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Packages.meta b/JNFrame/Assets/Packages.meta
new file mode 100644
index 00000000..d1263c8c
--- /dev/null
+++ b/JNFrame/Assets/Packages.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: f5ddeed46214a6549ad76520afa1f466
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Packages/Google.Protobuf.3.15.8.meta b/JNFrame/Assets/Packages/Google.Protobuf.3.15.8.meta
new file mode 100644
index 00000000..2145a8cd
--- /dev/null
+++ b/JNFrame/Assets/Packages/Google.Protobuf.3.15.8.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 4e6b7d62fcb9ab846a7e98ef1d3266dd
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Packages/Google.Protobuf.3.15.8/.signature.p7s b/JNFrame/Assets/Packages/Google.Protobuf.3.15.8/.signature.p7s
new file mode 100644
index 00000000..9022ef6e
Binary files /dev/null and b/JNFrame/Assets/Packages/Google.Protobuf.3.15.8/.signature.p7s differ
diff --git a/JNFrame/Assets/Packages/Google.Protobuf.3.15.8/Google.Protobuf.nuspec b/JNFrame/Assets/Packages/Google.Protobuf.3.15.8/Google.Protobuf.nuspec
new file mode 100644
index 00000000..377b49cb
--- /dev/null
+++ b/JNFrame/Assets/Packages/Google.Protobuf.3.15.8/Google.Protobuf.nuspec
@@ -0,0 +1,30 @@
+
+
+
+ Google.Protobuf
+ 3.15.8
+ Google Inc.
+ Google Inc.
+ false
+ https://github.com/protocolbuffers/protobuf/blob/master/LICENSE
+ https://github.com/protocolbuffers/protobuf
+ C# runtime library for Protocol Buffers - Google's data interchange format.
+ C# proto3 support
+ Copyright 2015, Google Inc.
+ Protocol Buffers Binary Serialization Format Google proto proto3
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/JNFrame/Assets/Packages/Google.Protobuf.3.15.8/Google.Protobuf.nuspec.meta b/JNFrame/Assets/Packages/Google.Protobuf.3.15.8/Google.Protobuf.nuspec.meta
new file mode 100644
index 00000000..0584abef
--- /dev/null
+++ b/JNFrame/Assets/Packages/Google.Protobuf.3.15.8/Google.Protobuf.nuspec.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: f251e4c06aaa618458c77025c57ea05c
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Packages/Google.Protobuf.3.15.8/lib.meta b/JNFrame/Assets/Packages/Google.Protobuf.3.15.8/lib.meta
new file mode 100644
index 00000000..2dc9d18d
--- /dev/null
+++ b/JNFrame/Assets/Packages/Google.Protobuf.3.15.8/lib.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: c3a32c58ec0f04f43b8a83eaaee0fad6
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Packages/Google.Protobuf.3.15.8/lib/netstandard2.0.meta b/JNFrame/Assets/Packages/Google.Protobuf.3.15.8/lib/netstandard2.0.meta
new file mode 100644
index 00000000..be639f5e
--- /dev/null
+++ b/JNFrame/Assets/Packages/Google.Protobuf.3.15.8/lib/netstandard2.0.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 0d6bbee8d0e4206419e6a1f3d21c49d6
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Packages/Google.Protobuf.3.15.8/lib/netstandard2.0/Google.Protobuf.dll b/JNFrame/Assets/Packages/Google.Protobuf.3.15.8/lib/netstandard2.0/Google.Protobuf.dll
new file mode 100644
index 00000000..207a7fca
Binary files /dev/null and b/JNFrame/Assets/Packages/Google.Protobuf.3.15.8/lib/netstandard2.0/Google.Protobuf.dll differ
diff --git a/JNFrame/Assets/Packages/Google.Protobuf.3.15.8/lib/netstandard2.0/Google.Protobuf.dll.meta b/JNFrame/Assets/Packages/Google.Protobuf.3.15.8/lib/netstandard2.0/Google.Protobuf.dll.meta
new file mode 100644
index 00000000..26f8086d
--- /dev/null
+++ b/JNFrame/Assets/Packages/Google.Protobuf.3.15.8/lib/netstandard2.0/Google.Protobuf.dll.meta
@@ -0,0 +1,23 @@
+fileFormatVersion: 2
+guid: 57fb929cf6fba524c850bd783eeff4a7
+labels:
+- NuGetForUnity
+PluginImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ iconMap: {}
+ executionOrder: {}
+ defineConstraints: []
+ isPreloaded: 0
+ isOverridable: 0
+ isExplicitlyReferenced: 0
+ validateReferences: 1
+ platformData:
+ - first:
+ Any:
+ second:
+ enabled: 1
+ settings: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Packages/Google.Protobuf.3.15.8/lib/netstandard2.0/Google.Protobuf.xml b/JNFrame/Assets/Packages/Google.Protobuf.3.15.8/lib/netstandard2.0/Google.Protobuf.xml
new file mode 100644
index 00000000..ba87ed87
--- /dev/null
+++ b/JNFrame/Assets/Packages/Google.Protobuf.3.15.8/lib/netstandard2.0/Google.Protobuf.xml
@@ -0,0 +1,10097 @@
+
+
+
+ Google.Protobuf
+
+
+
+
+ Provides a utility routine to copy small arrays much more quickly than Buffer.BlockCopy
+
+
+
+
+ The threshold above which you should use Buffer.BlockCopy rather than ByteArray.Copy
+
+
+
+
+ Determines which copy routine to use based on the number of bytes to be copied.
+
+
+
+
+ Reverses the order of bytes in the array
+
+
+
+
+ Immutable array of bytes.
+
+
+
+
+ Internal use only. Ensure that the provided memory is not mutated and belongs to this instance.
+
+
+
+
+ Internal use only. Ensure that the provided memory is not mutated and belongs to this instance.
+ This method encapsulates converting array to memory. Reduces need for SecuritySafeCritical
+ in .NET Framework.
+
+
+
+
+ Constructs a new ByteString from the given memory. The memory is
+ *not* copied, and must not be modified after this constructor is called.
+
+
+
+
+ Returns an empty ByteString.
+
+
+
+
+ Returns the length of this ByteString in bytes.
+
+
+
+
+ Returns true if this byte string is empty, false otherwise.
+
+
+
+
+ Provides read-only access to the data of this .
+ No data is copied so this is the most efficient way of accessing.
+
+
+
+
+ Provides read-only access to the data of this .
+ No data is copied so this is the most efficient way of accessing.
+
+
+
+
+ Converts this into a byte array.
+
+ The data is copied - changes to the returned array will not be reflected in this ByteString.
+ A byte array with the same data as this ByteString.
+
+
+
+ Converts this into a standard base64 representation.
+
+ A base64 representation of this ByteString.
+
+
+
+ Constructs a from the Base64 Encoded String.
+
+
+
+
+ Constructs a from data in the given stream, synchronously.
+
+ If successful, will be read completely, from the position
+ at the start of the call.
+ The stream to copy into a ByteString.
+ A ByteString with content read from the given stream.
+
+
+
+ Constructs a from data in the given stream, asynchronously.
+
+ If successful, will be read completely, from the position
+ at the start of the call.
+ The stream to copy into a ByteString.
+ The cancellation token to use when reading from the stream, if any.
+ A ByteString with content read from the given stream.
+
+
+
+ Constructs a from the given array. The contents
+ are copied, so further modifications to the array will not
+ be reflected in the returned ByteString.
+ This method can also be invoked in ByteString.CopyFrom(0xaa, 0xbb, ...) form
+ which is primarily useful for testing.
+
+
+
+
+ Constructs a from a portion of a byte array.
+
+
+
+
+ Constructs a from a read only span. The contents
+ are copied, so further modifications to the span will not
+ be reflected in the returned .
+
+
+
+
+ Creates a new by encoding the specified text with
+ the given encoding.
+
+
+
+
+ Creates a new by encoding the specified text in UTF-8.
+
+
+
+
+ Returns the byte at the given index.
+
+
+
+
+ Converts this into a string by applying the given encoding.
+
+
+ This method should only be used to convert binary data which was the result of encoding
+ text with the given encoding.
+
+ The encoding to use to decode the binary data into text.
+ The result of decoding the binary data with the given decoding.
+
+
+
+ Converts this into a string by applying the UTF-8 encoding.
+
+
+ This method should only be used to convert binary data which was the result of encoding
+ text with UTF-8.
+
+ The result of decoding the binary data with the given decoding.
+
+
+
+ Returns an iterator over the bytes in this .
+
+ An iterator over the bytes in this object.
+
+
+
+ Returns an iterator over the bytes in this .
+
+ An iterator over the bytes in this object.
+
+
+
+ Creates a CodedInputStream from this ByteString's data.
+
+
+
+
+ Compares two byte strings for equality.
+
+ The first byte string to compare.
+ The second byte string to compare.
+ true if the byte strings are equal; false otherwise.
+
+
+
+ Compares two byte strings for inequality.
+
+ The first byte string to compare.
+ The second byte string to compare.
+ false if the byte strings are equal; true otherwise.
+
+
+
+ Compares this byte string with another object.
+
+ The object to compare this with.
+ true if refers to an equal ; false otherwise.
+
+
+
+ Returns a hash code for this object. Two equal byte strings
+ will return the same hash code.
+
+ A hash code for this object.
+
+
+
+ Compares this byte string with another.
+
+ The to compare this with.
+ true if refers to an equal byte string; false otherwise.
+
+
+
+ Copies the entire byte array to the destination array provided at the offset specified.
+
+
+
+
+ Writes the entire byte array to the provided stream
+
+
+
+
+ SecuritySafeCritical attribute can not be placed on types with async methods.
+ This class has ByteString's async methods so it can be marked with SecuritySafeCritical.
+
+
+
+
+ Reads and decodes protocol message fields.
+
+
+
+ This class is generally used by generated code to read appropriate
+ primitives from the stream. It effectively encapsulates the lowest
+ levels of protocol buffer format.
+
+
+ Repeated fields and map fields are not handled by this class; use
+ and to serialize such fields.
+
+
+
+
+
+ Whether to leave the underlying stream open when disposing of this stream.
+ This is always true when there's no stream.
+
+
+
+
+ Buffer of data read from the stream or provided at construction time.
+
+
+
+
+ The stream to read further input from, or null if the byte array buffer was provided
+ directly on construction, with no further data available.
+
+
+
+
+ The parser state is kept separately so that other parse implementations can reuse the same
+ parsing primitives.
+
+
+
+
+ Creates a new CodedInputStream reading data from the given byte array.
+
+
+
+
+ Creates a new that reads from the given byte array slice.
+
+
+
+
+ Creates a new reading data from the given stream, which will be disposed
+ when the returned object is disposed.
+
+ The stream to read from.
+
+
+
+ Creates a new reading data from the given stream.
+
+ The stream to read from.
+ true to leave open when the returned
+ is disposed; false to dispose of the given stream when the
+ returned object is disposed.
+
+
+
+ Creates a new CodedInputStream reading data from the given
+ stream and buffer, using the default limits.
+
+
+
+
+ Creates a new CodedInputStream reading data from the given
+ stream and buffer, using the specified limits.
+
+
+ This chains to the version with the default limits instead of vice versa to avoid
+ having to check that the default values are valid every time.
+
+
+
+
+ Creates a with the specified size and recursion limits, reading
+ from an input stream.
+
+
+ This method exists separately from the constructor to reduce the number of constructor overloads.
+ It is likely to be used considerably less frequently than the constructors, as the default limits
+ are suitable for most use cases.
+
+ The input stream to read from
+ The total limit of data to read from the stream.
+ The maximum recursion depth to allow while reading.
+ A CodedInputStream reading from with the specified size
+ and recursion limits.
+
+
+
+ Returns the current position in the input stream, or the position in the input buffer
+
+
+
+
+ Returns the last tag read, or 0 if no tags have been read or we've read beyond
+ the end of the stream.
+
+
+
+
+ Returns the size limit for this stream.
+
+
+ This limit is applied when reading from the underlying stream, as a sanity check. It is
+ not applied when reading from a byte array data source without an underlying stream.
+ The default value is Int32.MaxValue.
+
+
+ The size limit.
+
+
+
+
+ Returns the recursion limit for this stream. This limit is applied whilst reading messages,
+ to avoid maliciously-recursive data.
+
+
+ The default limit is 100.
+
+
+ The recursion limit for this stream.
+
+
+
+
+ Internal-only property; when set to true, unknown fields will be discarded while parsing.
+
+
+
+
+ Internal-only property; provides extension identifiers to compatible messages while parsing.
+
+
+
+
+ Disposes of this instance, potentially closing any underlying stream.
+
+
+ As there is no flushing to perform here, disposing of a which
+ was constructed with the leaveOpen option parameter set to true (or one which
+ was constructed to read from a byte array) has no effect.
+
+
+
+
+ Verifies that the last call to ReadTag() returned tag 0 - in other words,
+ we've reached the end of the stream when we expected to.
+
+ The
+ tag read was not the one specified
+
+
+
+ Peeks at the next field tag. This is like calling , but the
+ tag is not consumed. (So a subsequent call to will return the
+ same value.)
+
+
+
+
+ Reads a field tag, returning the tag of 0 for "end of stream".
+
+
+ If this method returns 0, it doesn't necessarily mean the end of all
+ the data in this CodedInputStream; it may be the end of the logical stream
+ for an embedded message, for example.
+
+ The next field tag, or 0 for end of stream. (0 is never a valid tag.)
+
+
+
+ Skips the data for the field with the tag we've just read.
+ This should be called directly after , when
+ the caller wishes to skip an unknown field.
+
+
+ This method throws if the last-read tag was an end-group tag.
+ If a caller wishes to skip a group, they should skip the whole group, by calling this method after reading the
+ start-group tag. This behavior allows callers to call this method on any field they don't understand, correctly
+ resulting in an error if an end-group tag has not been paired with an earlier start-group tag.
+
+ The last tag was an end-group tag
+ The last read operation read to the end of the logical stream
+
+
+
+ Skip a group.
+
+
+
+
+ Reads a double field from the stream.
+
+
+
+
+ Reads a float field from the stream.
+
+
+
+
+ Reads a uint64 field from the stream.
+
+
+
+
+ Reads an int64 field from the stream.
+
+
+
+
+ Reads an int32 field from the stream.
+
+
+
+
+ Reads a fixed64 field from the stream.
+
+
+
+
+ Reads a fixed32 field from the stream.
+
+
+
+
+ Reads a bool field from the stream.
+
+
+
+
+ Reads a string field from the stream.
+
+
+
+
+ Reads an embedded message field value from the stream.
+
+
+
+
+ Reads an embedded group field from the stream.
+
+
+
+
+ Reads a bytes field value from the stream.
+
+
+
+
+ Reads a uint32 field value from the stream.
+
+
+
+
+ Reads an enum field value from the stream.
+
+
+
+
+ Reads an sfixed32 field value from the stream.
+
+
+
+
+ Reads an sfixed64 field value from the stream.
+
+
+
+
+ Reads an sint32 field value from the stream.
+
+
+
+
+ Reads an sint64 field value from the stream.
+
+
+
+
+ Reads a length for length-delimited data.
+
+
+ This is internally just reading a varint, but this method exists
+ to make the calling code clearer.
+
+
+
+
+ Peeks at the next tag in the stream. If it matches ,
+ the tag is consumed and the method returns true; otherwise, the
+ stream is left in the original position and the method returns false.
+
+
+
+
+ Reads a raw Varint from the stream. If larger than 32 bits, discard the upper bits.
+ This method is optimised for the case where we've got lots of data in the buffer.
+ That means we can check the size just once, then just read directly from the buffer
+ without constant rechecking of the buffer length.
+
+
+
+
+ Reads a varint from the input one byte at a time, so that it does not
+ read any bytes after the end of the varint. If you simply wrapped the
+ stream in a CodedInputStream and used ReadRawVarint32(Stream)
+ then you would probably end up reading past the end of the varint since
+ CodedInputStream buffers its input.
+
+
+
+
+
+
+ Reads a raw varint from the stream.
+
+
+
+
+ Reads a 32-bit little-endian integer from the stream.
+
+
+
+
+ Reads a 64-bit little-endian integer from the stream.
+
+
+
+
+ Sets currentLimit to (current position) + byteLimit. This is called
+ when descending into a length-delimited embedded message. The previous
+ limit is returned.
+
+ The old limit.
+
+
+
+ Discards the current limit, returning the previous limit.
+
+
+
+
+ Returns whether or not all the data before the limit has been read.
+
+
+
+
+
+ Returns true if the stream has reached the end of the input. This is the
+ case if either the end of the underlying input source has been reached or
+ the stream has reached a limit created using PushLimit.
+
+
+
+
+ Called when buffer is empty to read more bytes from the
+ input. If is true, RefillBuffer() guarantees that
+ either there will be at least one byte in the buffer when it returns
+ or it will throw an exception. If is false,
+ RefillBuffer() returns false if no more bytes were available.
+
+
+
+
+
+
+ Reads a fixed size of bytes from the input.
+
+
+ the end of the stream or the current limit was reached
+
+
+
+
+ Reads a top-level message or a nested message after the limits for this message have been pushed.
+ (parser will proceed until the end of the current limit)
+ NOTE: this method needs to be public because it's invoked by the generated code - e.g. msg.MergeFrom(CodedInputStream input) method
+
+
+
+
+ Encodes and writes protocol message fields.
+
+
+
+ This class is generally used by generated code to write appropriate
+ primitives to the stream. It effectively encapsulates the lowest
+ levels of protocol buffer format. Unlike some other implementations,
+ this does not include combined "write tag and value" methods. Generated
+ code knows the exact byte representations of the tags they're going to write,
+ so there's no need to re-encode them each time. Manually-written code calling
+ this class should just call one of the WriteTag overloads before each value.
+
+
+ Repeated fields and map fields are not handled by this class; use RepeatedField<T>
+ and MapField<TKey, TValue> to serialize such fields.
+
+
+
+
+
+ Computes the number of bytes that would be needed to encode a
+ double field, including the tag.
+
+
+
+
+ Computes the number of bytes that would be needed to encode a
+ float field, including the tag.
+
+
+
+
+ Computes the number of bytes that would be needed to encode a
+ uint64 field, including the tag.
+
+
+
+
+ Computes the number of bytes that would be needed to encode an
+ int64 field, including the tag.
+
+
+
+
+ Computes the number of bytes that would be needed to encode an
+ int32 field, including the tag.
+
+
+
+
+ Computes the number of bytes that would be needed to encode a
+ fixed64 field, including the tag.
+
+
+
+
+ Computes the number of bytes that would be needed to encode a
+ fixed32 field, including the tag.
+
+
+
+
+ Computes the number of bytes that would be needed to encode a
+ bool field, including the tag.
+
+
+
+
+ Computes the number of bytes that would be needed to encode a
+ string field, including the tag.
+
+
+
+
+ Computes the number of bytes that would be needed to encode a
+ group field, including the tag.
+
+
+
+
+ Computes the number of bytes that would be needed to encode an
+ embedded message field, including the tag.
+
+
+
+
+ Computes the number of bytes that would be needed to encode a
+ bytes field, including the tag.
+
+
+
+
+ Computes the number of bytes that would be needed to encode a
+ uint32 field, including the tag.
+
+
+
+
+ Computes the number of bytes that would be needed to encode a
+ enum field, including the tag. The caller is responsible for
+ converting the enum value to its numeric value.
+
+
+
+
+ Computes the number of bytes that would be needed to encode an
+ sfixed32 field, including the tag.
+
+
+
+
+ Computes the number of bytes that would be needed to encode an
+ sfixed64 field, including the tag.
+
+
+
+
+ Computes the number of bytes that would be needed to encode an
+ sint32 field, including the tag.
+
+
+
+
+ Computes the number of bytes that would be needed to encode an
+ sint64 field, including the tag.
+
+
+
+
+ Computes the number of bytes that would be needed to encode a length,
+ as written by .
+
+
+
+
+ Computes the number of bytes that would be needed to encode a varint.
+
+
+
+
+ Computes the number of bytes that would be needed to encode a varint.
+
+
+
+
+ Computes the number of bytes that would be needed to encode a tag.
+
+
+
+
+ The buffer size used by CreateInstance(Stream).
+
+
+
+
+ Creates a new CodedOutputStream that writes directly to the given
+ byte array. If more bytes are written than fit in the array,
+ OutOfSpaceException will be thrown.
+
+
+
+
+ Creates a new CodedOutputStream that writes directly to the given
+ byte array slice. If more bytes are written than fit in the array,
+ OutOfSpaceException will be thrown.
+
+
+
+
+ Creates a new which write to the given stream, and disposes of that
+ stream when the returned CodedOutputStream is disposed.
+
+ The stream to write to. It will be disposed when the returned CodedOutputStream is disposed.
+
+
+
+ Creates a new CodedOutputStream which write to the given stream and uses
+ the specified buffer size.
+
+ The stream to write to. It will be disposed when the returned CodedOutputStream is disposed.
+ The size of buffer to use internally.
+
+
+
+ Creates a new CodedOutputStream which write to the given stream.
+
+ The stream to write to.
+ If true, is left open when the returned CodedOutputStream is disposed;
+ if false, the provided stream is disposed as well.
+
+
+
+ Creates a new CodedOutputStream which write to the given stream and uses
+ the specified buffer size.
+
+ The stream to write to.
+ The size of buffer to use internally.
+ If true, is left open when the returned CodedOutputStream is disposed;
+ if false, the provided stream is disposed as well.
+
+
+
+ Returns the current position in the stream, or the position in the output buffer
+
+
+
+
+ Writes a double field value, without a tag, to the stream.
+
+ The value to write
+
+
+
+ Writes a float field value, without a tag, to the stream.
+
+ The value to write
+
+
+
+ Writes a uint64 field value, without a tag, to the stream.
+
+ The value to write
+
+
+
+ Writes an int64 field value, without a tag, to the stream.
+
+ The value to write
+
+
+
+ Writes an int32 field value, without a tag, to the stream.
+
+ The value to write
+
+
+
+ Writes a fixed64 field value, without a tag, to the stream.
+
+ The value to write
+
+
+
+ Writes a fixed32 field value, without a tag, to the stream.
+
+ The value to write
+
+
+
+ Writes a bool field value, without a tag, to the stream.
+
+ The value to write
+
+
+
+ Writes a string field value, without a tag, to the stream.
+ The data is length-prefixed.
+
+ The value to write
+
+
+
+ Writes a message, without a tag, to the stream.
+ The data is length-prefixed.
+
+ The value to write
+
+
+
+ Writes a message, without a tag, to the stream.
+ Only the message data is written, without a length-delimiter.
+
+ The value to write
+
+
+
+ Writes a group, without a tag, to the stream.
+
+ The value to write
+
+
+
+ Write a byte string, without a tag, to the stream.
+ The data is length-prefixed.
+
+ The value to write
+
+
+
+ Writes a uint32 value, without a tag, to the stream.
+
+ The value to write
+
+
+
+ Writes an enum value, without a tag, to the stream.
+
+ The value to write
+
+
+
+ Writes an sfixed32 value, without a tag, to the stream.
+
+ The value to write.
+
+
+
+ Writes an sfixed64 value, without a tag, to the stream.
+
+ The value to write
+
+
+
+ Writes an sint32 value, without a tag, to the stream.
+
+ The value to write
+
+
+
+ Writes an sint64 value, without a tag, to the stream.
+
+ The value to write
+
+
+
+ Writes a length (in bytes) for length-delimited data.
+
+
+ This method simply writes a rawint, but exists for clarity in calling code.
+
+ Length value, in bytes.
+
+
+
+ Encodes and writes a tag.
+
+ The number of the field to write the tag for
+ The wire format type of the tag to write
+
+
+
+ Writes an already-encoded tag.
+
+ The encoded tag
+
+
+
+ Writes the given single-byte tag directly to the stream.
+
+ The encoded tag
+
+
+
+ Writes the given two-byte tag directly to the stream.
+
+ The first byte of the encoded tag
+ The second byte of the encoded tag
+
+
+
+ Writes the given three-byte tag directly to the stream.
+
+ The first byte of the encoded tag
+ The second byte of the encoded tag
+ The third byte of the encoded tag
+
+
+
+ Writes the given four-byte tag directly to the stream.
+
+ The first byte of the encoded tag
+ The second byte of the encoded tag
+ The third byte of the encoded tag
+ The fourth byte of the encoded tag
+
+
+
+ Writes the given five-byte tag directly to the stream.
+
+ The first byte of the encoded tag
+ The second byte of the encoded tag
+ The third byte of the encoded tag
+ The fourth byte of the encoded tag
+ The fifth byte of the encoded tag
+
+
+
+ Writes a 32 bit value as a varint. The fast route is taken when
+ there's enough buffer space left to whizz through without checking
+ for each byte; otherwise, we resort to calling WriteRawByte each time.
+
+
+
+
+ Writes out an array of bytes.
+
+
+
+
+ Writes out part of an array of bytes.
+
+
+
+
+ Indicates that a CodedOutputStream wrapping a flat byte array
+ ran out of space.
+
+
+
+
+ Flushes any buffered data and optionally closes the underlying stream, if any.
+
+
+
+ By default, any underlying stream is closed by this method. To configure this behaviour,
+ use a constructor overload with a leaveOpen parameter. If this instance does not
+ have an underlying stream, this method does nothing.
+
+
+ For the sake of efficiency, calling this method does not prevent future write calls - but
+ if a later write ends up writing to a stream which has been disposed, that is likely to
+ fail. It is recommend that you not call any other methods after this.
+
+
+
+
+
+ Flushes any buffered data to the underlying stream (if there is one).
+
+
+
+
+ Verifies that SpaceLeft returns zero. It's common to create a byte array
+ that is exactly big enough to hold a message, then write to it with
+ a CodedOutputStream. Calling CheckNoSpaceLeft after writing verifies that
+ the message was actually as big as expected, which can help finding bugs.
+
+
+
+
+ If writing to a flat array, returns the space left in the array. Otherwise,
+ throws an InvalidOperationException.
+
+
+
+
+ Utility to compare if two Lists are the same, and the hash code
+ of a List.
+
+
+
+
+ Checks if two lists are equal.
+
+
+
+
+ Gets the list's hash code.
+
+
+
+
+ Representation of a map field in a Protocol Buffer message.
+
+ Key type in the map. Must be a type supported by Protocol Buffer map keys.
+ Value type in the map. Must be a type supported by Protocol Buffers.
+
+
+ For string keys, the equality comparison is provided by .
+
+
+ Null values are not permitted in the map, either for wrapper types or regular messages.
+ If a map is deserialized from a data stream and the value is missing from an entry, a default value
+ is created instead. For primitive types, that is the regular default value (0, the empty string and so
+ on); for message types, an empty instance of the message is created, as if the map entry contained a 0-length
+ encoded value for the field.
+
+
+ This implementation does not generally prohibit the use of key/value types which are not
+ supported by Protocol Buffers (e.g. using a key type of byte) but nor does it guarantee
+ that all operations will work in such cases.
+
+
+ The order in which entries are returned when iterating over this object is undefined, and may change
+ in future versions.
+
+
+
+
+
+ Creates a deep clone of this object.
+
+
+ A deep clone of this object.
+
+
+
+
+ Adds the specified key/value pair to the map.
+
+
+ This operation fails if the key already exists in the map. To replace an existing entry, use the indexer.
+
+ The key to add
+ The value to add.
+ The given key already exists in map.
+
+
+
+ Determines whether the specified key is present in the map.
+
+ The key to check.
+ true if the map contains the given key; false otherwise.
+
+
+
+ Removes the entry identified by the given key from the map.
+
+ The key indicating the entry to remove from the map.
+ true if the map contained the given key before the entry was removed; false otherwise.
+
+
+
+ Gets the value associated with the specified key.
+
+ The key whose value to get.
+ When this method returns, the value associated with the specified key, if the key is found;
+ otherwise, the default value for the type of the parameter.
+ This parameter is passed uninitialized.
+ true if the map contains an element with the specified key; otherwise, false.
+
+
+
+ Gets or sets the value associated with the specified key.
+
+ The key of the value to get or set.
+ The property is retrieved and key does not exist in the collection.
+ The value associated with the specified key. If the specified key is not found,
+ a get operation throws a , and a set operation creates a new element with the specified key.
+
+
+
+ Gets a collection containing the keys in the map.
+
+
+
+
+ Gets a collection containing the values in the map.
+
+
+
+
+ Adds the specified entries to the map. The keys and values are not automatically cloned.
+
+ The entries to add to the map.
+
+
+
+ Returns an enumerator that iterates through the collection.
+
+
+ An enumerator that can be used to iterate through the collection.
+
+
+
+
+ Returns an enumerator that iterates through a collection.
+
+
+ An object that can be used to iterate through the collection.
+
+
+
+
+ Adds the specified item to the map.
+
+ The item to add to the map.
+
+
+
+ Removes all items from the map.
+
+
+
+
+ Determines whether map contains an entry equivalent to the given key/value pair.
+
+ The key/value pair to find.
+
+
+
+
+ Copies the key/value pairs in this map to an array.
+
+ The array to copy the entries into.
+ The index of the array at which to start copying values.
+
+
+
+ Removes the specified key/value pair from the map.
+
+ Both the key and the value must be found for the entry to be removed.
+ The key/value pair to remove.
+ true if the key/value pair was found and removed; false otherwise.
+
+
+
+ Gets the number of elements contained in the map.
+
+
+
+
+ Gets a value indicating whether the map is read-only.
+
+
+
+
+ Determines whether the specified , is equal to this instance.
+
+ The to compare with this instance.
+
+ true if the specified is equal to this instance; otherwise, false.
+
+
+
+
+ Returns a hash code for this instance.
+
+
+ A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
+
+
+
+
+ Compares this map with another for equality.
+
+
+ The order of the key/value pairs in the maps is not deemed significant in this comparison.
+
+ The map to compare this with.
+ true if refers to an equal map; false otherwise.
+
+
+
+ Adds entries to the map from the given stream.
+
+
+ It is assumed that the stream is initially positioned after the tag specified by the codec.
+ This method will continue reading entries from the stream until the end is reached, or
+ a different tag is encountered.
+
+ Stream to read from
+ Codec describing how the key/value pairs are encoded
+
+
+
+ Adds entries to the map from the given parse context.
+
+
+ It is assumed that the input is initially positioned after the tag specified by the codec.
+ This method will continue reading entries from the input until the end is reached, or
+ a different tag is encountered.
+
+ Input to read from
+ Codec describing how the key/value pairs are encoded
+
+
+
+ Writes the contents of this map to the given coded output stream, using the specified codec
+ to encode each entry.
+
+ The output stream to write to.
+ The codec to use for each entry.
+
+
+
+ Writes the contents of this map to the given write context, using the specified codec
+ to encode each entry.
+
+ The write context to write to.
+ The codec to use for each entry.
+
+
+
+ Calculates the size of this map based on the given entry codec.
+
+ The codec to use to encode each entry.
+
+
+
+
+ Returns a string representation of this repeated field, in the same
+ way as it would be represented by the default JSON formatter.
+
+
+
+
+ A codec for a specific map field. This contains all the information required to encode and
+ decode the nested messages.
+
+
+
+
+ Creates a new entry codec based on a separate key codec and value codec,
+ and the tag to use for each map entry.
+
+ The key codec.
+ The value codec.
+ The map tag to use to introduce each map entry.
+
+
+
+ The key codec.
+
+
+
+
+ The value codec.
+
+
+
+
+ The tag used in the enclosing message to indicate map entries.
+
+
+
+
+ Provides a central place to implement equality comparisons, primarily for bitwise float/double equality.
+
+
+
+
+ Returns an equality comparer for suitable for Protobuf equality comparisons.
+ This is usually just the default equality comparer for the type, but floating point numbers are compared
+ bitwise.
+
+ The type of equality comparer to return.
+ The equality comparer.
+
+
+
+ Returns an equality comparer suitable for comparing 64-bit floating point values, by bitwise comparison.
+ (NaN values are considered equal, but only when they have the same representation.)
+
+
+
+
+ Returns an equality comparer suitable for comparing 32-bit floating point values, by bitwise comparison.
+ (NaN values are considered equal, but only when they have the same representation.)
+
+
+
+
+ Returns an equality comparer suitable for comparing nullable 64-bit floating point values, by bitwise comparison.
+ (NaN values are considered equal, but only when they have the same representation.)
+
+
+
+
+ Returns an equality comparer suitable for comparing nullable 32-bit floating point values, by bitwise comparison.
+ (NaN values are considered equal, but only when they have the same representation.)
+
+
+
+
+ Read-only wrapper around another dictionary.
+
+
+
+
+ The contents of a repeated field: essentially, a collection with some extra
+ restrictions (no null values) and capabilities (deep cloning).
+
+
+ This implementation does not generally prohibit the use of types which are not
+ supported by Protocol Buffers but nor does it guarantee that all operations will work in such cases.
+
+ The element type of the repeated field.
+
+
+
+ Creates a deep clone of this repeated field.
+
+
+ If the field type is
+ a message type, each element is also cloned; otherwise, it is
+ assumed that the field type is primitive (including string and
+ bytes, both of which are immutable) and so a simple copy is
+ equivalent to a deep clone.
+
+ A deep clone of this repeated field.
+
+
+
+ Adds the entries from the given input stream, decoding them with the specified codec.
+
+ The input stream to read from.
+ The codec to use in order to read each entry.
+
+
+
+ Adds the entries from the given parse context, decoding them with the specified codec.
+
+ The input to read from.
+ The codec to use in order to read each entry.
+
+
+
+ Calculates the size of this collection based on the given codec.
+
+ The codec to use when encoding each field.
+ The number of bytes that would be written to an output by one of the WriteTo methods,
+ using the same codec.
+
+
+
+ Writes the contents of this collection to the given ,
+ encoding each value using the specified codec.
+
+ The output stream to write to.
+ The codec to use when encoding each value.
+
+
+
+ Writes the contents of this collection to the given write context,
+ encoding each value using the specified codec.
+
+ The write context to write to.
+ The codec to use when encoding each value.
+
+
+
+ Gets and sets the capacity of the RepeatedField's internal array. WHen set, the internal array is reallocated to the given capacity.
+ The new value is less than Count -or- when Count is less than 0.
+
+
+
+
+ Adds the specified item to the collection.
+
+ The item to add.
+
+
+
+ Removes all items from the collection.
+
+
+
+
+ Determines whether this collection contains the given item.
+
+ The item to find.
+ true if this collection contains the given item; false otherwise.
+
+
+
+ Copies this collection to the given array.
+
+ The array to copy to.
+ The first index of the array to copy to.
+
+
+
+ Removes the specified item from the collection
+
+ The item to remove.
+ true if the item was found and removed; false otherwise.
+
+
+
+ Gets the number of elements contained in the collection.
+
+
+
+
+ Gets a value indicating whether the collection is read-only.
+
+
+
+
+ Adds all of the specified values into this collection.
+
+ The values to add to this collection.
+
+
+
+ Adds all of the specified values into this collection. This method is present to
+ allow repeated fields to be constructed from queries within collection initializers.
+ Within non-collection-initializer code, consider using the equivalent
+ method instead for clarity.
+
+ The values to add to this collection.
+
+
+
+ Returns an enumerator that iterates through the collection.
+
+
+ An enumerator that can be used to iterate through the collection.
+
+
+
+
+ Determines whether the specified , is equal to this instance.
+
+ The to compare with this instance.
+
+ true if the specified is equal to this instance; otherwise, false.
+
+
+
+
+ Returns an enumerator that iterates through a collection.
+
+
+ An object that can be used to iterate through the collection.
+
+
+
+
+ Returns a hash code for this instance.
+
+
+ A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
+
+
+
+
+ Compares this repeated field with another for equality.
+
+ The repeated field to compare this with.
+ true if refers to an equal repeated field; false otherwise.
+
+
+
+ Returns the index of the given item within the collection, or -1 if the item is not
+ present.
+
+ The item to find in the collection.
+ The zero-based index of the item, or -1 if it is not found.
+
+
+
+ Inserts the given item at the specified index.
+
+ The index at which to insert the item.
+ The item to insert.
+
+
+
+ Removes the item at the given index.
+
+ The zero-based index of the item to remove.
+
+
+
+ Returns a string representation of this repeated field, in the same
+ way as it would be represented by the default JSON formatter.
+
+
+
+
+ Gets or sets the item at the specified index.
+
+
+ The element at the specified index.
+
+ The zero-based index of the element to get or set.
+ The item at the specified index.
+
+
+
+ Extension methods for , effectively providing
+ the familiar members from previous desktop framework versions while
+ targeting the newer releases, .NET Core etc.
+
+
+
+
+ Returns the public getter of a property, or null if there is no such getter
+ (either because it's read-only, or the getter isn't public).
+
+
+
+
+ Returns the public setter of a property, or null if there is no such setter
+ (either because it's write-only, or the setter isn't public).
+
+
+
+
+ Provides extension methods on Type that just proxy to TypeInfo.
+ These are used to support the new type system from .NET 4.5, without
+ having calls to GetTypeInfo all over the place. While the methods here are meant to be
+ broadly compatible with the desktop framework, there are some subtle differences in behaviour - but
+ they're not expected to affect our use cases. While the class is internal, that should be fine: we can
+ evaluate each new use appropriately.
+
+
+
+
+ See https://msdn.microsoft.com/en-us/library/system.type.isassignablefrom
+
+
+
+
+ Returns a representation of the public property associated with the given name in the given type,
+ including inherited properties or null if there is no such public property.
+ Here, "public property" means a property where either the getter, or the setter, or both, is public.
+
+
+
+
+ Returns a representation of the public method associated with the given name in the given type,
+ including inherited methods.
+
+
+ This has a few differences compared with Type.GetMethod in the desktop framework. It will throw
+ if there is an ambiguous match even between a private method and a public one, but it *won't* throw
+ if there are two overloads at different levels in the type hierarchy (e.g. class Base declares public void Foo(int) and
+ class Child : Base declares public void Foo(long)).
+
+ One type in the hierarchy declared more than one method with the same name
+
+
+
+ Represents a non-generic extension definition. This API is experimental and subject to change.
+
+
+
+
+ Internal use. Creates a new extension with the specified field number.
+
+
+
+
+ Gets the field number of this extension
+
+
+
+
+ Represents a type-safe extension identifier used for getting and setting single extension values in instances.
+ This API is experimental and subject to change.
+
+ The message type this field applies to
+ The field value type of this extension
+
+
+
+ Creates a new extension identifier with the specified field number and codec
+
+
+
+
+ Represents a type-safe extension identifier used for getting repeated extension values in instances.
+ This API is experimental and subject to change.
+
+ The message type this field applies to
+ The repeated field value type of this extension
+
+
+
+ Creates a new repeated extension identifier with the specified field number and codec
+
+
+
+
+ Provides extensions to messages while parsing. This API is experimental and subject to change.
+
+
+
+
+ Creates a new empty extension registry
+
+
+
+
+ Gets the total number of extensions in this extension registry
+
+
+
+
+ Returns whether the registry is readonly
+
+
+
+
+ Adds the specified extension to the registry
+
+
+
+
+ Adds the specified extensions to the registry
+
+
+
+
+ Clears the registry of all values
+
+
+
+
+ Gets whether the extension registry contains the specified extension
+
+
+
+
+ Copies the arrays in the registry set to the specified array at the specified index
+
+ The array to copy to
+ The array index to start at
+
+
+
+ Returns an enumerator to enumerate through the items in the registry
+
+ Returns an enumerator for the extensions in this registry
+
+
+
+ Removes the specified extension from the set
+
+ The extension
+ true if the extension was removed, otherwise false
+
+
+
+ Clones the registry into a new registry
+
+
+
+
+ Methods for managing s with null checking.
+
+ Most users will not use this class directly and its API is experimental and subject to change.
+
+
+
+
+ Gets the value of the specified extension
+
+
+
+
+ Gets the value of the specified repeated extension or null if it doesn't exist in this set
+
+
+
+
+ Gets the value of the specified repeated extension, registering it if it doesn't exist
+
+
+
+
+ Sets the value of the specified extension. This will make a new instance of ExtensionSet if the set is null.
+
+
+
+
+ Gets whether the value of the specified extension is set
+
+
+
+
+ Clears the value of the specified extension
+
+
+
+
+ Clears the value of the specified extension
+
+
+
+
+ Tries to merge a field from the coded input, returning true if the field was merged.
+ If the set is null or the field was not otherwise merged, this returns false.
+
+
+
+
+ Tries to merge a field from the coded input, returning true if the field was merged.
+ If the set is null or the field was not otherwise merged, this returns false.
+
+
+
+
+ Merges the second set into the first set, creating a new instance if first is null
+
+
+
+
+ Clones the set into a new set. If the set is null, this returns null
+
+
+
+
+ Used for keeping track of extensions in messages.
+ methods route to this set.
+
+ Most users will not need to use this class directly
+
+ The message type that extensions in this set target
+
+
+
+ Gets a hash code of the set
+
+
+
+
+ Returns whether this set is equal to the other object
+
+
+
+
+ Calculates the size of this extension set
+
+
+
+
+ Writes the extension values in this set to the output stream
+
+
+
+
+ Writes the extension values in this set to the write context
+
+
+
+
+ Factory methods for .
+
+
+
+
+ Retrieves a codec suitable for a string field with the given tag.
+
+ The tag.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for a bytes field with the given tag.
+
+ The tag.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for a bool field with the given tag.
+
+ The tag.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for an int32 field with the given tag.
+
+ The tag.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for an sint32 field with the given tag.
+
+ The tag.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for a fixed32 field with the given tag.
+
+ The tag.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for an sfixed32 field with the given tag.
+
+ The tag.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for a uint32 field with the given tag.
+
+ The tag.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for an int64 field with the given tag.
+
+ The tag.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for an sint64 field with the given tag.
+
+ The tag.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for a fixed64 field with the given tag.
+
+ The tag.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for an sfixed64 field with the given tag.
+
+ The tag.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for a uint64 field with the given tag.
+
+ The tag.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for a float field with the given tag.
+
+ The tag.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for a double field with the given tag.
+
+ The tag.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for an enum field with the given tag.
+
+ The tag.
+ A conversion function from to the enum type.
+ A conversion function from the enum type to .
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for a string field with the given tag.
+
+ The tag.
+ The default value.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for a bytes field with the given tag.
+
+ The tag.
+ The default value.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for a bool field with the given tag.
+
+ The tag.
+ The default value.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for an int32 field with the given tag.
+
+ The tag.
+ The default value.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for an sint32 field with the given tag.
+
+ The tag.
+ The default value.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for a fixed32 field with the given tag.
+
+ The tag.
+ The default value.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for an sfixed32 field with the given tag.
+
+ The tag.
+ The default value.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for a uint32 field with the given tag.
+
+ The tag.
+ The default value.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for an int64 field with the given tag.
+
+ The tag.
+ The default value.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for an sint64 field with the given tag.
+
+ The tag.
+ The default value.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for a fixed64 field with the given tag.
+
+ The tag.
+ The default value.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for an sfixed64 field with the given tag.
+
+ The tag.
+ The default value.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for a uint64 field with the given tag.
+
+ The tag.
+ The default value.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for a float field with the given tag.
+
+ The tag.
+ The default value.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for a double field with the given tag.
+
+ The tag.
+ The default value.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for an enum field with the given tag.
+
+ The tag.
+ A conversion function from to the enum type.
+ A conversion function from the enum type to .
+ The default value.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for a message field with the given tag.
+
+ The tag.
+ A parser to use for the message type.
+ A codec for the given tag.
+
+
+
+ Retrieves a codec suitable for a group field with the given tag.
+
+ The start group tag.
+ The end group tag.
+ A parser to use for the group message type.
+ A codec for given tag
+
+
+
+ Creates a codec for a wrapper type of a class - which must be string or ByteString.
+
+
+
+
+ Creates a codec for a wrapper type of a struct - which must be Int32, Int64, UInt32, UInt64,
+ Bool, Single or Double.
+
+
+
+
+ Helper code to create codecs for wrapper types.
+
+
+ Somewhat ugly with all the static methods, but the conversions involved to/from nullable types make it
+ slightly tricky to improve. So long as we keep the public API (ForClassWrapper, ForStructWrapper) in place,
+ we can refactor later if we come up with something cleaner.
+
+
+
+
+ Returns a field codec which effectively wraps a value of type T in a message.
+
+
+
+
+
+
+ An encode/decode pair for a single field. This effectively encapsulates
+ all the information needed to read or write the field value from/to a coded
+ stream.
+
+
+ This class is public and has to be as it is used by generated code, but its public
+ API is very limited - just what the generated code needs to call directly.
+
+
+
+ This never writes default values to the stream, and does not address "packedness"
+ in repeated fields itself, other than to know whether or not the field *should* be packed.
+
+
+
+
+ Merges an input stream into a value
+
+
+
+
+ Merges a value into a reference to another value, returning a boolean if the value was set
+
+
+
+
+ Returns a delegate to write a value (unconditionally) to a coded output stream.
+
+
+
+
+ Returns the size calculator for just a value.
+
+
+
+
+ Returns a delegate to read a value from a coded input stream. It is assumed that
+ the stream is already positioned on the appropriate tag.
+
+
+
+
+ Returns a delegate to merge a value from a coded input stream.
+ It is assumed that the stream is already positioned on the appropriate tag
+
+
+
+
+ Returns a delegate to merge two values together.
+
+
+
+
+ Returns the fixed size for an entry, or 0 if sizes vary.
+
+
+
+
+ Gets the tag of the codec.
+
+
+ The tag of the codec.
+
+
+
+
+ Gets the end tag of the codec or 0 if there is no end tag
+
+
+ The end tag of the codec.
+
+
+
+
+ Default value for this codec. Usually the same for every instance of the same type, but
+ for string/ByteString wrapper fields the codec's default value is null, whereas for
+ other string/ByteString fields it's "" or ByteString.Empty.
+
+
+ The default value of the codec's type.
+
+
+
+
+ Write a tag and the given value, *if* the value is not the default.
+
+
+
+
+ Write a tag and the given value, *if* the value is not the default.
+
+
+
+
+ Reads a value of the codec type from the given .
+
+ The input stream to read from.
+ The value read from the stream.
+
+
+
+ Reads a value of the codec type from the given .
+
+ The parse context to read from.
+ The value read.
+
+
+
+ Calculates the size required to write the given value, with a tag,
+ if the value is not the default.
+
+
+
+
+ Calculates the size required to write the given value, with a tag, even
+ if the value is the default.
+
+
+
+
+ A tree representation of a FieldMask. Each leaf node in this tree represent
+ a field path in the FieldMask.
+
+ For example, FieldMask "foo.bar,foo.baz,bar.baz" as a tree will be:
+
+ [root] -+- foo -+- bar
+ | |
+ | +- baz
+ |
+ +- bar --- baz
+
+
+ By representing FieldMasks with this tree structure we can easily convert
+ a FieldMask to a canonical form, merge two FieldMasks, calculate the
+ intersection to two FieldMasks and traverse all fields specified by the
+ FieldMask in a message tree.
+
+
+
+
+ Creates an empty FieldMaskTree.
+
+
+
+
+ Creates a FieldMaskTree for a given FieldMask.
+
+
+
+
+ Adds a field path to the tree. In a FieldMask, every field path matches the
+ specified field as well as all its sub-fields. For example, a field path
+ "foo.bar" matches field "foo.bar" and also "foo.bar.baz", etc. When adding
+ a field path to the tree, redundant sub-paths will be removed. That is,
+ after adding "foo.bar" to the tree, "foo.bar.baz" will be removed if it
+ exists, which will turn the tree node for "foo.bar" to a leaf node.
+ Likewise, if the field path to add is a sub-path of an existing leaf node,
+ nothing will be changed in the tree.
+
+
+
+
+ Merges all field paths in a FieldMask into this tree.
+
+
+
+
+ Converts this tree to a FieldMask.
+
+
+
+
+ Gathers all field paths in a sub-tree.
+
+
+
+
+ Adds the intersection of this tree with the given to .
+
+
+
+
+ Merges all fields specified by this FieldMaskTree from to .
+
+
+
+
+ Merges all fields specified by a sub-tree from to .
+
+
+
+
+ Class containing helpful workarounds for various platform compatibility
+
+
+
+
+ Interface for a Protocol Buffers message, supporting
+ parsing from and writing to .
+
+
+
+
+ Internal implementation of merging data from given parse context into this message.
+ Users should never invoke this method directly.
+
+
+
+
+ Internal implementation of writing this message to a given write context.
+ Users should never invoke this method directly.
+
+
+
+
+ A message type that has a custom string format for diagnostic purposes.
+
+
+
+ Calling on a generated message type normally
+ returns the JSON representation. If a message type implements this interface,
+ then the method will be called instead of the regular
+ JSON formatting code, but only when ToString() is called either on the message itself
+ or on another message which contains it. This does not affect the normal JSON formatting of
+ the message.
+
+
+ For example, if you create a proto message representing a GUID, the internal
+ representation may be a bytes field or four fixed32 fields. However, when debugging
+ it may be more convenient to see a result in the same format as provides.
+
+ This interface extends to avoid it accidentally being implemented
+ on types other than messages, where it would not be used by anything in the framework.
+
+
+
+
+ Returns a string representation of this object, for diagnostic purposes.
+
+
+ This method is called when a message is formatted as part of a
+ call. It does not affect the JSON representation used by other than
+ in calls to . While it is recommended
+ that the result is valid JSON, this is never assumed by the Protobuf library.
+
+ A string representation of this object, for diagnostic purposes.
+
+
+
+ Generic interface for a deeply cloneable type.
+
+
+
+ All generated messages implement this interface, but so do some non-message types.
+ Additionally, due to the type constraint on T in ,
+ it is simpler to keep this as a separate interface.
+
+
+ The type itself, returned by the method.
+
+
+
+ Creates a deep clone of this object.
+
+ A deep clone of this object.
+
+
+
+ Generic interface for a Protocol Buffers message containing one or more extensions, where the type parameter is expected to be the same type as the implementation class.
+ This interface is experiemental and is subject to change.
+
+
+
+
+ Gets the value of the specified extension
+
+
+
+
+ Gets the value of the specified repeated extension or null if the extension isn't registered in this set.
+ For a version of this method that never returns null, use
+
+
+
+
+ Gets the value of the specified repeated extension, registering it if it hasn't already been registered.
+
+
+
+
+ Sets the value of the specified extension
+
+
+
+
+ Gets whether the value of the specified extension is set
+
+
+
+
+ Clears the value of the specified extension
+
+
+
+
+ Clears the value of the specified repeated extension
+
+
+
+
+ Interface for a Protocol Buffers message, supporting
+ basic operations required for serialization.
+
+
+
+
+ Merges the data from the specified coded input stream with the current message.
+
+ See the user guide for precise merge semantics.
+
+
+
+
+ Writes the data to the given coded output stream.
+
+ Coded output stream to write the data to. Must not be null.
+
+
+
+ Calculates the size of this message in Protocol Buffer wire format, in bytes.
+
+ The number of bytes required to write this message
+ to a coded output stream.
+
+
+
+ Descriptor for this message. All instances are expected to return the same descriptor,
+ and for generated types this will be an explicitly-implemented member, returning the
+ same value as the static property declared on the type.
+
+
+
+
+ Generic interface for a Protocol Buffers message,
+ where the type parameter is expected to be the same type as
+ the implementation class.
+
+ The message type.
+
+
+
+ Merges the given message into this one.
+
+ See the user guide for precise merge semantics.
+ The message to merge with this one. Must not be null.
+
+
+
+ Thrown when an attempt is made to parse invalid JSON, e.g. using
+ a non-string property key, or including a redundant comma. Parsing a protocol buffer
+ message represented in JSON using can throw both this
+ exception and depending on the situation. This
+ exception is only thrown for "pure JSON" errors, whereas InvalidProtocolBufferException
+ is thrown when the JSON may be valid in and of itself, but cannot be parsed as a protocol buffer
+ message.
+
+
+
+
+ Thrown when a protocol message being parsed is invalid in some way,
+ e.g. it contains a malformed varint or a negative byte length.
+
+
+
+
+ Creates an exception for an error condition of an invalid tag being encountered.
+
+
+
+
+ Reflection-based converter from messages to JSON.
+
+
+
+ Instances of this class are thread-safe, with no mutable state.
+
+
+ This is a simple start to get JSON formatting working. As it's reflection-based,
+ it's not as quick as baking calls into generated messages - but is a simpler implementation.
+ (This code is generally not heavily optimized.)
+
+
+
+
+
+ Returns a formatter using the default settings.
+
+
+
+
+ The JSON representation of the first 160 characters of Unicode.
+ Empty strings are replaced by the static constructor.
+
+
+
+
+ Creates a new formatted with the given settings.
+
+ The settings.
+
+
+
+ Formats the specified message as JSON.
+
+ The message to format.
+ The formatted message.
+
+
+
+ Formats the specified message as JSON.
+
+ The message to format.
+ The TextWriter to write the formatted message to.
+ The formatted message.
+
+
+
+ Converts a message to JSON for diagnostic purposes with no extra context.
+
+
+
+ This differs from calling on the default JSON
+ formatter in its handling of . As no type registry is available
+ in calls, the normal way of resolving the type of
+ an Any message cannot be applied. Instead, a JSON property named @value
+ is included with the base64 data from the property of the message.
+
+ The value returned by this method is only designed to be used for diagnostic
+ purposes. It may not be parsable by , and may not be parsable
+ by other Protocol Buffer implementations.
+
+ The message to format for diagnostic purposes.
+ The diagnostic-only JSON representation of the message
+
+
+
+ Determines whether or not a field value should be serialized according to the field,
+ its value in the message, and the settings of this formatter.
+
+
+
+
+ Writes a single value to the given writer as JSON. Only types understood by
+ Protocol Buffers can be written in this way. This method is only exposed for
+ advanced use cases; most users should be using
+ or .
+
+ The writer to write the value to. Must not be null.
+ The value to write. May be null.
+
+
+
+ Central interception point for well-known type formatting. Any well-known types which
+ don't need special handling can fall back to WriteMessage. We avoid assuming that the
+ values are using the embedded well-known types, in order to allow for dynamic messages
+ in the future.
+
+
+
+
+ Writes a string (including leading and trailing double quotes) to a builder, escaping as required.
+
+
+ Other than surrogate pair handling, this code is mostly taken from src/google/protobuf/util/internal/json_escaping.cc.
+
+
+
+
+ Settings controlling JSON formatting.
+
+
+
+
+ Default settings, as used by
+
+
+
+
+ Whether fields which would otherwise not be included in the formatted data
+ should be formatted even when the value is not present, or has the default value.
+ This option only affects fields which don't support "presence" (e.g.
+ singular non-optional proto3 primitive fields).
+
+
+
+
+ The type registry used to format messages.
+
+
+
+
+ Whether to format enums as ints. Defaults to false.
+
+
+
+
+ Creates a new object with the specified formatting of default values
+ and an empty type registry.
+
+ true if default values (0, empty strings etc) should be formatted; false otherwise.
+
+
+
+ Creates a new object with the specified formatting of default values
+ and type registry.
+
+ true if default values (0, empty strings etc) should be formatted; false otherwise.
+ The to use when formatting messages.
+
+
+
+ Creates a new object with the specified parameters.
+
+ true if default values (0, empty strings etc) should be formatted; false otherwise.
+ The to use when formatting messages. TypeRegistry.Empty will be used if it is null.
+ true to format the enums as integers; false to format enums as enum names.
+
+
+
+ Creates a new object with the specified formatting of default values and the current settings.
+
+ true if default values (0, empty strings etc) should be formatted; false otherwise.
+
+
+
+ Creates a new object with the specified type registry and the current settings.
+
+ The to use when formatting messages.
+
+
+
+ Creates a new object with the specified enums formatting option and the current settings.
+
+ true to format the enums as integers; false to format enums as enum names.
+
+
+
+ Reflection-based converter from JSON to messages.
+
+
+
+ Instances of this class are thread-safe, with no mutable state.
+
+
+ This is a simple start to get JSON parsing working. As it's reflection-based,
+ it's not as quick as baking calls into generated messages - but is a simpler implementation.
+ (This code is generally not heavily optimized.)
+
+
+
+
+
+ Returns a formatter using the default settings.
+
+
+
+
+ Creates a new formatted with the given settings.
+
+ The settings.
+
+
+
+ Parses and merges the information into the given message.
+
+ The message to merge the JSON information into.
+ The JSON to parse.
+
+
+
+ Parses JSON read from and merges the information into the given message.
+
+ The message to merge the JSON information into.
+ Reader providing the JSON to parse.
+
+
+
+ Merges the given message using data from the given tokenizer. In most cases, the next
+ token should be a "start object" token, but wrapper types and nullity can invalidate
+ that assumption. This is implemented as an LL(1) recursive descent parser over the stream
+ of tokens provided by the tokenizer. This token stream is assumed to be valid JSON, with the
+ tokenizer performing that validation - but not every token stream is valid "protobuf JSON".
+
+
+
+
+ Parses into a new message.
+
+ The type of message to create.
+ The JSON to parse.
+ The JSON does not comply with RFC 7159
+ The JSON does not represent a Protocol Buffers message correctly
+
+
+
+ Parses JSON read from into a new message.
+
+ The type of message to create.
+ Reader providing the JSON to parse.
+ The JSON does not comply with RFC 7159
+ The JSON does not represent a Protocol Buffers message correctly
+
+
+
+ Parses into a new message.
+
+ The JSON to parse.
+ Descriptor of message type to parse.
+ The JSON does not comply with RFC 7159
+ The JSON does not represent a Protocol Buffers message correctly
+
+
+
+ Parses JSON read from into a new message.
+
+ Reader providing the JSON to parse.
+ Descriptor of message type to parse.
+ The JSON does not comply with RFC 7159
+ The JSON does not represent a Protocol Buffers message correctly
+
+
+
+ Creates a new instance of the message type for the given field.
+
+
+
+
+ Checks that any infinite/NaN values originated from the correct text.
+ This corrects the lenient whitespace handling of double.Parse/float.Parse, as well as the
+ way that Mono parses out-of-range values as infinity.
+
+
+
+
+ Settings controlling JSON parsing.
+
+
+
+
+ Default settings, as used by . This has the same default
+ recursion limit as , and an empty type registry.
+
+
+
+
+ The maximum depth of messages to parse. Note that this limit only applies to parsing
+ messages, not collections - so a message within a collection within a message only counts as
+ depth 2, not 3.
+
+
+
+
+ The type registry used to parse messages.
+
+
+
+
+ Whether the parser should ignore unknown fields (true) or throw an exception when
+ they are encountered (false).
+
+
+
+
+ Creates a new object with the specified recursion limit.
+
+ The maximum depth of messages to parse
+
+
+
+ Creates a new object with the specified recursion limit and type registry.
+
+ The maximum depth of messages to parse
+ The type registry used to parse messages
+
+
+
+ Creates a new object set to either ignore unknown fields, or throw an exception
+ when unknown fields are encountered.
+
+ true if unknown fields should be ignored when parsing; false to throw an exception.
+
+
+
+ Creates a new object based on this one, but with the specified recursion limit.
+
+ The new recursion limit.
+
+
+
+ Creates a new object based on this one, but with the specified type registry.
+
+ The new type registry. Must not be null.
+
+
+
+ Simple but strict JSON tokenizer, rigidly following RFC 7159.
+
+
+
+ This tokenizer is stateful, and only returns "useful" tokens - names, values etc.
+ It does not create tokens for the separator between names and values, or for the comma
+ between values. It validates the token stream as it goes - so callers can assume that the
+ tokens it produces are appropriate. For example, it would never produce "start object, end array."
+
+ Implementation details: the base class handles single token push-back and
+ Not thread-safe.
+
+
+
+
+ Creates a tokenizer that reads from the given text reader.
+
+
+
+
+ Creates a tokenizer that first replays the given list of tokens, then continues reading
+ from another tokenizer. Note that if the returned tokenizer is "pushed back", that does not push back
+ on the continuation tokenizer, or vice versa. Care should be taken when using this method - it was
+ created for the sake of Any parsing.
+
+
+
+
+ Returns the depth of the stack, purely in objects (not collections).
+ Informally, this is the number of remaining unclosed '{' characters we have.
+
+
+
+
+ Returns the next JSON token in the stream. An EndDocument token is returned to indicate the end of the stream,
+ after which point Next() should not be called again.
+
+ This implementation provides single-token buffering, and calls if there is no buffered token.
+ The next token in the stream. This is never null.
+ This method is called after an EndDocument token has been returned
+ The input text does not comply with RFC 7159
+
+
+
+ Returns the next JSON token in the stream, when requested by the base class. (The method delegates
+ to this if it doesn't have a buffered token.)
+
+ This method is called after an EndDocument token has been returned
+ The input text does not comply with RFC 7159
+
+
+
+ Skips the value we're about to read. This must only be called immediately after reading a property name.
+ If the value is an object or an array, the complete object/array is skipped.
+
+
+
+
+ Tokenizer which first exhausts a list of tokens, then consults another tokenizer.
+
+
+
+
+ Tokenizer which does all the *real* work of parsing JSON.
+
+
+
+
+ This method essentially just loops through characters skipping whitespace, validating and
+ changing state (e.g. from ObjectBeforeColon to ObjectAfterColon)
+ until it reaches something which will be a genuine token (e.g. a start object, or a value) at which point
+ it returns the token. Although the method is large, it would be relatively hard to break down further... most
+ of it is the large switch statement, which sometimes returns and sometimes doesn't.
+
+
+
+
+ Reads a string token. It is assumed that the opening " has already been read.
+
+
+
+
+ Reads an escaped character. It is assumed that the leading backslash has already been read.
+
+
+
+
+ Reads an escaped Unicode 4-nybble hex sequence. It is assumed that the leading \u has already been read.
+
+
+
+
+ Consumes a text-only literal, throwing an exception if the read text doesn't match it.
+ It is assumed that the first letter of the literal has already been read.
+
+
+
+
+ Validates that we're in a valid state to read a value (using the given error prefix if necessary)
+ and changes the state to the appropriate one, e.g. ObjectAfterColon to ObjectAfterProperty.
+
+
+
+
+ Pops the top-most container, and sets the state to the appropriate one for the end of a value
+ in the parent container.
+
+
+
+
+ Possible states of the tokenizer.
+
+
+ This is a flags enum purely so we can simply and efficiently represent a set of valid states
+ for checking.
+
+ Each is documented with an example,
+ where ^ represents the current position within the text stream. The examples all use string values,
+ but could be any value, including nested objects/arrays.
+ The complete state of the tokenizer also includes a stack to indicate the contexts (arrays/objects).
+ Any additional notional state of "AfterValue" indicates that a value has been completed, at which
+ point there's an immediate transition to ExpectedEndOfDocument, ObjectAfterProperty or ArrayAfterValue.
+
+
+ These states were derived manually by reading RFC 7159 carefully.
+
+
+
+
+
+ ^ { "foo": "bar" }
+ Before the value in a document. Next states: ObjectStart, ArrayStart, "AfterValue"
+
+
+
+
+ { "foo": "bar" } ^
+ After the value in a document. Next states: ReaderExhausted
+
+
+
+
+ { "foo": "bar" } ^ (and already read to the end of the reader)
+ Terminal state.
+
+
+
+
+ { ^ "foo": "bar" }
+ Before the *first* property in an object.
+ Next states:
+ "AfterValue" (empty object)
+ ObjectBeforeColon (read a name)
+
+
+
+
+ { "foo" ^ : "bar", "x": "y" }
+ Next state: ObjectAfterColon
+
+
+
+
+ { "foo" : ^ "bar", "x": "y" }
+ Before any property other than the first in an object.
+ (Equivalently: after any property in an object)
+ Next states:
+ "AfterValue" (value is simple)
+ ObjectStart (value is object)
+ ArrayStart (value is array)
+
+
+
+
+ { "foo" : "bar" ^ , "x" : "y" }
+ At the end of a property, so expecting either a comma or end-of-object
+ Next states: ObjectAfterComma or "AfterValue"
+
+
+
+
+ { "foo":"bar", ^ "x":"y" }
+ Read the comma after the previous property, so expecting another property.
+ This is like ObjectStart, but closing brace isn't valid here
+ Next state: ObjectBeforeColon.
+
+
+
+
+ [ ^ "foo", "bar" ]
+ Before the *first* value in an array.
+ Next states:
+ "AfterValue" (read a value)
+ "AfterValue" (end of array; will pop stack)
+
+
+
+
+ [ "foo" ^ , "bar" ]
+ After any value in an array, so expecting either a comma or end-of-array
+ Next states: ArrayAfterComma or "AfterValue"
+
+
+
+
+ [ "foo", ^ "bar" ]
+ After a comma in an array, so there *must* be another value (simple or complex).
+ Next states: "AfterValue" (simple value), StartObject, StartArray
+
+
+
+
+ Wrapper around a text reader allowing small amounts of buffering and location handling.
+
+
+
+
+ The buffered next character, if we have one.
+
+
+
+
+ Returns the next character in the stream, or null if we have reached the end.
+
+
+
+
+
+ Creates a new exception appropriate for the current state of the reader.
+
+
+
+
+ Stream implementation which proxies another stream, only allowing a certain amount
+ of data to be read. Note that this is only used to read delimited streams, so it
+ doesn't attempt to implement everything.
+
+
+
+
+ Extension methods on and .
+
+
+
+
+ Merges data from the given byte array into an existing message.
+
+ The message to merge the data into.
+ The data to merge, which must be protobuf-encoded binary data.
+
+
+
+ Merges data from the given byte array slice into an existing message.
+
+ The message to merge the data into.
+ The data containing the slice to merge, which must be protobuf-encoded binary data.
+ The offset of the slice to merge.
+ The length of the slice to merge.
+
+
+
+ Merges data from the given byte string into an existing message.
+
+ The message to merge the data into.
+ The data to merge, which must be protobuf-encoded binary data.
+
+
+
+ Merges data from the given stream into an existing message.
+
+ The message to merge the data into.
+ Stream containing the data to merge, which must be protobuf-encoded binary data.
+
+
+
+ Merges length-delimited data from the given stream into an existing message.
+
+
+ The stream is expected to contain a length and then the data. Only the amount of data
+ specified by the length will be consumed.
+
+ The message to merge the data into.
+ Stream containing the data to merge, which must be protobuf-encoded binary data.
+
+
+
+ Converts the given message into a byte array in protobuf encoding.
+
+ The message to convert.
+ The message data as a byte array.
+
+
+
+ Writes the given message data to the given stream in protobuf encoding.
+
+ The message to write to the stream.
+ The stream to write to.
+
+
+
+ Writes the length and then data of the given message to a stream.
+
+ The message to write.
+ The output stream to write to.
+
+
+
+ Converts the given message into a byte string in protobuf encoding.
+
+ The message to convert.
+ The message data as a byte string.
+
+
+
+ Writes the given message data to the given buffer writer in protobuf encoding.
+
+ The message to write to the stream.
+ The stream to write to.
+
+
+
+ Writes the given message data to the given span in protobuf encoding.
+ The size of the destination span needs to fit the serialized size
+ of the message exactly, otherwise an exception is thrown.
+
+ The message to write to the stream.
+ The span to write to. Size must match size of the message exactly.
+
+
+
+ Checks if all required fields in a message have values set. For proto3 messages, this returns true
+
+
+
+
+ A general message parser, typically used by reflection-based code as all the methods
+ return simple .
+
+
+
+
+ Creates a template instance ready for population.
+
+ An empty message.
+
+
+
+ Parses a message from a byte array.
+
+ The byte array containing the message. Must not be null.
+ The newly parsed message.
+
+
+
+ Parses a message from a byte array slice.
+
+ The byte array containing the message. Must not be null.
+ The offset of the slice to parse.
+ The length of the slice to parse.
+ The newly parsed message.
+
+
+
+ Parses a message from the given byte string.
+
+ The data to parse.
+ The parsed message.
+
+
+
+ Parses a message from the given stream.
+
+ The stream to parse.
+ The parsed message.
+
+
+
+ Parses a message from the given sequence.
+
+ The data to parse.
+ The parsed message.
+
+
+
+ Parses a length-delimited message from the given stream.
+
+
+ The stream is expected to contain a length and then the data. Only the amount of data
+ specified by the length will be consumed.
+
+ The stream to parse.
+ The parsed message.
+
+
+
+ Parses a message from the given coded input stream.
+
+ The stream to parse.
+ The parsed message.
+
+
+
+ Parses a message from the given JSON.
+
+ The JSON to parse.
+ The parsed message.
+ The JSON does not comply with RFC 7159
+ The JSON does not represent a Protocol Buffers message correctly
+
+
+
+ Creates a new message parser which optionally discards unknown fields when parsing.
+
+ Whether or not to discard unknown fields when parsing.
+ A newly configured message parser.
+
+
+
+ Creates a new message parser which registers extensions from the specified registry upon creating the message instance
+
+ The extensions to register
+ A newly configured message parser.
+
+
+
+ A parser for a specific message type.
+
+
+
+ This delegates most behavior to the
+ implementation within the original type, but
+ provides convenient overloads to parse from a variety of sources.
+
+
+ Most applications will never need to create their own instances of this type;
+ instead, use the static Parser property of a generated message type to obtain a
+ parser for that type.
+
+ */
+ public string GetTime()
+ {
+ //
+ // standardise the format.
+ //
+ if (time[time.Length - 1] == 'Z')
+ {
+ return time.Substring(0, time.Length - 1) + "GMT+00:00";
+ }
+ else
+ {
+ int signPos = time.Length - 5;
+ char sign = time[signPos];
+ if (sign == '-' || sign == '+')
+ {
+ return time.Substring(0, signPos)
+ + "GMT"
+ + time.Substring(signPos, 3)
+ + ":"
+ + time.Substring(signPos + 3);
+ }
+ else
+ {
+ signPos = time.Length - 3;
+ sign = time[signPos];
+ if (sign == '-' || sign == '+')
+ {
+ return time.Substring(0, signPos)
+ + "GMT"
+ + time.Substring(signPos)
+ + ":00";
+ }
+ }
+ }
+
+ return time + CalculateGmtOffset();
+ }
+
+ private string CalculateGmtOffset()
+ {
+ char sign = '+';
+ DateTime time = ToDateTime();
+
+#if SILVERLIGHT || PORTABLE || NETFX_CORE
+ long offset = time.Ticks - time.ToUniversalTime().Ticks;
+ if (offset < 0)
+ {
+ sign = '-';
+ offset = -offset;
+ }
+ int hours = (int)(offset / TimeSpan.TicksPerHour);
+ int minutes = (int)(offset / TimeSpan.TicksPerMinute) % 60;
+#else
+ // Note: GetUtcOffset incorporates Daylight Savings offset
+ TimeSpan offset = TimeZone.CurrentTimeZone.GetUtcOffset(time);
+ if (offset.CompareTo(TimeSpan.Zero) < 0)
+ {
+ sign = '-';
+ offset = offset.Duration();
+ }
+ int hours = offset.Hours;
+ int minutes = offset.Minutes;
+#endif
+
+ return "GMT" + sign + Convert(hours) + ":" + Convert(minutes);
+ }
+
+ private static string Convert(
+ int time)
+ {
+ if (time < 10)
+ {
+ return "0" + time;
+ }
+
+ return time.ToString();
+ }
+
+ public DateTime ToDateTime()
+ {
+ string formatStr;
+ string d = time;
+ bool makeUniversal = false;
+
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(d, "Z"))
+ {
+ if (HasFractionalSeconds)
+ {
+ int fCount = d.Length - d.IndexOf('.') - 2;
+ formatStr = @"yyyyMMddHHmmss." + FString(fCount) + @"\Z";
+ }
+ else
+ {
+ formatStr = @"yyyyMMddHHmmss\Z";
+ }
+ }
+ else if (time.IndexOf('-') > 0 || time.IndexOf('+') > 0)
+ {
+ d = GetTime();
+ makeUniversal = true;
+
+ if (HasFractionalSeconds)
+ {
+ int fCount = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.IndexOf(d, "GMT") - 1 - d.IndexOf('.');
+ formatStr = @"yyyyMMddHHmmss." + FString(fCount) + @"'GMT'zzz";
+ }
+ else
+ {
+ formatStr = @"yyyyMMddHHmmss'GMT'zzz";
+ }
+ }
+ else
+ {
+ if (HasFractionalSeconds)
+ {
+ int fCount = d.Length - 1 - d.IndexOf('.');
+ formatStr = @"yyyyMMddHHmmss." + FString(fCount);
+ }
+ else
+ {
+ formatStr = @"yyyyMMddHHmmss";
+ }
+
+ // TODO?
+// dateF.setTimeZone(new SimpleTimeZone(0, TimeZone.getDefault().getID()));
+ }
+
+ return ParseDateString(d, formatStr, makeUniversal);
+ }
+
+ private string FString(
+ int count)
+ {
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < count; ++i)
+ {
+ sb.Append('f');
+ }
+ return sb.ToString();
+ }
+
+ private DateTime ParseDateString(string s, string format, bool makeUniversal)
+ {
+ /*
+ * NOTE: DateTime.Kind and DateTimeStyles.AssumeUniversal not available in .NET 1.1
+ */
+ DateTimeStyles style = DateTimeStyles.None;
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(format, "Z"))
+ {
+ try
+ {
+ style = (DateTimeStyles)Enums.GetEnumValue(typeof(DateTimeStyles), "AssumeUniversal");
+ }
+ catch (Exception)
+ {
+ }
+
+ style |= DateTimeStyles.AdjustToUniversal;
+ }
+
+ DateTime dt = DateTime.ParseExact(s, format, DateTimeFormatInfo.InvariantInfo, style);
+
+ return makeUniversal ? dt.ToUniversalTime() : dt;
+ }
+
+ private bool HasFractionalSeconds
+ {
+ get { return time.IndexOf('.') == 14; }
+ }
+
+ private byte[] GetOctets()
+ {
+ return Strings.ToAsciiByteArray(time);
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.GeneralizedTime, GetOctets());
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerGeneralizedTime other = asn1Object as DerGeneralizedTime;
+
+ if (other == null)
+ return false;
+
+ return this.time.Equals(other.time);
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ return time.GetHashCode();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerGeneralizedTime.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerGeneralizedTime.cs.meta
new file mode 100644
index 00000000..b7a2d0f0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerGeneralizedTime.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 1ebcc047ba1daf04db5d2ebd9c124a28
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerGraphicString.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerGraphicString.cs
new file mode 100644
index 00000000..08a518aa
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerGraphicString.cs
@@ -0,0 +1,107 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1
+{
+ public class DerGraphicString
+ : DerStringBase
+ {
+ private readonly byte[] mString;
+
+ /**
+ * return a Graphic String from the passed in object
+ *
+ * @param obj a DerGraphicString or an object that can be converted into one.
+ * @exception IllegalArgumentException if the object cannot be converted.
+ * @return a DerGraphicString instance, or null.
+ */
+ public static DerGraphicString GetInstance(object obj)
+ {
+ if (obj == null || obj is DerGraphicString)
+ {
+ return (DerGraphicString)obj;
+ }
+
+ if (obj is byte[])
+ {
+ try
+ {
+ return (DerGraphicString)FromByteArray((byte[])obj);
+ }
+ catch (Exception e)
+ {
+ throw new ArgumentException("encoding error in GetInstance: " + e.ToString(), "obj");
+ }
+ }
+
+ throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+ }
+
+ /**
+ * return a Graphic String from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want
+ * @param explicit true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception IllegalArgumentException if the tagged object cannot
+ * be converted.
+ * @return a DerGraphicString instance, or null.
+ */
+ public static DerGraphicString GetInstance(Asn1TaggedObject obj, bool isExplicit)
+ {
+ Asn1Object o = obj.GetObject();
+
+ if (isExplicit || o is DerGraphicString)
+ {
+ return GetInstance(o);
+ }
+
+ return new DerGraphicString(((Asn1OctetString)o).GetOctets());
+ }
+
+ /**
+ * basic constructor - with bytes.
+ * @param string the byte encoding of the characters making up the string.
+ */
+ public DerGraphicString(byte[] encoding)
+ {
+ this.mString = Arrays.Clone(encoding);
+ }
+
+ public override string GetString()
+ {
+ return Strings.FromByteArray(mString);
+ }
+
+ public byte[] GetOctets()
+ {
+ return Arrays.Clone(mString);
+ }
+
+ internal override void Encode(DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.GraphicString, mString);
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ return Arrays.GetHashCode(mString);
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerGraphicString other = asn1Object as DerGraphicString;
+
+ if (other == null)
+ return false;
+
+ return Arrays.AreEqual(mString, other.mString);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerGraphicString.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerGraphicString.cs.meta
new file mode 100644
index 00000000..80a2f5ce
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerGraphicString.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: f18e39588618e334c961eec4c763ef13
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerIA5String.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerIA5String.cs
new file mode 100644
index 00000000..2089d6c4
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerIA5String.cs
@@ -0,0 +1,149 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1
+{
+ /**
+ * Der IA5String object - this is an ascii string.
+ */
+ public class DerIA5String
+ : DerStringBase
+ {
+ private readonly string str;
+
+ /**
+ * return a IA5 string from the passed in object
+ *
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static DerIA5String GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is DerIA5String)
+ {
+ return (DerIA5String)obj;
+ }
+
+ throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj));
+ }
+
+ /**
+ * return an IA5 string from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want
+ * @param explicitly true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static DerIA5String GetInstance(
+ Asn1TaggedObject obj,
+ bool isExplicit)
+ {
+ Asn1Object o = obj.GetObject();
+
+ if (isExplicit || o is DerIA5String)
+ {
+ return GetInstance(o);
+ }
+
+ return new DerIA5String(((Asn1OctetString)o).GetOctets());
+ }
+
+ /**
+ * basic constructor - with bytes.
+ */
+ public DerIA5String(
+ byte[] str)
+ : this(Strings.FromAsciiByteArray(str), false)
+ {
+ }
+
+ /**
+ * basic constructor - without validation.
+ */
+ public DerIA5String(
+ string str)
+ : this(str, false)
+ {
+ }
+
+ /**
+ * Constructor with optional validation.
+ *
+ * @param string the base string to wrap.
+ * @param validate whether or not to check the string.
+ * @throws ArgumentException if validate is true and the string
+ * contains characters that should not be in an IA5String.
+ */
+ public DerIA5String(
+ string str,
+ bool validate)
+ {
+ if (str == null)
+ throw new ArgumentNullException("str");
+ if (validate && !IsIA5String(str))
+ throw new ArgumentException("string contains illegal characters", "str");
+
+ this.str = str;
+ }
+
+ public override string GetString()
+ {
+ return str;
+ }
+
+ public byte[] GetOctets()
+ {
+ return Strings.ToAsciiByteArray(str);
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.IA5String, GetOctets());
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ return this.str.GetHashCode();
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerIA5String other = asn1Object as DerIA5String;
+
+ if (other == null)
+ return false;
+
+ return this.str.Equals(other.str);
+ }
+
+ /**
+ * return true if the passed in String can be represented without
+ * loss as an IA5String, false otherwise.
+ *
+ * @return true if in printable set, false otherwise.
+ */
+ public static bool IsIA5String(
+ string str)
+ {
+ foreach (char ch in str)
+ {
+ if (ch > 0x007f)
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerIA5String.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerIA5String.cs.meta
new file mode 100644
index 00000000..286717d9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerIA5String.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 92ba1c46247b34d4b83218ac4a011b9e
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerInteger.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerInteger.cs
new file mode 100644
index 00000000..099ead44
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerInteger.cs
@@ -0,0 +1,138 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1
+{
+ public class DerInteger
+ : Asn1Object
+ {
+ public const string AllowUnsafeProperty = "BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.AllowUnsafeInteger";
+
+ internal static bool AllowUnsafe()
+ {
+ string allowUnsafeValue = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetEnvironmentVariable(AllowUnsafeProperty);
+ return allowUnsafeValue != null && BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase("true", allowUnsafeValue);
+ }
+
+ private readonly byte[] bytes;
+
+ /**
+ * return an integer from the passed in object
+ *
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static DerInteger GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is DerInteger)
+ {
+ return (DerInteger)obj;
+ }
+
+ throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj));
+ }
+
+ /**
+ * return an Integer from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want
+ * @param isExplicit true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static DerInteger GetInstance(
+ Asn1TaggedObject obj,
+ bool isExplicit)
+ {
+ if (obj == null)
+ throw new ArgumentNullException("obj");
+
+ Asn1Object o = obj.GetObject();
+
+ if (isExplicit || o is DerInteger)
+ {
+ return GetInstance(o);
+ }
+
+ return new DerInteger(Asn1OctetString.GetInstance(o).GetOctets());
+ }
+
+ public DerInteger(
+ int value)
+ {
+ bytes = BigInteger.ValueOf(value).ToByteArray();
+ }
+
+ public DerInteger(
+ BigInteger value)
+ {
+ if (value == null)
+ throw new ArgumentNullException("value");
+
+ bytes = value.ToByteArray();
+ }
+
+ public DerInteger(
+ byte[] bytes)
+ {
+ if (bytes.Length > 1)
+ {
+ if ((bytes[0] == 0 && (bytes[1] & 0x80) == 0)
+ || (bytes[0] == (byte)0xff && (bytes[1] & 0x80) != 0))
+ {
+ if (!AllowUnsafe())
+ throw new ArgumentException("malformed integer");
+ }
+ }
+ this.bytes = Arrays.Clone(bytes);
+ }
+
+ public BigInteger Value
+ {
+ get { return new BigInteger(bytes); }
+ }
+
+ /**
+ * in some cases positive values Get crammed into a space,
+ * that's not quite big enough...
+ */
+ public BigInteger PositiveValue
+ {
+ get { return new BigInteger(1, bytes); }
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.Integer, bytes);
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ return Arrays.GetHashCode(bytes);
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerInteger other = asn1Object as DerInteger;
+
+ if (other == null)
+ return false;
+
+ return Arrays.AreEqual(this.bytes, other.bytes);
+ }
+
+ public override string ToString()
+ {
+ return Value.ToString();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerInteger.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerInteger.cs.meta
new file mode 100644
index 00000000..7492aca5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerInteger.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ae09d83855723bc498fdae7631d51686
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerNull.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerNull.cs
new file mode 100644
index 00000000..97894bf6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerNull.cs
@@ -0,0 +1,45 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1
+{
+ /**
+ * A Null object.
+ */
+ public class DerNull
+ : Asn1Null
+ {
+ public static readonly DerNull Instance = new DerNull(0);
+
+ byte[] zeroBytes = new byte[0];
+
+ [Obsolete("Use static Instance object")]
+ public DerNull()
+ {
+ }
+
+ protected internal DerNull(int dummy)
+ {
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.Null, zeroBytes);
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ return asn1Object is DerNull;
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ return -1;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerNull.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerNull.cs.meta
new file mode 100644
index 00000000..6513dbce
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerNull.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 48eba232a4b25614c941a9adb09edc24
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerNumericString.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerNumericString.cs
new file mode 100644
index 00000000..d3939505
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerNumericString.cs
@@ -0,0 +1,142 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1
+{
+ /**
+ * Der NumericString object - this is an ascii string of characters {0,1,2,3,4,5,6,7,8,9, }.
+ */
+ public class DerNumericString
+ : DerStringBase
+ {
+ private readonly string str;
+
+ /**
+ * return a Numeric string from the passed in object
+ *
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static DerNumericString GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is DerNumericString)
+ {
+ return (DerNumericString)obj;
+ }
+
+ throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj));
+ }
+
+ /**
+ * return an Numeric string from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want
+ * @param explicitly true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static DerNumericString GetInstance(
+ Asn1TaggedObject obj,
+ bool isExplicit)
+ {
+ Asn1Object o = obj.GetObject();
+
+ if (isExplicit || o is DerNumericString)
+ {
+ return GetInstance(o);
+ }
+
+ return new DerNumericString(Asn1OctetString.GetInstance(o).GetOctets());
+ }
+
+ /**
+ * basic constructor - with bytes.
+ */
+ public DerNumericString(
+ byte[] str)
+ : this(Strings.FromAsciiByteArray(str), false)
+ {
+ }
+
+ /**
+ * basic constructor - without validation..
+ */
+ public DerNumericString(
+ string str)
+ : this(str, false)
+ {
+ }
+
+ /**
+ * Constructor with optional validation.
+ *
+ * @param string the base string to wrap.
+ * @param validate whether or not to check the string.
+ * @throws ArgumentException if validate is true and the string
+ * contains characters that should not be in a NumericString.
+ */
+ public DerNumericString(
+ string str,
+ bool validate)
+ {
+ if (str == null)
+ throw new ArgumentNullException("str");
+ if (validate && !IsNumericString(str))
+ throw new ArgumentException("string contains illegal characters", "str");
+
+ this.str = str;
+ }
+
+ public override string GetString()
+ {
+ return str;
+ }
+
+ public byte[] GetOctets()
+ {
+ return Strings.ToAsciiByteArray(str);
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.NumericString, GetOctets());
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerNumericString other = asn1Object as DerNumericString;
+
+ if (other == null)
+ return false;
+
+ return this.str.Equals(other.str);
+ }
+
+ /**
+ * Return true if the string can be represented as a NumericString ('0'..'9', ' ')
+ *
+ * @param str string to validate.
+ * @return true if numeric, fale otherwise.
+ */
+ public static bool IsNumericString(
+ string str)
+ {
+ foreach (char ch in str)
+ {
+ if (ch > 0x007f || (ch != ' ' && !char.IsDigit(ch)))
+ return false;
+ }
+
+ return true;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerNumericString.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerNumericString.cs.meta
new file mode 100644
index 00000000..3cc5a3bf
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerNumericString.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: b0707908aca9e6943ba955d46365d37e
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerObjectIdentifier.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerObjectIdentifier.cs
new file mode 100644
index 00000000..3d160bf4
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerObjectIdentifier.cs
@@ -0,0 +1,358 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+using System.Text;
+using System.Text.RegularExpressions;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1
+{
+ public class DerObjectIdentifier
+ : Asn1Object
+ {
+ private readonly string identifier;
+
+ private byte[] body = null;
+
+ /**
+ * return an Oid from the passed in object
+ *
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static DerObjectIdentifier GetInstance(object obj)
+ {
+ if (obj == null || obj is DerObjectIdentifier)
+ return (DerObjectIdentifier) obj;
+ if (obj is byte[])
+ return FromOctetString((byte[])obj);
+ throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+ }
+
+ /**
+ * return an object Identifier from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want
+ * @param explicitly true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static DerObjectIdentifier GetInstance(
+ Asn1TaggedObject obj,
+ bool explicitly)
+ {
+ Asn1Object o = obj.GetObject();
+
+ if (explicitly || o is DerObjectIdentifier)
+ {
+ return GetInstance(o);
+ }
+
+ return FromOctetString(Asn1OctetString.GetInstance(o).GetOctets());
+ }
+
+ public DerObjectIdentifier(
+ string identifier)
+ {
+ if (identifier == null)
+ throw new ArgumentNullException("identifier");
+ if (!IsValidIdentifier(identifier))
+ throw new FormatException("string " + identifier + " not an OID");
+
+ this.identifier = identifier;
+ }
+
+ internal DerObjectIdentifier(DerObjectIdentifier oid, string branchID)
+ {
+ if (!IsValidBranchID(branchID, 0))
+ throw new ArgumentException("string " + branchID + " not a valid OID branch", "branchID");
+
+ this.identifier = oid.Id + "." + branchID;
+ }
+
+ // TODO Change to ID?
+ public string Id
+ {
+ get { return identifier; }
+ }
+
+ public virtual DerObjectIdentifier Branch(string branchID)
+ {
+ return new DerObjectIdentifier(this, branchID);
+ }
+
+ /**
+ * Return true if this oid is an extension of the passed in branch, stem.
+ * @param stem the arc or branch that is a possible parent.
+ * @return true if the branch is on the passed in stem, false otherwise.
+ */
+ public virtual bool On(DerObjectIdentifier stem)
+ {
+ string id = Id, stemId = stem.Id;
+ return id.Length > stemId.Length && id[stemId.Length] == '.' && BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(id, stemId);
+ }
+
+ internal DerObjectIdentifier(byte[] bytes)
+ {
+ this.identifier = MakeOidStringFromBytes(bytes);
+ this.body = Arrays.Clone(bytes);
+ }
+
+ private void WriteField(
+ Stream outputStream,
+ long fieldValue)
+ {
+ byte[] result = new byte[9];
+ int pos = 8;
+ result[pos] = (byte)(fieldValue & 0x7f);
+ while (fieldValue >= (1L << 7))
+ {
+ fieldValue >>= 7;
+ result[--pos] = (byte)((fieldValue & 0x7f) | 0x80);
+ }
+ outputStream.Write(result, pos, 9 - pos);
+ }
+
+ private void WriteField(
+ Stream outputStream,
+ BigInteger fieldValue)
+ {
+ int byteCount = (fieldValue.BitLength + 6) / 7;
+ if (byteCount == 0)
+ {
+ outputStream.WriteByte(0);
+ }
+ else
+ {
+ BigInteger tmpValue = fieldValue;
+ byte[] tmp = new byte[byteCount];
+ for (int i = byteCount-1; i >= 0; i--)
+ {
+ tmp[i] = (byte) ((tmpValue.IntValue & 0x7f) | 0x80);
+ tmpValue = tmpValue.ShiftRight(7);
+ }
+ tmp[byteCount-1] &= 0x7f;
+ outputStream.Write(tmp, 0, tmp.Length);
+ }
+ }
+
+ private void DoOutput(MemoryStream bOut)
+ {
+ OidTokenizer tok = new OidTokenizer(identifier);
+
+ string token = tok.NextToken();
+ int first = int.Parse(token) * 40;
+
+ token = tok.NextToken();
+ if (token.Length <= 18)
+ {
+ WriteField(bOut, first + Int64.Parse(token));
+ }
+ else
+ {
+ WriteField(bOut, new BigInteger(token).Add(BigInteger.ValueOf(first)));
+ }
+
+ while (tok.HasMoreTokens)
+ {
+ token = tok.NextToken();
+ if (token.Length <= 18)
+ {
+ WriteField(bOut, Int64.Parse(token));
+ }
+ else
+ {
+ WriteField(bOut, new BigInteger(token));
+ }
+ }
+ }
+
+ internal byte[] GetBody()
+ {
+ lock (this)
+ {
+ if (body == null)
+ {
+ MemoryStream bOut = new MemoryStream();
+ DoOutput(bOut);
+ body = bOut.ToArray();
+ }
+ }
+
+ return body;
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.ObjectIdentifier, GetBody());
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ return identifier.GetHashCode();
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerObjectIdentifier other = asn1Object as DerObjectIdentifier;
+
+ if (other == null)
+ return false;
+
+ return this.identifier.Equals(other.identifier);
+ }
+
+ public override string ToString()
+ {
+ return identifier;
+ }
+
+ private static bool IsValidBranchID(
+ String branchID, int start)
+ {
+ bool periodAllowed = false;
+
+ int pos = branchID.Length;
+ while (--pos >= start)
+ {
+ char ch = branchID[pos];
+
+ // TODO Leading zeroes?
+ if ('0' <= ch && ch <= '9')
+ {
+ periodAllowed = true;
+ continue;
+ }
+
+ if (ch == '.')
+ {
+ if (!periodAllowed)
+ return false;
+
+ periodAllowed = false;
+ continue;
+ }
+
+ return false;
+ }
+
+ return periodAllowed;
+ }
+
+ private static bool IsValidIdentifier(string identifier)
+ {
+ if (identifier.Length < 3 || identifier[1] != '.')
+ return false;
+
+ char first = identifier[0];
+ if (first < '0' || first > '2')
+ return false;
+
+ return IsValidBranchID(identifier, 2);
+ }
+
+ private const long LONG_LIMIT = (long.MaxValue >> 7) - 0x7f;
+
+ private static string MakeOidStringFromBytes(
+ byte[] bytes)
+ {
+ StringBuilder objId = new StringBuilder();
+ long value = 0;
+ BigInteger bigValue = null;
+ bool first = true;
+
+ for (int i = 0; i != bytes.Length; i++)
+ {
+ int b = bytes[i];
+
+ if (value <= LONG_LIMIT)
+ {
+ value += (b & 0x7f);
+ if ((b & 0x80) == 0) // end of number reached
+ {
+ if (first)
+ {
+ if (value < 40)
+ {
+ objId.Append('0');
+ }
+ else if (value < 80)
+ {
+ objId.Append('1');
+ value -= 40;
+ }
+ else
+ {
+ objId.Append('2');
+ value -= 80;
+ }
+ first = false;
+ }
+
+ objId.Append('.');
+ objId.Append(value);
+ value = 0;
+ }
+ else
+ {
+ value <<= 7;
+ }
+ }
+ else
+ {
+ if (bigValue == null)
+ {
+ bigValue = BigInteger.ValueOf(value);
+ }
+ bigValue = bigValue.Or(BigInteger.ValueOf(b & 0x7f));
+ if ((b & 0x80) == 0)
+ {
+ if (first)
+ {
+ objId.Append('2');
+ bigValue = bigValue.Subtract(BigInteger.ValueOf(80));
+ first = false;
+ }
+
+ objId.Append('.');
+ objId.Append(bigValue);
+ bigValue = null;
+ value = 0;
+ }
+ else
+ {
+ bigValue = bigValue.ShiftLeft(7);
+ }
+ }
+ }
+
+ return objId.ToString();
+ }
+
+ private static readonly DerObjectIdentifier[] cache = new DerObjectIdentifier[1024];
+
+ internal static DerObjectIdentifier FromOctetString(byte[] enc)
+ {
+ int hashCode = Arrays.GetHashCode(enc);
+ int first = hashCode & 1023;
+
+ lock (cache)
+ {
+ DerObjectIdentifier entry = cache[first];
+ if (entry != null && Arrays.AreEqual(enc, entry.GetBody()))
+ {
+ return entry;
+ }
+
+ return cache[first] = new DerObjectIdentifier(enc);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerObjectIdentifier.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerObjectIdentifier.cs.meta
new file mode 100644
index 00000000..d76bd72a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerObjectIdentifier.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 44d9a2bc67c903f468455f944abaccfc
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerOctetString.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerOctetString.cs
new file mode 100644
index 00000000..4b59c167
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerOctetString.cs
@@ -0,0 +1,38 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1
+{
+ public class DerOctetString
+ : Asn1OctetString
+ {
+ /// The octets making up the octet string.
+ public DerOctetString(
+ byte[] str)
+ : base(str)
+ {
+ }
+
+ public DerOctetString(
+ Asn1Encodable obj)
+ : base(obj)
+ {
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.OctetString, str);
+ }
+
+ internal static void Encode(
+ DerOutputStream derOut,
+ byte[] bytes,
+ int offset,
+ int length)
+ {
+ derOut.WriteEncoded(Asn1Tags.OctetString, bytes, offset, length);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerOctetString.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerOctetString.cs.meta
new file mode 100644
index 00000000..3a2f33f6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerOctetString.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 8d4f36a04b2ccfc478c9e105de48f09f
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerOutputStream.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerOutputStream.cs
new file mode 100644
index 00000000..2b610cab
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerOutputStream.cs
@@ -0,0 +1,175 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1
+{
+ public class DerOutputStream
+ : FilterStream
+ {
+ public DerOutputStream(Stream os)
+ : base(os)
+ {
+ }
+
+ private void WriteLength(
+ int length)
+ {
+ if (length > 127)
+ {
+ int size = 1;
+ uint val = (uint)length;
+
+ while ((val >>= 8) != 0)
+ {
+ size++;
+ }
+
+ WriteByte((byte)(size | 0x80));
+
+ for (int i = (size - 1) * 8; i >= 0; i -= 8)
+ {
+ WriteByte((byte)(length >> i));
+ }
+ }
+ else
+ {
+ WriteByte((byte)length);
+ }
+ }
+
+ internal void WriteEncoded(
+ int tag,
+ byte[] bytes)
+ {
+ WriteByte((byte)tag);
+ WriteLength(bytes.Length);
+ Write(bytes, 0, bytes.Length);
+ }
+
+ internal void WriteEncoded(
+ int tag,
+ byte first,
+ byte[] bytes)
+ {
+ WriteByte((byte)tag);
+ WriteLength(bytes.Length + 1);
+ WriteByte(first);
+ Write(bytes, 0, bytes.Length);
+ }
+
+ internal void WriteEncoded(
+ int tag,
+ byte[] bytes,
+ int offset,
+ int length)
+ {
+ WriteByte((byte)tag);
+ WriteLength(length);
+ Write(bytes, offset, length);
+ }
+
+ internal void WriteTag(
+ int flags,
+ int tagNo)
+ {
+ if (tagNo < 31)
+ {
+ WriteByte((byte)(flags | tagNo));
+ }
+ else
+ {
+ WriteByte((byte)(flags | 0x1f));
+ if (tagNo < 128)
+ {
+ WriteByte((byte)tagNo);
+ }
+ else
+ {
+ byte[] stack = new byte[5];
+ int pos = stack.Length;
+
+ stack[--pos] = (byte)(tagNo & 0x7F);
+
+ do
+ {
+ tagNo >>= 7;
+ stack[--pos] = (byte)(tagNo & 0x7F | 0x80);
+ }
+ while (tagNo > 127);
+
+ Write(stack, pos, stack.Length - pos);
+ }
+ }
+ }
+
+ internal void WriteEncoded(
+ int flags,
+ int tagNo,
+ byte[] bytes)
+ {
+ WriteTag(flags, tagNo);
+ WriteLength(bytes.Length);
+ Write(bytes, 0, bytes.Length);
+ }
+
+ protected void WriteNull()
+ {
+ WriteByte(Asn1Tags.Null);
+ WriteByte(0x00);
+ }
+
+ [Obsolete("Use version taking an Asn1Encodable arg instead")]
+ public virtual void WriteObject(
+ object obj)
+ {
+ if (obj == null)
+ {
+ WriteNull();
+ }
+ else if (obj is Asn1Object)
+ {
+ ((Asn1Object)obj).Encode(this);
+ }
+ else if (obj is Asn1Encodable)
+ {
+ ((Asn1Encodable)obj).ToAsn1Object().Encode(this);
+ }
+ else
+ {
+ throw new IOException("object not Asn1Object");
+ }
+ }
+
+ public virtual void WriteObject(
+ Asn1Encodable obj)
+ {
+ if (obj == null)
+ {
+ WriteNull();
+ }
+ else
+ {
+ obj.ToAsn1Object().Encode(this);
+ }
+ }
+
+ public virtual void WriteObject(
+ Asn1Object obj)
+ {
+ if (obj == null)
+ {
+ WriteNull();
+ }
+ else
+ {
+ obj.Encode(this);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerOutputStream.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerOutputStream.cs.meta
new file mode 100644
index 00000000..68f7bbb1
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerOutputStream.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: b1bb944f8dee86942a8e2fb0c5c9520c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerPrintableString.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerPrintableString.cs
new file mode 100644
index 00000000..d510d974
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerPrintableString.cs
@@ -0,0 +1,167 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1
+{
+ /**
+ * Der PrintableString object.
+ */
+ public class DerPrintableString
+ : DerStringBase
+ {
+ private readonly string str;
+
+ /**
+ * return a printable string from the passed in object.
+ *
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static DerPrintableString GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is DerPrintableString)
+ {
+ return (DerPrintableString)obj;
+ }
+
+ throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj));
+ }
+
+ /**
+ * return a Printable string from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want
+ * @param explicitly true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static DerPrintableString GetInstance(
+ Asn1TaggedObject obj,
+ bool isExplicit)
+ {
+ Asn1Object o = obj.GetObject();
+
+ if (isExplicit || o is DerPrintableString)
+ {
+ return GetInstance(o);
+ }
+
+ return new DerPrintableString(Asn1OctetString.GetInstance(o).GetOctets());
+ }
+
+ /**
+ * basic constructor - byte encoded string.
+ */
+ public DerPrintableString(
+ byte[] str)
+ : this(Strings.FromAsciiByteArray(str), false)
+ {
+ }
+
+ /**
+ * basic constructor - this does not validate the string
+ */
+ public DerPrintableString(
+ string str)
+ : this(str, false)
+ {
+ }
+
+ /**
+ * Constructor with optional validation.
+ *
+ * @param string the base string to wrap.
+ * @param validate whether or not to check the string.
+ * @throws ArgumentException if validate is true and the string
+ * contains characters that should not be in a PrintableString.
+ */
+ public DerPrintableString(
+ string str,
+ bool validate)
+ {
+ if (str == null)
+ throw new ArgumentNullException("str");
+ if (validate && !IsPrintableString(str))
+ throw new ArgumentException("string contains illegal characters", "str");
+
+ this.str = str;
+ }
+
+ public override string GetString()
+ {
+ return str;
+ }
+
+ public byte[] GetOctets()
+ {
+ return Strings.ToAsciiByteArray(str);
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.PrintableString, GetOctets());
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerPrintableString other = asn1Object as DerPrintableString;
+
+ if (other == null)
+ return false;
+
+ return this.str.Equals(other.str);
+ }
+
+ /**
+ * return true if the passed in String can be represented without
+ * loss as a PrintableString, false otherwise.
+ *
+ * @return true if in printable set, false otherwise.
+ */
+ public static bool IsPrintableString(
+ string str)
+ {
+ foreach (char ch in str)
+ {
+ if (ch > 0x007f)
+ return false;
+
+ if (char.IsLetterOrDigit(ch))
+ continue;
+
+// if (char.IsPunctuation(ch))
+// continue;
+
+ switch (ch)
+ {
+ case ' ':
+ case '\'':
+ case '(':
+ case ')':
+ case '+':
+ case '-':
+ case '.':
+ case ':':
+ case '=':
+ case '?':
+ case '/':
+ case ',':
+ continue;
+ }
+
+ return false;
+ }
+
+ return true;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerPrintableString.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerPrintableString.cs.meta
new file mode 100644
index 00000000..fedbd301
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerPrintableString.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 1200ec73d3f7fca4aaff102854e1059d
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerSequence.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerSequence.cs
new file mode 100644
index 00000000..876a43d6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerSequence.cs
@@ -0,0 +1,92 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1
+{
+ public class DerSequence
+ : Asn1Sequence
+ {
+ public static readonly DerSequence Empty = new DerSequence();
+
+ public static DerSequence FromVector(
+ Asn1EncodableVector v)
+ {
+ return v.Count < 1 ? Empty : new DerSequence(v);
+ }
+
+ /**
+ * create an empty sequence
+ */
+ public DerSequence()
+ : base(0)
+ {
+ }
+
+ /**
+ * create a sequence containing one object
+ */
+ public DerSequence(
+ Asn1Encodable obj)
+ : base(1)
+ {
+ AddObject(obj);
+ }
+
+ public DerSequence(
+ params Asn1Encodable[] v)
+ : base(v.Length)
+ {
+ foreach (Asn1Encodable ae in v)
+ {
+ AddObject(ae);
+ }
+ }
+
+ /**
+ * create a sequence containing a vector of objects.
+ */
+ public DerSequence(
+ Asn1EncodableVector v)
+ : base(v.Count)
+ {
+ foreach (Asn1Encodable ae in v)
+ {
+ AddObject(ae);
+ }
+ }
+
+ /*
+ * A note on the implementation:
+ *
+ * As Der requires the constructed, definite-length model to
+ * be used for structured types, this varies slightly from the
+ * ASN.1 descriptions given. Rather than just outputing Sequence,
+ * we also have to specify Constructed, and the objects length.
+ */
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ // TODO Intermediate buffer could be avoided if we could calculate expected length
+ MemoryStream bOut = new MemoryStream();
+ DerOutputStream dOut = new DerOutputStream(bOut);
+
+ foreach (Asn1Encodable obj in this)
+ {
+ dOut.WriteObject(obj);
+ }
+
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(dOut);
+
+ byte[] bytes = bOut.ToArray();
+
+ derOut.WriteEncoded(Asn1Tags.Sequence | Asn1Tags.Constructed, bytes);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerSequence.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerSequence.cs.meta
new file mode 100644
index 00000000..6f646b1f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerSequence.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 1ca9f0cbe9fb5c1489017b4d412573eb
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerSet.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerSet.cs
new file mode 100644
index 00000000..72e94224
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerSet.cs
@@ -0,0 +1,115 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1
+{
+ /**
+ * A Der encoded set object
+ */
+ public class DerSet
+ : Asn1Set
+ {
+ public static readonly DerSet Empty = new DerSet();
+
+ public static DerSet FromVector(
+ Asn1EncodableVector v)
+ {
+ return v.Count < 1 ? Empty : new DerSet(v);
+ }
+
+ internal static DerSet FromVector(
+ Asn1EncodableVector v,
+ bool needsSorting)
+ {
+ return v.Count < 1 ? Empty : new DerSet(v, needsSorting);
+ }
+
+ /**
+ * create an empty set
+ */
+ public DerSet()
+ : base(0)
+ {
+ }
+
+ /**
+ * @param obj - a single object that makes up the set.
+ */
+ public DerSet(
+ Asn1Encodable obj)
+ : base(1)
+ {
+ AddObject(obj);
+ }
+
+ public DerSet(
+ params Asn1Encodable[] v)
+ : base(v.Length)
+ {
+ foreach (Asn1Encodable o in v)
+ {
+ AddObject(o);
+ }
+
+ Sort();
+ }
+
+ /**
+ * @param v - a vector of objects making up the set.
+ */
+ public DerSet(
+ Asn1EncodableVector v)
+ : this(v, true)
+ {
+ }
+
+ internal DerSet(
+ Asn1EncodableVector v,
+ bool needsSorting)
+ : base(v.Count)
+ {
+ foreach (Asn1Encodable o in v)
+ {
+ AddObject(o);
+ }
+
+ if (needsSorting)
+ {
+ Sort();
+ }
+ }
+
+ /*
+ * A note on the implementation:
+ *
+ * As Der requires the constructed, definite-length model to
+ * be used for structured types, this varies slightly from the
+ * ASN.1 descriptions given. Rather than just outputing Set,
+ * we also have to specify Constructed, and the objects length.
+ */
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ // TODO Intermediate buffer could be avoided if we could calculate expected length
+ MemoryStream bOut = new MemoryStream();
+ DerOutputStream dOut = new DerOutputStream(bOut);
+
+ foreach (Asn1Encodable obj in this)
+ {
+ dOut.WriteObject(obj);
+ }
+
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(dOut);
+
+ byte[] bytes = bOut.ToArray();
+
+ derOut.WriteEncoded(Asn1Tags.Set | Asn1Tags.Constructed, bytes);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerSet.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerSet.cs.meta
new file mode 100644
index 00000000..eb8e6376
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerSet.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: f364dec2c9a290d44970ffd282c606bc
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerStringBase.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerStringBase.cs
new file mode 100644
index 00000000..fd1c5039
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerStringBase.cs
@@ -0,0 +1,26 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1
+{
+ public abstract class DerStringBase
+ : Asn1Object, IAsn1String
+ {
+ protected DerStringBase()
+ {
+ }
+
+ public abstract string GetString();
+
+ public override string ToString()
+ {
+ return GetString();
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ return GetString().GetHashCode();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerStringBase.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerStringBase.cs.meta
new file mode 100644
index 00000000..8065a32e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerStringBase.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 4ff347a2eb85434458a6035f9c07cb84
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerT61String.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerT61String.cs
new file mode 100644
index 00000000..afc7649e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerT61String.cs
@@ -0,0 +1,106 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1
+{
+ /**
+ * Der T61String (also the teletex string) - 8-bit characters
+ */
+ public class DerT61String
+ : DerStringBase
+ {
+ private readonly string str;
+
+ /**
+ * return a T61 string from the passed in object.
+ *
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static DerT61String GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is DerT61String)
+ {
+ return (DerT61String)obj;
+ }
+
+ throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj));
+ }
+
+ /**
+ * return an T61 string from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want
+ * @param explicitly true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static DerT61String GetInstance(
+ Asn1TaggedObject obj,
+ bool isExplicit)
+ {
+ Asn1Object o = obj.GetObject();
+
+ if (isExplicit || o is DerT61String)
+ {
+ return GetInstance(o);
+ }
+
+ return new DerT61String(Asn1OctetString.GetInstance(o).GetOctets());
+ }
+
+ /**
+ * basic constructor - with bytes.
+ */
+ public DerT61String(
+ byte[] str)
+ : this(Strings.FromByteArray(str))
+ {
+ }
+
+ /**
+ * basic constructor - with string.
+ */
+ public DerT61String(
+ string str)
+ {
+ if (str == null)
+ throw new ArgumentNullException("str");
+
+ this.str = str;
+ }
+
+ public override string GetString()
+ {
+ return str;
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.T61String, GetOctets());
+ }
+
+ public byte[] GetOctets()
+ {
+ return Strings.ToByteArray(str);
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerT61String other = asn1Object as DerT61String;
+
+ if (other == null)
+ return false;
+
+ return this.str.Equals(other.str);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerT61String.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerT61String.cs.meta
new file mode 100644
index 00000000..20d449ec
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerT61String.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 3128101ae52c6af4982834c862464364
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerTaggedObject.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerTaggedObject.cs
new file mode 100644
index 00000000..2fe3afae
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerTaggedObject.cs
@@ -0,0 +1,76 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1
+{
+ /**
+ * DER TaggedObject - in ASN.1 notation this is any object preceded by
+ * a [n] where n is some number - these are assumed to follow the construction
+ * rules (as with sequences).
+ */
+ public class DerTaggedObject
+ : Asn1TaggedObject
+ {
+ /**
+ * @param tagNo the tag number for this object.
+ * @param obj the tagged object.
+ */
+ public DerTaggedObject(
+ int tagNo,
+ Asn1Encodable obj)
+ : base(tagNo, obj)
+ {
+ }
+
+ /**
+ * @param explicitly true if an explicitly tagged object.
+ * @param tagNo the tag number for this object.
+ * @param obj the tagged object.
+ */
+ public DerTaggedObject(
+ bool explicitly,
+ int tagNo,
+ Asn1Encodable obj)
+ : base(explicitly, tagNo, obj)
+ {
+ }
+
+ /**
+ * create an implicitly tagged object that contains a zero
+ * length sequence.
+ */
+ public DerTaggedObject(
+ int tagNo)
+ : base(false, tagNo, DerSequence.Empty)
+ {
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ if (!IsEmpty())
+ {
+ byte[] bytes = obj.GetDerEncoded();
+
+ if (explicitly)
+ {
+ derOut.WriteEncoded(Asn1Tags.Constructed | Asn1Tags.Tagged, tagNo, bytes);
+ }
+ else
+ {
+ //
+ // need to mark constructed types... (preserve Constructed tag)
+ //
+ int flags = (bytes[0] & Asn1Tags.Constructed) | Asn1Tags.Tagged;
+ derOut.WriteTag(flags, tagNo);
+ derOut.Write(bytes, 1, bytes.Length - 1);
+ }
+ }
+ else
+ {
+ derOut.WriteEncoded(Asn1Tags.Constructed | Asn1Tags.Tagged, tagNo, new byte[0]);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerTaggedObject.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerTaggedObject.cs.meta
new file mode 100644
index 00000000..9d6344ad
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerTaggedObject.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 09a923adf168ad244bfe61ba31f805bb
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerUTCTime.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerUTCTime.cs
new file mode 100644
index 00000000..eb4b4a48
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerUTCTime.cs
@@ -0,0 +1,271 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Globalization;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1
+{
+ /**
+ * UTC time object.
+ */
+ public class DerUtcTime
+ : Asn1Object
+ {
+ private readonly string time;
+
+ /**
+ * return an UTC Time from the passed in object.
+ *
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static DerUtcTime GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is DerUtcTime)
+ {
+ return (DerUtcTime)obj;
+ }
+
+ throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj));
+ }
+
+ /**
+ * return an UTC Time from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want
+ * @param explicitly true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static DerUtcTime GetInstance(
+ Asn1TaggedObject obj,
+ bool isExplicit)
+ {
+ Asn1Object o = obj.GetObject();
+
+ if (isExplicit || o is DerUtcTime)
+ {
+ return GetInstance(o);
+ }
+
+ return new DerUtcTime(((Asn1OctetString)o).GetOctets());
+ }
+
+ /**
+ * The correct format for this is YYMMDDHHMMSSZ (it used to be that seconds were
+ * never encoded. When you're creating one of these objects from scratch, that's
+ * what you want to use, otherwise we'll try to deal with whatever Gets read from
+ * the input stream... (this is why the input format is different from the GetTime()
+ * method output).
+ *
+ * @param time the time string.
+ */
+ public DerUtcTime(
+ string time)
+ {
+ if (time == null)
+ throw new ArgumentNullException("time");
+
+ this.time = time;
+
+ try
+ {
+ ToDateTime();
+ }
+ catch (FormatException e)
+ {
+ throw new ArgumentException("invalid date string: " + e.Message);
+ }
+ }
+
+ /**
+ * base constructor from a DateTime object
+ */
+ public DerUtcTime(
+ DateTime time)
+ {
+#if PORTABLE || NETFX_CORE
+ this.time = time.ToUniversalTime().ToString("yyMMddHHmmss", CultureInfo.InvariantCulture) + "Z";
+#else
+ this.time = time.ToString("yyMMddHHmmss", CultureInfo.InvariantCulture) + "Z";
+#endif
+ }
+
+ internal DerUtcTime(
+ byte[] bytes)
+ {
+ //
+ // explicitly convert to characters
+ //
+ this.time = Strings.FromAsciiByteArray(bytes);
+ }
+
+// public DateTime ToDateTime()
+// {
+// string tm = this.AdjustedTimeString;
+//
+// return new DateTime(
+// Int16.Parse(tm.Substring(0, 4)),
+// Int16.Parse(tm.Substring(4, 2)),
+// Int16.Parse(tm.Substring(6, 2)),
+// Int16.Parse(tm.Substring(8, 2)),
+// Int16.Parse(tm.Substring(10, 2)),
+// Int16.Parse(tm.Substring(12, 2)));
+// }
+
+ /**
+ * return the time as a date based on whatever a 2 digit year will return. For
+ * standardised processing use ToAdjustedDateTime().
+ *
+ * @return the resulting date
+ * @exception ParseException if the date string cannot be parsed.
+ */
+ public DateTime ToDateTime()
+ {
+ return ParseDateString(TimeString, @"yyMMddHHmmss'GMT'zzz");
+ }
+
+ /**
+ * return the time as an adjusted date
+ * in the range of 1950 - 2049.
+ *
+ * @return a date in the range of 1950 to 2049.
+ * @exception ParseException if the date string cannot be parsed.
+ */
+ public DateTime ToAdjustedDateTime()
+ {
+ return ParseDateString(AdjustedTimeString, @"yyyyMMddHHmmss'GMT'zzz");
+ }
+
+ private DateTime ParseDateString(
+ string dateStr,
+ string formatStr)
+ {
+ DateTime dt = DateTime.ParseExact(
+ dateStr,
+ formatStr,
+ DateTimeFormatInfo.InvariantInfo);
+
+ return dt.ToUniversalTime();
+ }
+
+ /**
+ * return the time - always in the form of
+ * YYMMDDhhmmssGMT(+hh:mm|-hh:mm).
+ *
+ * Normally in a certificate we would expect "Z" rather than "GMT",
+ * however adding the "GMT" means we can just use:
+ *
+ * dateF = new SimpleDateFormat("yyMMddHHmmssz");
+ *
+ * To read in the time and Get a date which is compatible with our local
+ * time zone.
+ *
+ * Note: In some cases, due to the local date processing, this
+ * may lead to unexpected results. If you want to stick the normal
+ * convention of 1950 to 2049 use the GetAdjustedTime() method.
+ */
+ public string TimeString
+ {
+ get
+ {
+ //
+ // standardise the format.
+ //
+ if (time.IndexOf('-') < 0 && time.IndexOf('+') < 0)
+ {
+ if (time.Length == 11)
+ {
+ return time.Substring(0, 10) + "00GMT+00:00";
+ }
+ else
+ {
+ return time.Substring(0, 12) + "GMT+00:00";
+ }
+ }
+ else
+ {
+ int index = time.IndexOf('-');
+ if (index < 0)
+ {
+ index = time.IndexOf('+');
+ }
+ string d = time;
+
+ if (index == time.Length - 3)
+ {
+ d += "00";
+ }
+
+ if (index == 10)
+ {
+ return d.Substring(0, 10) + "00GMT" + d.Substring(10, 3) + ":" + d.Substring(13, 2);
+ }
+ else
+ {
+ return d.Substring(0, 12) + "GMT" + d.Substring(12, 3) + ":" + d.Substring(15, 2);
+ }
+ }
+ }
+ }
+
+ [Obsolete("Use 'AdjustedTimeString' property instead")]
+ public string AdjustedTime
+ {
+ get { return AdjustedTimeString; }
+ }
+
+ ///
+ /// Return a time string as an adjusted date with a 4 digit year.
+ /// This goes in the range of 1950 - 2049.
+ ///
+ public string AdjustedTimeString
+ {
+ get
+ {
+ string d = TimeString;
+ string c = d[0] < '5' ? "20" : "19";
+
+ return c + d;
+ }
+ }
+
+ private byte[] GetOctets()
+ {
+ return Strings.ToAsciiByteArray(time);
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.UtcTime, GetOctets());
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerUtcTime other = asn1Object as DerUtcTime;
+
+ if (other == null)
+ return false;
+
+ return this.time.Equals(other.time);
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ return time.GetHashCode();
+ }
+
+ public override string ToString()
+ {
+ return time;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerUTCTime.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerUTCTime.cs.meta
new file mode 100644
index 00000000..f6ae5216
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerUTCTime.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 974cf3154ca4d22409f3c9f174fd6f5d
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerUTF8String.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerUTF8String.cs
new file mode 100644
index 00000000..64778583
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerUTF8String.cs
@@ -0,0 +1,102 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1
+{
+ /**
+ * Der UTF8String object.
+ */
+ public class DerUtf8String
+ : DerStringBase
+ {
+ private readonly string str;
+
+ /**
+ * return an UTF8 string from the passed in object.
+ *
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static DerUtf8String GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is DerUtf8String)
+ {
+ return (DerUtf8String)obj;
+ }
+
+ throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj));
+ }
+
+ /**
+ * return an UTF8 string from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want
+ * @param explicitly true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static DerUtf8String GetInstance(
+ Asn1TaggedObject obj,
+ bool isExplicit)
+ {
+ Asn1Object o = obj.GetObject();
+
+ if (isExplicit || o is DerUtf8String)
+ {
+ return GetInstance(o);
+ }
+
+ return new DerUtf8String(Asn1OctetString.GetInstance(o).GetOctets());
+ }
+
+ /**
+ * basic constructor - byte encoded string.
+ */
+ public DerUtf8String(
+ byte[] str)
+ : this(Encoding.UTF8.GetString(str, 0, str.Length))
+ {
+ }
+
+ /**
+ * basic constructor
+ */
+ public DerUtf8String(
+ string str)
+ {
+ if (str == null)
+ throw new ArgumentNullException("str");
+
+ this.str = str;
+ }
+
+ public override string GetString()
+ {
+ return str;
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerUtf8String other = asn1Object as DerUtf8String;
+
+ if (other == null)
+ return false;
+
+ return this.str.Equals(other.str);
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.Utf8String, Encoding.UTF8.GetBytes(str));
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerUTF8String.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerUTF8String.cs.meta
new file mode 100644
index 00000000..70a0e116
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerUTF8String.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 59793e3c98172f046a238fb0352e1e38
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerUniversalString.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerUniversalString.cs
new file mode 100644
index 00000000..ef688f9e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerUniversalString.cs
@@ -0,0 +1,111 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1
+{
+ /**
+ * Der UniversalString object.
+ */
+ public class DerUniversalString
+ : DerStringBase
+ {
+ private static readonly char[] table = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
+
+ private readonly byte[] str;
+
+ /**
+ * return a Universal string from the passed in object.
+ *
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static DerUniversalString GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is DerUniversalString)
+ {
+ return (DerUniversalString)obj;
+ }
+
+ throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj));
+ }
+
+ /**
+ * return a Universal string from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want
+ * @param explicitly true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static DerUniversalString GetInstance(
+ Asn1TaggedObject obj,
+ bool isExplicit)
+ {
+ Asn1Object o = obj.GetObject();
+
+ if (isExplicit || o is DerUniversalString)
+ {
+ return GetInstance(o);
+ }
+
+ return new DerUniversalString(Asn1OctetString.GetInstance(o).GetOctets());
+ }
+
+ /**
+ * basic constructor - byte encoded string.
+ */
+ public DerUniversalString(
+ byte[] str)
+ {
+ if (str == null)
+ throw new ArgumentNullException("str");
+
+ this.str = str;
+ }
+
+ public override string GetString()
+ {
+ StringBuilder buffer = new StringBuilder("#");
+ byte[] enc = GetDerEncoded();
+
+ for (int i = 0; i != enc.Length; i++)
+ {
+ uint ubyte = enc[i];
+ buffer.Append(table[(ubyte >> 4) & 0xf]);
+ buffer.Append(table[enc[i] & 0xf]);
+ }
+
+ return buffer.ToString();
+ }
+
+ public byte[] GetOctets()
+ {
+ return (byte[]) str.Clone();
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.UniversalString, this.str);
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerUniversalString other = asn1Object as DerUniversalString;
+
+ if (other == null)
+ return false;
+
+// return this.GetString().Equals(other.GetString());
+ return Arrays.AreEqual(this.str, other.str);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerUniversalString.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerUniversalString.cs.meta
new file mode 100644
index 00000000..648b26f4
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerUniversalString.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 9aeab3619d1c4324f9e7968fa71c7ed4
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerVideotexString.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerVideotexString.cs
new file mode 100644
index 00000000..e730dce5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerVideotexString.cs
@@ -0,0 +1,107 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1
+{
+ public class DerVideotexString
+ : DerStringBase
+ {
+ private readonly byte[] mString;
+
+ /**
+ * return a Videotex String from the passed in object
+ *
+ * @param obj a DERVideotexString or an object that can be converted into one.
+ * @exception IllegalArgumentException if the object cannot be converted.
+ * @return a DERVideotexString instance, or null.
+ */
+ public static DerVideotexString GetInstance(object obj)
+ {
+ if (obj == null || obj is DerVideotexString)
+ {
+ return (DerVideotexString)obj;
+ }
+
+ if (obj is byte[])
+ {
+ try
+ {
+ return (DerVideotexString)FromByteArray((byte[])obj);
+ }
+ catch (Exception e)
+ {
+ throw new ArgumentException("encoding error in GetInstance: " + e.ToString(), "obj");
+ }
+ }
+
+ throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+ }
+
+ /**
+ * return a Videotex String from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want
+ * @param explicit true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception IllegalArgumentException if the tagged object cannot
+ * be converted.
+ * @return a DERVideotexString instance, or null.
+ */
+ public static DerVideotexString GetInstance(Asn1TaggedObject obj, bool isExplicit)
+ {
+ Asn1Object o = obj.GetObject();
+
+ if (isExplicit || o is DerVideotexString)
+ {
+ return GetInstance(o);
+ }
+
+ return new DerVideotexString(((Asn1OctetString)o).GetOctets());
+ }
+
+ /**
+ * basic constructor - with bytes.
+ * @param string the byte encoding of the characters making up the string.
+ */
+ public DerVideotexString(byte[] encoding)
+ {
+ this.mString = Arrays.Clone(encoding);
+ }
+
+ public override string GetString()
+ {
+ return Strings.FromByteArray(mString);
+ }
+
+ public byte[] GetOctets()
+ {
+ return Arrays.Clone(mString);
+ }
+
+ internal override void Encode(DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.VideotexString, mString);
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ return Arrays.GetHashCode(mString);
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerVideotexString other = asn1Object as DerVideotexString;
+
+ if (other == null)
+ return false;
+
+ return Arrays.AreEqual(mString, other.mString);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerVideotexString.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerVideotexString.cs.meta
new file mode 100644
index 00000000..b9e4a3c7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerVideotexString.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: dd1f8c7688b859b4d990225267b276ec
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerVisibleString.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerVisibleString.cs
new file mode 100644
index 00000000..3c422fb1
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerVisibleString.cs
@@ -0,0 +1,115 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1
+{
+ /**
+ * Der VisibleString object.
+ */
+ public class DerVisibleString
+ : DerStringBase
+ {
+ private readonly string str;
+
+ /**
+ * return a Visible string from the passed in object.
+ *
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static DerVisibleString GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is DerVisibleString)
+ {
+ return (DerVisibleString)obj;
+ }
+
+ if (obj is Asn1OctetString)
+ {
+ return new DerVisibleString(((Asn1OctetString)obj).GetOctets());
+ }
+
+ if (obj is Asn1TaggedObject)
+ {
+ return GetInstance(((Asn1TaggedObject)obj).GetObject());
+ }
+
+ throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj));
+ }
+
+ /**
+ * return a Visible string from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want
+ * @param explicitly true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static DerVisibleString GetInstance(
+ Asn1TaggedObject obj,
+ bool explicitly)
+ {
+ return GetInstance(obj.GetObject());
+ }
+
+ /**
+ * basic constructor - byte encoded string.
+ */
+ public DerVisibleString(
+ byte[] str)
+ : this(Strings.FromAsciiByteArray(str))
+ {
+ }
+
+ /**
+ * basic constructor
+ */
+ public DerVisibleString(
+ string str)
+ {
+ if (str == null)
+ throw new ArgumentNullException("str");
+
+ this.str = str;
+ }
+
+ public override string GetString()
+ {
+ return str;
+ }
+
+ public byte[] GetOctets()
+ {
+ return Strings.ToAsciiByteArray(str);
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.VisibleString, GetOctets());
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerVisibleString other = asn1Object as DerVisibleString;
+
+ if (other == null)
+ return false;
+
+ return this.str.Equals(other.str);
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ return this.str.GetHashCode();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerVisibleString.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerVisibleString.cs.meta
new file mode 100644
index 00000000..92b11d14
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/DerVisibleString.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: f9c45522cf4626c4c81e4e6b8b3fe74b
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/IAsn1ApplicationSpecificParser.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/IAsn1ApplicationSpecificParser.cs
new file mode 100644
index 00000000..a7f0e115
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/IAsn1ApplicationSpecificParser.cs
@@ -0,0 +1,14 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1
+{
+ public interface IAsn1ApplicationSpecificParser
+ : IAsn1Convertible
+ {
+ IAsn1Convertible ReadObject();
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/IAsn1ApplicationSpecificParser.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/IAsn1ApplicationSpecificParser.cs.meta
new file mode 100644
index 00000000..3e400bf1
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/IAsn1ApplicationSpecificParser.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 5db852656650b934d8a382f2d26d18b1
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/IAsn1Choice.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/IAsn1Choice.cs
new file mode 100644
index 00000000..77b82c8e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/IAsn1Choice.cs
@@ -0,0 +1,21 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1
+{
+ /**
+ * Marker interface for CHOICE objects - if you implement this in a roll-your-own
+ * object, any attempt to tag the object implicitly will convert the tag to an
+ * explicit one as the encoding rules require.
+ *
+ * If you use this interface your class should also implement the getInstance
+ * pattern which takes a tag object and the tagging mode used.
+ *
+ * 1.3.6.1.4.1.22554.1.1
+ */
+ public static readonly DerObjectIdentifier bc_pbe_sha1 = bc_pbe.Branch("1");
+
+ /** SHA-2.SHA-256; 1.3.6.1.4.1.22554.1.2.1 */
+ public static readonly DerObjectIdentifier bc_pbe_sha256 = bc_pbe.Branch("2.1");
+ /** SHA-2.SHA-384; 1.3.6.1.4.1.22554.1.2.2 */
+ public static readonly DerObjectIdentifier bc_pbe_sha384 = bc_pbe.Branch("2.2");
+ /** SHA-2.SHA-512; 1.3.6.1.4.1.22554.1.2.3 */
+ public static readonly DerObjectIdentifier bc_pbe_sha512 = bc_pbe.Branch("2.3");
+ /** SHA-2.SHA-224; 1.3.6.1.4.1.22554.1.2.4 */
+ public static readonly DerObjectIdentifier bc_pbe_sha224 = bc_pbe.Branch("2.4");
+
+ /**
+ * PKCS-5(1)|PKCS-12(2)
+ */
+ /** SHA-1.PKCS5; 1.3.6.1.4.1.22554.1.1.1 */
+ public static readonly DerObjectIdentifier bc_pbe_sha1_pkcs5 = bc_pbe_sha1.Branch("1");
+ /** SHA-1.PKCS12; 1.3.6.1.4.1.22554.1.1.2 */
+ public static readonly DerObjectIdentifier bc_pbe_sha1_pkcs12 = bc_pbe_sha1.Branch("2");
+
+ /** SHA-256.PKCS12; 1.3.6.1.4.1.22554.1.2.1.1 */
+ public static readonly DerObjectIdentifier bc_pbe_sha256_pkcs5 = bc_pbe_sha256.Branch("1");
+ /** SHA-256.PKCS12; 1.3.6.1.4.1.22554.1.2.1.2 */
+ public static readonly DerObjectIdentifier bc_pbe_sha256_pkcs12 = bc_pbe_sha256.Branch("2");
+
+ /**
+ * AES(1) . (CBC-128(2)|CBC-192(22)|CBC-256(42))
+ */
+ /** 1.3.6.1.4.1.22554.1.1.2.1.2 */
+ public static readonly DerObjectIdentifier bc_pbe_sha1_pkcs12_aes128_cbc = bc_pbe_sha1_pkcs12.Branch("1.2");
+ /** 1.3.6.1.4.1.22554.1.1.2.1.22 */
+ public static readonly DerObjectIdentifier bc_pbe_sha1_pkcs12_aes192_cbc = bc_pbe_sha1_pkcs12.Branch("1.22");
+ /** 1.3.6.1.4.1.22554.1.1.2.1.42 */
+ public static readonly DerObjectIdentifier bc_pbe_sha1_pkcs12_aes256_cbc = bc_pbe_sha1_pkcs12.Branch("1.42");
+
+ /** 1.3.6.1.4.1.22554.1.1.2.2.2 */
+ public static readonly DerObjectIdentifier bc_pbe_sha256_pkcs12_aes128_cbc = bc_pbe_sha256_pkcs12.Branch("1.2");
+ /** 1.3.6.1.4.1.22554.1.1.2.2.22 */
+ public static readonly DerObjectIdentifier bc_pbe_sha256_pkcs12_aes192_cbc = bc_pbe_sha256_pkcs12.Branch("1.22");
+ /** 1.3.6.1.4.1.22554.1.1.2.2.42 */
+ public static readonly DerObjectIdentifier bc_pbe_sha256_pkcs12_aes256_cbc = bc_pbe_sha256_pkcs12.Branch("1.42");
+
+ /**
+ * signature(2) algorithms
+ */
+ public static readonly DerObjectIdentifier bc_sig = bc.Branch("2");
+
+ /**
+ * Sphincs-256
+ */
+ public static readonly DerObjectIdentifier sphincs256 = bc_sig.Branch("1");
+ public static readonly DerObjectIdentifier sphincs256_with_BLAKE512 = sphincs256.Branch("1");
+ public static readonly DerObjectIdentifier sphincs256_with_SHA512 = sphincs256.Branch("2");
+ public static readonly DerObjectIdentifier sphincs256_with_SHA3_512 = sphincs256.Branch("3");
+
+ /**
+ * XMSS
+ */
+ public static readonly DerObjectIdentifier xmss = bc_sig.Branch("2");
+ public static readonly DerObjectIdentifier xmss_with_SHA256 = xmss.Branch("1");
+ public static readonly DerObjectIdentifier xmss_with_SHA512 = xmss.Branch("2");
+ public static readonly DerObjectIdentifier xmss_with_SHAKE128 = xmss.Branch("3");
+ public static readonly DerObjectIdentifier xmss_with_SHAKE256 = xmss.Branch("4");
+
+ /**
+ * XMSS^MT
+ */
+ public static readonly DerObjectIdentifier xmss_mt = bc_sig.Branch("3");
+ public static readonly DerObjectIdentifier xmss_mt_with_SHA256 = xmss_mt.Branch("1");
+ public static readonly DerObjectIdentifier xmss_mt_with_SHA512 = xmss_mt.Branch("2");
+ public static readonly DerObjectIdentifier xmss_mt_with_SHAKE128 = xmss_mt.Branch("3");
+ public static readonly DerObjectIdentifier xmss_mt_with_SHAKE256 = xmss_mt.Branch("4");
+
+ /**
+ * key_exchange(3) algorithms
+ */
+ public static readonly DerObjectIdentifier bc_exch = bc.Branch("3");
+
+ /**
+ * NewHope
+ */
+ public static readonly DerObjectIdentifier newHope = bc_exch.Branch("1");
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/bc/BCObjectIdentifiers.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/bc/BCObjectIdentifiers.cs.meta
new file mode 100644
index 00000000..040ff09c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/bc/BCObjectIdentifiers.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 88b600bd01c1bd84d852eaee534e8c9a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/bsi.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/bsi.meta
new file mode 100644
index 00000000..211a68ae
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/bsi.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: d69a6d859d991b64f8b842ce92e9378d
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/bsi/BsiObjectIdentifiers.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/bsi/BsiObjectIdentifiers.cs
new file mode 100644
index 00000000..61731e90
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/bsi/BsiObjectIdentifiers.cs
@@ -0,0 +1,107 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Bsi
+{
+ /// See https://www.bsi.bund.de/cae/servlet/contentblob/471398/publicationFile/30615/BSI-TR-03111_pdf.pdf
+ public abstract class BsiObjectIdentifiers
+ {
+ public static readonly DerObjectIdentifier bsi_de = new DerObjectIdentifier("0.4.0.127.0.7");
+
+ /* 0.4.0.127.0.7.1.1 */
+ public static readonly DerObjectIdentifier id_ecc = bsi_de.Branch("1.1");
+
+ /* 0.4.0.127.0.7.1.1.4.1 */
+ public static readonly DerObjectIdentifier ecdsa_plain_signatures = id_ecc.Branch("4.1");
+
+ /* 0.4.0.127.0.7.1.1.4.1.1 */
+ public static readonly DerObjectIdentifier ecdsa_plain_SHA1 = ecdsa_plain_signatures.Branch("1");
+
+ /* 0.4.0.127.0.7.1.1.4.1.2 */
+ public static readonly DerObjectIdentifier ecdsa_plain_SHA224 = ecdsa_plain_signatures.Branch("2");
+
+ /* 0.4.0.127.0.7.1.1.4.1.3 */
+ public static readonly DerObjectIdentifier ecdsa_plain_SHA256 = ecdsa_plain_signatures.Branch("3");
+
+ /* 0.4.0.127.0.7.1.1.4.1.4 */
+ public static readonly DerObjectIdentifier ecdsa_plain_SHA384 = ecdsa_plain_signatures.Branch("4");
+
+ /* 0.4.0.127.0.7.1.1.4.1.5 */
+ public static readonly DerObjectIdentifier ecdsa_plain_SHA512 = ecdsa_plain_signatures.Branch("5");
+
+ /* 0.4.0.127.0.7.1.1.4.1.6 */
+ public static readonly DerObjectIdentifier ecdsa_plain_RIPEMD160 = ecdsa_plain_signatures.Branch("6");
+
+ /** 0.4.0.127.0.7.1 */
+ public static readonly DerObjectIdentifier algorithm = bsi_de.Branch("1");
+
+ public static readonly DerObjectIdentifier ecka_eg = id_ecc.Branch("5.1");
+
+ /** ElGamal Elliptic Curve Key Agreement and Key Derivation according to X963 OID: 0.4.0.127.0.7.1.1.5.1.1 */
+ public static readonly DerObjectIdentifier ecka_eg_X963kdf = ecka_eg.Branch("1");
+
+ /** ElGamal Elliptic Curve Key Agreement and Key Derivation according to X963
+ * with hash function SHA-1
+ * OID: 0.4.0.127.0.7.1.1.5.1.1.1 */
+ public static readonly DerObjectIdentifier ecka_eg_X963kdf_SHA1 = ecka_eg_X963kdf.Branch("1");
+
+ /** ElGamal Elliptic Curve Key Agreement and Key Derivation according to X963
+ * with hash function SHA224
+ * OID: 0.4.0.127.0.7.1.1.5.1.1.2 */
+ public static readonly DerObjectIdentifier ecka_eg_X963kdf_SHA224 = ecka_eg_X963kdf.Branch("2");
+
+ /** ElGamal Elliptic Curve Key Agreement and Key Derivation according to X963
+ * with hash function SHA256
+ * OID: 0.4.0.127.0.7.1.1.5.1.1.3 */
+ public static readonly DerObjectIdentifier ecka_eg_X963kdf_SHA256 = ecka_eg_X963kdf.Branch("3");
+
+ /** ElGamal Elliptic Curve Key Agreement and Key Derivation according to X963
+ * with hash function SHA384
+ * OID: 0.4.0.127.0.7.1.1.5.1.1.4 */
+ public static readonly DerObjectIdentifier ecka_eg_X963kdf_SHA384 = ecka_eg_X963kdf.Branch("4");
+
+ /** ElGamal Elliptic Curve Key Agreement and Key Derivation according to X963
+ * with hash function SHA512
+ * OID: 0.4.0.127.0.7.1.1.5.1.1.5 */
+ public static readonly DerObjectIdentifier ecka_eg_X963kdf_SHA512 = ecka_eg_X963kdf.Branch("5");
+
+ /** ElGamal Elliptic Curve Key Agreement and Key Derivation according to X963
+ * with hash function RIPEMD160
+ * OID: 0.4.0.127.0.7.1.1.5.1.1.6 */
+ public static readonly DerObjectIdentifier ecka_eg_X963kdf_RIPEMD160 = ecka_eg_X963kdf.Branch("6");
+
+ /**
+ * Key Derivation Function for Session Keys
+ */
+ public static readonly DerObjectIdentifier ecka_eg_SessionKDF = ecka_eg.Branch("2");
+
+ public static readonly DerObjectIdentifier ecka_eg_SessionKDF_3DES = ecka_eg_SessionKDF.Branch("1");
+ public static readonly DerObjectIdentifier ecka_eg_SessionKDF_AES128 = ecka_eg_SessionKDF.Branch("2");
+ public static readonly DerObjectIdentifier ecka_eg_SessionKDF_AES192 = ecka_eg_SessionKDF.Branch("3");
+ public static readonly DerObjectIdentifier ecka_eg_SessionKDF_AES256 = ecka_eg_SessionKDF.Branch("4");
+
+ /** AES encryption (CBC) and authentication (CMAC)
+ * OID: 0.4.0.127.0.7.1.x */
+ //TODO: replace "1" with correct OID
+ //public static readonly DerObjectIdentifier aes_cbc_cmac = algorithm.Branch("1");
+
+ /** AES encryption (CBC) and authentication (CMAC) with 128 bit
+ * OID: 0.4.0.127.0.7.1.x.y1 */
+ //TODO: replace "1" with correct OID
+ //public static readonly DerObjectIdentifier id_aes128_CBC_CMAC = aes_cbc_cmac.Branch("1");
+
+
+ /** AES encryption (CBC) and authentication (CMAC) with 192 bit
+ * OID: 0.4.0.127.0.7.1.x.y2 */
+ //TODO: replace "1" with correct OID
+ //public static readonly DerObjectIdentifier id_aes192_CBC_CMAC = aes_cbc_cmac.Branch("1");
+
+ /** AES encryption (CBC) and authentication (CMAC) with 256 bit
+ * OID: 0.4.0.127.0.7.1.x.y3 */
+ //TODO: replace "1" with correct OID
+ //public static readonly DerObjectIdentifier id_aes256_CBC_CMAC = aes_cbc_cmac.Branch("1");
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/bsi/BsiObjectIdentifiers.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/bsi/BsiObjectIdentifiers.cs.meta
new file mode 100644
index 00000000..505ba3bf
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/bsi/BsiObjectIdentifiers.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c637ff969c8ac00459df1c73c136ad8b
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp.meta
new file mode 100644
index 00000000..5419c323
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 90e6fc2668a091f4dba719add4667fee
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/CAKeyUpdAnnContent.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/CAKeyUpdAnnContent.cs
new file mode 100644
index 00000000..84ee8c32
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/CAKeyUpdAnnContent.cs
@@ -0,0 +1,66 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp
+{
+ public class CAKeyUpdAnnContent
+ : Asn1Encodable
+ {
+ private readonly CmpCertificate oldWithNew;
+ private readonly CmpCertificate newWithOld;
+ private readonly CmpCertificate newWithNew;
+
+ private CAKeyUpdAnnContent(Asn1Sequence seq)
+ {
+ oldWithNew = CmpCertificate.GetInstance(seq[0]);
+ newWithOld = CmpCertificate.GetInstance(seq[1]);
+ newWithNew = CmpCertificate.GetInstance(seq[2]);
+ }
+
+ public static CAKeyUpdAnnContent GetInstance(object obj)
+ {
+ if (obj is CAKeyUpdAnnContent)
+ return (CAKeyUpdAnnContent)obj;
+
+ if (obj is Asn1Sequence)
+ return new CAKeyUpdAnnContent((Asn1Sequence)obj);
+
+ throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+ }
+
+ public virtual CmpCertificate OldWithNew
+ {
+ get { return oldWithNew; }
+ }
+
+ public virtual CmpCertificate NewWithOld
+ {
+ get { return newWithOld; }
+ }
+
+ public virtual CmpCertificate NewWithNew
+ {
+ get { return newWithNew; }
+ }
+
+ /**
+ *
+ * CAKeyUpdAnnContent ::= SEQUENCE {
+ * oldWithNew CmpCertificate, -- old pub signed with new priv
+ * newWithOld CmpCertificate, -- new pub signed with old priv
+ * newWithNew CmpCertificate -- new pub signed with new priv
+ * }
+ *
+ * CertResponse ::= SEQUENCE {
+ * certReqId INTEGER,
+ * -- to match this response with corresponding request (a value
+ * -- of -1 is to be used if certReqId is not specified in the
+ * -- corresponding request)
+ * status PKIStatusInfo,
+ * certifiedKeyPair CertifiedKeyPair OPTIONAL,
+ * rspInfo OCTET STRING OPTIONAL
+ * -- analogous to the id-regInfo-utf8Pairs string defined
+ * -- for regInfo in CertReqMsg [CRMF]
+ * }
+ *
+ * CertStatus ::= SEQUENCE {
+ * certHash OCTET STRING,
+ * -- the hash of the certificate, using the same hash algorithm
+ * -- as is used to create and verify the certificate signature
+ * certReqId INTEGER,
+ * -- to match this confirmation with the corresponding req/rep
+ * statusInfo PKIStatusInfo OPTIONAL
+ * }
+ *
+ * Challenge ::= SEQUENCE {
+ * owf AlgorithmIdentifier OPTIONAL,
+ *
+ * -- MUST be present in the first Challenge; MAY be omitted in
+ * -- any subsequent Challenge in POPODecKeyChallContent (if
+ * -- omitted, then the owf used in the immediately preceding
+ * -- Challenge is to be used).
+ *
+ * witness OCTET STRING,
+ * -- the result of applying the one-way function (owf) to a
+ * -- randomly-generated INTEGER, A. [Note that a different
+ * -- INTEGER MUST be used for each Challenge.]
+ * challenge OCTET STRING
+ * -- the encryption (under the public key for which the cert.
+ * -- request is being made) of Rand, where Rand is specified as
+ * -- Rand ::= SEQUENCE {
+ * -- int INTEGER,
+ * -- - the randomly-generated INTEGER A (above)
+ * -- sender GeneralName
+ * -- - the sender's name (as included in PKIHeader)
+ * -- }
+ * }
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector();
+ v.AddOptional(owf);
+ v.Add(witness);
+ v.Add(challenge);
+ return new DerSequence(v);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/Challenge.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/Challenge.cs.meta
new file mode 100644
index 00000000..2d13e282
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/Challenge.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ab7eeb71d93e81e498a0911105158b6d
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/CmpCertificate.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/CmpCertificate.cs
new file mode 100644
index 00000000..e45dd315
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/CmpCertificate.cs
@@ -0,0 +1,85 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp
+{
+ public class CmpCertificate
+ : Asn1Encodable, IAsn1Choice
+ {
+ private readonly X509CertificateStructure x509v3PKCert;
+ private readonly AttributeCertificate x509v2AttrCert;
+
+ /**
+ * Note: the addition of attribute certificates is a BC extension.
+ */
+ public CmpCertificate(AttributeCertificate x509v2AttrCert)
+ {
+ this.x509v2AttrCert = x509v2AttrCert;
+ }
+
+ public CmpCertificate(X509CertificateStructure x509v3PKCert)
+ {
+ if (x509v3PKCert.Version != 3)
+ throw new ArgumentException("only version 3 certificates allowed", "x509v3PKCert");
+
+ this.x509v3PKCert = x509v3PKCert;
+ }
+
+ public static CmpCertificate GetInstance(object obj)
+ {
+ if (obj is CmpCertificate)
+ return (CmpCertificate)obj;
+
+ if (obj is Asn1Sequence)
+ return new CmpCertificate(X509CertificateStructure.GetInstance(obj));
+
+ if (obj is Asn1TaggedObject)
+ return new CmpCertificate(AttributeCertificate.GetInstance(((Asn1TaggedObject)obj).GetObject()));
+
+ throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+ }
+
+ public virtual bool IsX509v3PKCert
+ {
+ get { return x509v3PKCert != null; }
+ }
+
+ public virtual X509CertificateStructure X509v3PKCert
+ {
+ get { return x509v3PKCert; }
+ }
+
+ public virtual AttributeCertificate X509v2AttrCert
+ {
+ get { return x509v2AttrCert; }
+ }
+
+ /**
+ *
+ * PKIFailureInfo ::= BIT STRING {
+ * badAlg (0),
+ * -- unrecognized or unsupported Algorithm Identifier
+ * badMessageCheck (1), -- integrity check failed (e.g., signature did not verify)
+ * badRequest (2),
+ * -- transaction not permitted or supported
+ * badTime (3), -- messageTime was not sufficiently close to the system time, as defined by local policy
+ * badCertId (4), -- no certificate could be found matching the provided criteria
+ * badDataFormat (5),
+ * -- the data submitted has the wrong format
+ * wrongAuthority (6), -- the authority indicated in the request is different from the one creating the response token
+ * incorrectData (7), -- the requester's data is incorrect (for notary services)
+ * missingTimeStamp (8), -- when the timestamp is missing but should be there (by policy)
+ * badPOP (9) -- the proof-of-possession failed
+ * certRevoked (10),
+ * certConfirmed (11),
+ * wrongIntegrity (12),
+ * badRecipientNonce (13),
+ * timeNotAvailable (14),
+ * -- the TSA's time source is not available
+ * unacceptedPolicy (15),
+ * -- the requested TSA policy is not supported by the TSA
+ * unacceptedExtension (16),
+ * -- the requested extension is not supported by the TSA
+ * addInfoNotAvailable (17)
+ * -- the additional information requested could not be understood
+ * -- or is not available
+ * badSenderNonce (18),
+ * badCertTemplate (19),
+ * signerNotTrusted (20),
+ * transactionIdInUse (21),
+ * unsupportedVersion (22),
+ * notAuthorized (23),
+ * systemUnavail (24),
+ * systemFailure (25),
+ * -- the request cannot be handled due to system failure
+ * duplicateCertReq (26)
+ *
+ */
+ public class PkiFailureInfo
+ : DerBitString
+ {
+ public const int BadAlg = (1 << 7); // unrecognized or unsupported Algorithm Identifier
+ public const int BadMessageCheck = (1 << 6); // integrity check failed (e.g., signature did not verify)
+ public const int BadRequest = (1 << 5);
+ public const int BadTime = (1 << 4); // -- messageTime was not sufficiently close to the system time, as defined by local policy
+ public const int BadCertId = (1 << 3); // no certificate could be found matching the provided criteria
+ public const int BadDataFormat = (1 << 2);
+ public const int WrongAuthority = (1 << 1); // the authority indicated in the request is different from the one creating the response token
+ public const int IncorrectData = 1; // the requester's data is incorrect (for notary services)
+ public const int MissingTimeStamp = (1 << 15); // when the timestamp is missing but should be there (by policy)
+ public const int BadPop = (1 << 14); // the proof-of-possession failed
+ public const int CertRevoked = (1 << 13);
+ public const int CertConfirmed = (1 << 12);
+ public const int WrongIntegrity = (1 << 11);
+ public const int BadRecipientNonce = (1 << 10);
+ public const int TimeNotAvailable = (1 << 9); // the TSA's time source is not available
+ public const int UnacceptedPolicy = (1 << 8); // the requested TSA policy is not supported by the TSA
+ public const int UnacceptedExtension = (1 << 23); //the requested extension is not supported by the TSA
+ public const int AddInfoNotAvailable = (1 << 22); //the additional information requested could not be understood or is not available
+ public const int BadSenderNonce = (1 << 21);
+ public const int BadCertTemplate = (1 << 20);
+ public const int SignerNotTrusted = (1 << 19);
+ public const int TransactionIdInUse = (1 << 18);
+ public const int UnsupportedVersion = (1 << 17);
+ public const int NotAuthorized = (1 << 16);
+ public const int SystemUnavail = (1 << 31);
+ public const int SystemFailure = (1 << 30); //the request cannot be handled due to system failure
+ public const int DuplicateCertReq = (1 << 29);
+
+ /**
+ * Basic constructor.
+ */
+ public PkiFailureInfo(int info)
+ : base(info)
+ {
+ }
+
+ public PkiFailureInfo(
+ DerBitString info)
+ : base(info.GetBytes(), info.PadBits)
+ {
+ }
+
+ public override string ToString()
+ {
+ return "PkiFailureInfo: 0x" + this.IntValue.ToString("X");
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/PKIFailureInfo.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/PKIFailureInfo.cs.meta
new file mode 100644
index 00000000..b8192f30
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/PKIFailureInfo.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a919d31f3c580104786c2734f49858f9
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/PKIFreeText.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/PKIFreeText.cs
new file mode 100644
index 00000000..af74d46c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/PKIFreeText.cs
@@ -0,0 +1,103 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp
+{
+ public class PkiFreeText
+ : Asn1Encodable
+ {
+ internal Asn1Sequence strings;
+
+ public static PkiFreeText GetInstance(
+ Asn1TaggedObject obj,
+ bool isExplicit)
+ {
+ return GetInstance(Asn1Sequence.GetInstance(obj, isExplicit));
+ }
+
+ public static PkiFreeText GetInstance(
+ object obj)
+ {
+ if (obj is PkiFreeText)
+ {
+ return (PkiFreeText)obj;
+ }
+ else if (obj is Asn1Sequence)
+ {
+ return new PkiFreeText((Asn1Sequence)obj);
+ }
+
+ throw new ArgumentException("Unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+ }
+
+ public PkiFreeText(
+ Asn1Sequence seq)
+ {
+ foreach (object o in seq)
+ {
+ if (!(o is DerUtf8String))
+ {
+ throw new ArgumentException("attempt to insert non UTF8 STRING into PkiFreeText");
+ }
+ }
+
+ this.strings = seq;
+ }
+
+ public PkiFreeText(
+ DerUtf8String p)
+ {
+ strings = new DerSequence(p);
+ }
+
+ /**
+ * Return the number of string elements present.
+ *
+ * @return number of elements present.
+ */
+ [Obsolete("Use 'Count' property instead")]
+ public int Size
+ {
+ get { return strings.Count; }
+ }
+
+ public int Count
+ {
+ get { return strings.Count; }
+ }
+
+ /**
+ * Return the UTF8STRING at index.
+ *
+ * @param index index of the string of interest
+ * @return the string at index.
+ */
+ public DerUtf8String this[int index]
+ {
+ get { return (DerUtf8String) strings[index]; }
+ }
+
+ [Obsolete("Use 'object[index]' syntax instead")]
+ public DerUtf8String GetStringAt(
+ int index)
+ {
+ return this[index];
+ }
+
+ /**
+ *
+ * PkiHeader ::= SEQUENCE {
+ * pvno INTEGER { cmp1999(1), cmp2000(2) },
+ * sender GeneralName,
+ * -- identifies the sender
+ * recipient GeneralName,
+ * -- identifies the intended recipient
+ * messageTime [0] GeneralizedTime OPTIONAL,
+ * -- time of production of this message (used when sender
+ * -- believes that the transport will be "suitable"; i.e.,
+ * -- that the time will still be meaningful upon receipt)
+ * protectionAlg [1] AlgorithmIdentifier OPTIONAL,
+ * -- algorithm used for calculation of protection bits
+ * senderKID [2] KeyIdentifier OPTIONAL,
+ * recipKID [3] KeyIdentifier OPTIONAL,
+ * -- to identify specific keys used for protection
+ * transactionID [4] OCTET STRING OPTIONAL,
+ * -- identifies the transaction; i.e., this will be the same in
+ * -- corresponding request, response, certConf, and PKIConf
+ * -- messages
+ * senderNonce [5] OCTET STRING OPTIONAL,
+ * recipNonce [6] OCTET STRING OPTIONAL,
+ * -- nonces used to provide replay protection, senderNonce
+ * -- is inserted by the creator of this message; recipNonce
+ * -- is a nonce previously inserted in a related message by
+ * -- the intended recipient of this message
+ * freeText [7] PKIFreeText OPTIONAL,
+ * -- this may be used to indicate context-specific instructions
+ * -- (this field is intended for human consumption)
+ * generalInfo [8] SEQUENCE SIZE (1..MAX) OF
+ * InfoTypeAndValue OPTIONAL
+ * -- this may be used to convey context-specific information
+ * -- (this field not primarily intended for human consumption)
+ * }
+ *
+ * PKIHeader ::= SEQUENCE {
+ * pvno INTEGER { cmp1999(1), cmp2000(2) },
+ * sender GeneralName,
+ * -- identifies the sender
+ * recipient GeneralName,
+ * -- identifies the intended recipient
+ * messageTime [0] GeneralizedTime OPTIONAL,
+ * -- time of production of this message (used when sender
+ * -- believes that the transport will be "suitable"; i.e.,
+ * -- that the time will still be meaningful upon receipt)
+ * protectionAlg [1] AlgorithmIdentifier OPTIONAL,
+ * -- algorithm used for calculation of protection bits
+ * senderKID [2] KeyIdentifier OPTIONAL,
+ * recipKID [3] KeyIdentifier OPTIONAL,
+ * -- to identify specific keys used for protection
+ * transactionID [4] OCTET STRING OPTIONAL,
+ * -- identifies the transaction; i.e., this will be the same in
+ * -- corresponding request, response, certConf, and PKIConf
+ * -- messages
+ * senderNonce [5] OCTET STRING OPTIONAL,
+ * recipNonce [6] OCTET STRING OPTIONAL,
+ * -- nonces used to provide replay protection, senderNonce
+ * -- is inserted by the creator of this message; recipNonce
+ * -- is a nonce previously inserted in a related message by
+ * -- the intended recipient of this message
+ * freeText [7] PKIFreeText OPTIONAL,
+ * -- this may be used to indicate context-specific instructions
+ * -- (this field is intended for human consumption)
+ * generalInfo [8] SEQUENCE SIZE (1..MAX) OF
+ * InfoTypeAndValue OPTIONAL
+ * -- this may be used to convey context-specific information
+ * -- (this field not primarily intended for human consumption)
+ * }
+ *
+ * PkiStatusInfo ::= SEQUENCE {
+ * status PKIStatus, (INTEGER)
+ * statusString PkiFreeText OPTIONAL,
+ * failInfo PkiFailureInfo OPTIONAL (BIT STRING)
+ * }
+ *
+ * PKIStatus:
+ * granted (0), -- you got exactly what you asked for
+ * grantedWithMods (1), -- you got something like what you asked for
+ * rejection (2), -- you don't get it, more information elsewhere in the message
+ * waiting (3), -- the request body part has not yet been processed, expect to hear more later
+ * revocationWarning (4), -- this message contains a warning that a revocation is imminent
+ * revocationNotification (5), -- notification that a revocation has occurred
+ * keyUpdateWarning (6) -- update already done for the oldCertId specified in CertReqMsg
+ *
+ * PkiFailureInfo:
+ * badAlg (0), -- unrecognized or unsupported Algorithm Identifier
+ * badMessageCheck (1), -- integrity check failed (e.g., signature did not verify)
+ * badRequest (2), -- transaction not permitted or supported
+ * badTime (3), -- messageTime was not sufficiently close to the system time, as defined by local policy
+ * badCertId (4), -- no certificate could be found matching the provided criteria
+ * badDataFormat (5), -- the data submitted has the wrong format
+ * wrongAuthority (6), -- the authority indicated in the request is different from the one creating the response token
+ * incorrectData (7), -- the requester's data is incorrect (for notary services)
+ * missingTimeStamp (8), -- when the timestamp is missing but should be there (by policy)
+ * badPOP (9) -- the proof-of-possession failed
+ *
+ *
+ * PbmParameter ::= SEQUENCE {
+ * salt OCTET STRING,
+ * -- note: implementations MAY wish to limit acceptable sizes
+ * -- of this string to values appropriate for their environment
+ * -- in order to reduce the risk of denial-of-service attacks
+ * owf AlgorithmIdentifier,
+ * -- AlgId for a One-Way Function (SHA-1 recommended)
+ * iterationCount INTEGER,
+ * -- number of times the OWF is applied
+ * -- note: implementations MAY wish to limit acceptable sizes
+ * -- of this integer to values appropriate for their environment
+ * -- in order to reduce the risk of denial-of-service attacks
+ * mac AlgorithmIdentifier
+ * -- the MAC AlgId (e.g., DES-MAC, Triple-DES-MAC [PKCS11],
+ * } -- or HMAC [RFC2104, RFC2202])
+ *
+ * RevDetails ::= SEQUENCE {
+ * certDetails CertTemplate,
+ * -- allows requester to specify as much as they can about
+ * -- the cert. for which revocation is requested
+ * -- (e.g., for cases in which serialNumber is not available)
+ * crlEntryDetails Extensions OPTIONAL
+ * -- requested crlEntryExtensions
+ * }
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector(certDetails);
+ v.AddOptional(crlEntryDetails);
+ return new DerSequence(v);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/RevDetails.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/RevDetails.cs.meta
new file mode 100644
index 00000000..733f620d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/RevDetails.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: f46b291060b224942bd837481375c005
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/RevRepContent.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/RevRepContent.cs
new file mode 100644
index 00000000..bfc27b28
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/RevRepContent.cs
@@ -0,0 +1,117 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Crmf;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp
+{
+ public class RevRepContent
+ : Asn1Encodable
+ {
+ private readonly Asn1Sequence status;
+ private readonly Asn1Sequence revCerts;
+ private readonly Asn1Sequence crls;
+
+ private RevRepContent(Asn1Sequence seq)
+ {
+ status = Asn1Sequence.GetInstance(seq[0]);
+
+ for (int pos = 1; pos < seq.Count; ++pos)
+ {
+ Asn1TaggedObject tObj = Asn1TaggedObject.GetInstance(seq[pos]);
+
+ if (tObj.TagNo == 0)
+ {
+ revCerts = Asn1Sequence.GetInstance(tObj, true);
+ }
+ else
+ {
+ crls = Asn1Sequence.GetInstance(tObj, true);
+ }
+ }
+ }
+
+ public static RevRepContent GetInstance(object obj)
+ {
+ if (obj is RevRepContent)
+ return (RevRepContent)obj;
+
+ if (obj is Asn1Sequence)
+ return new RevRepContent((Asn1Sequence)obj);
+
+ throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+ }
+
+ public virtual PkiStatusInfo[] GetStatus()
+ {
+ PkiStatusInfo[] results = new PkiStatusInfo[status.Count];
+ for (int i = 0; i != results.Length; ++i)
+ {
+ results[i] = PkiStatusInfo.GetInstance(status[i]);
+ }
+ return results;
+ }
+
+ public virtual CertId[] GetRevCerts()
+ {
+ if (revCerts == null)
+ return null;
+
+ CertId[] results = new CertId[revCerts.Count];
+ for (int i = 0; i != results.Length; ++i)
+ {
+ results[i] = CertId.GetInstance(revCerts[i]);
+ }
+ return results;
+ }
+
+ public virtual CertificateList[] GetCrls()
+ {
+ if (crls == null)
+ return null;
+
+ CertificateList[] results = new CertificateList[crls.Count];
+ for (int i = 0; i != results.Length; ++i)
+ {
+ results[i] = CertificateList.GetInstance(crls[i]);
+ }
+ return results;
+ }
+
+ /**
+ *
+ * RevRepContent ::= SEQUENCE {
+ * status SEQUENCE SIZE (1..MAX) OF PKIStatusInfo,
+ * -- in same order as was sent in RevReqContent
+ * revCerts [0] SEQUENCE SIZE (1..MAX) OF CertId OPTIONAL,
+ * -- IDs for which revocation was requested
+ * -- (same order as status)
+ * crls [1] SEQUENCE SIZE (1..MAX) OF CertificateList OPTIONAL
+ * -- the resulting CRLs (there may be more than one)
+ * }
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector(status);
+ AddOptional(v, 0, revCerts);
+ AddOptional(v, 1, crls);
+ return new DerSequence(v);
+ }
+
+ private void AddOptional(Asn1EncodableVector v, int tagNo, Asn1Encodable obj)
+ {
+ if (obj != null)
+ {
+ v.Add(new DerTaggedObject(true, tagNo, obj));
+ }
+ }
+ }
+}
+
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/RevRepContent.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/RevRepContent.cs.meta
new file mode 100644
index 00000000..76f4795c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/RevRepContent.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 345761cabacdee14199048da28d3c395
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/RevRepContentBuilder.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/RevRepContentBuilder.cs
new file mode 100644
index 00000000..3d82c6f6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/RevRepContentBuilder.cs
@@ -0,0 +1,59 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Crmf;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp
+{
+ public class RevRepContentBuilder
+ {
+ private readonly Asn1EncodableVector status = new Asn1EncodableVector();
+ private readonly Asn1EncodableVector revCerts = new Asn1EncodableVector();
+ private readonly Asn1EncodableVector crls = new Asn1EncodableVector();
+
+ public virtual RevRepContentBuilder Add(PkiStatusInfo status)
+ {
+ this.status.Add(status);
+ return this;
+ }
+
+ public virtual RevRepContentBuilder Add(PkiStatusInfo status, CertId certId)
+ {
+ if (this.status.Count != this.revCerts.Count)
+ throw new InvalidOperationException("status and revCerts sequence must be in common order");
+
+ this.status.Add(status);
+ this.revCerts.Add(certId);
+ return this;
+ }
+
+ public virtual RevRepContentBuilder AddCrl(CertificateList crl)
+ {
+ this.crls.Add(crl);
+ return this;
+ }
+
+ public virtual RevRepContent Build()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector();
+
+ v.Add(new DerSequence(status));
+
+ if (revCerts.Count != 0)
+ {
+ v.Add(new DerTaggedObject(true, 0, new DerSequence(revCerts)));
+ }
+
+ if (crls.Count != 0)
+ {
+ v.Add(new DerTaggedObject(true, 1, new DerSequence(crls)));
+ }
+
+ return RevRepContent.GetInstance(new DerSequence(v));
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/RevRepContentBuilder.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/RevRepContentBuilder.cs.meta
new file mode 100644
index 00000000..2be8b500
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/RevRepContentBuilder.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c0470f2df4fce4e44a4fe1b0bab3e09d
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/RevReqContent.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/RevReqContent.cs
new file mode 100644
index 00000000..8ac7dad7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/RevReqContent.cs
@@ -0,0 +1,58 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp
+{
+ public class RevReqContent
+ : Asn1Encodable
+ {
+ private readonly Asn1Sequence content;
+
+ private RevReqContent(Asn1Sequence seq)
+ {
+ content = seq;
+ }
+
+ public static RevReqContent GetInstance(object obj)
+ {
+ if (obj is RevReqContent)
+ return (RevReqContent)obj;
+
+ if (obj is Asn1Sequence)
+ return new RevReqContent((Asn1Sequence)obj);
+
+ throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+ }
+
+ public RevReqContent(params RevDetails[] revDetails)
+ {
+ this.content = new DerSequence(revDetails);
+ }
+
+ public virtual RevDetails[] ToRevDetailsArray()
+ {
+ RevDetails[] result = new RevDetails[content.Count];
+ for (int i = 0; i != result.Length; ++i)
+ {
+ result[i] = RevDetails.GetInstance(content[i]);
+ }
+ return result;
+ }
+
+ /**
+ *
+ * RevReqContent ::= SEQUENCE OF RevDetails
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ return content;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/RevReqContent.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/RevReqContent.cs.meta
new file mode 100644
index 00000000..edf08dd2
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cmp/RevReqContent.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ca8dfb330261e2f449c12dd74b53fde3
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cms.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cms.meta
new file mode 100644
index 00000000..6b0ededd
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cms.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 212c4beac220c8742966c43564131081
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cms/Attribute.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cms/Attribute.cs
new file mode 100644
index 00000000..2baee6e8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/cms/Attribute.cs
@@ -0,0 +1,74 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms
+{
+ public class Attribute
+ : Asn1Encodable
+ {
+ private DerObjectIdentifier attrType;
+ private Asn1Set attrValues;
+
+ /**
+ * return an Attribute object from the given object.
+ *
+ * @param o the object we want converted.
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static Attribute GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is Attribute)
+ return (Attribute) obj;
+
+ if (obj is Asn1Sequence)
+ return new Attribute((Asn1Sequence) obj);
+
+ throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+ }
+
+ public Attribute(
+ Asn1Sequence seq)
+ {
+ attrType = (DerObjectIdentifier)seq[0];
+ attrValues = (Asn1Set)seq[1];
+ }
+
+ public Attribute(
+ DerObjectIdentifier attrType,
+ Asn1Set attrValues)
+ {
+ this.attrType = attrType;
+ this.attrValues = attrValues;
+ }
+
+ public DerObjectIdentifier AttrType
+ {
+ get { return attrType; }
+ }
+
+ public Asn1Set AttrValues
+ {
+ get { return attrValues; }
+ }
+
+ /**
+ * Produce an object suitable for an Asn1OutputStream.
+ *
+ * EncryptedValue ::= SEQUENCE {
+ * intendedAlg [0] AlgorithmIdentifier OPTIONAL,
+ * -- the intended algorithm for which the value will be used
+ * symmAlg [1] AlgorithmIdentifier OPTIONAL,
+ * -- the symmetric algorithm used to encrypt the value
+ * encSymmKey [2] BIT STRING OPTIONAL,
+ * -- the (encrypted) symmetric key used to encrypt the value
+ * keyAlg [3] AlgorithmIdentifier OPTIONAL,
+ * -- algorithm used to encrypt the symmetric key
+ * valueHint [4] OCTET STRING OPTIONAL,
+ * -- a brief description or identifier of the encValue content
+ * -- (may be meaningful only to the sending entity, and used only
+ * -- if EncryptedValue might be re-examined by the sending entity
+ * -- in the future)
+ * encValue BIT STRING }
+ * -- the encrypted value itself
+ *
+ * OptionalValidity ::= SEQUENCE {
+ * notBefore [0] Time OPTIONAL,
+ * notAfter [1] Time OPTIONAL } --at least one MUST be present
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector();
+
+ if (notBefore != null)
+ {
+ v.Add(new DerTaggedObject(true, 0, notBefore));
+ }
+
+ if (notAfter != null)
+ {
+ v.Add(new DerTaggedObject(true, 1, notAfter));
+ }
+
+ return new DerSequence(v);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/OptionalValidity.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/OptionalValidity.cs.meta
new file mode 100644
index 00000000..360a4554
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/OptionalValidity.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: d6de9f44c885f284d97ff26f588e3437
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PKIArchiveOptions.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PKIArchiveOptions.cs
new file mode 100644
index 00000000..d4a72da6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PKIArchiveOptions.cs
@@ -0,0 +1,111 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Crmf
+{
+ public class PkiArchiveOptions
+ : Asn1Encodable, IAsn1Choice
+ {
+ public const int encryptedPrivKey = 0;
+ public const int keyGenParameters = 1;
+ public const int archiveRemGenPrivKey = 2;
+
+ private readonly Asn1Encodable value;
+
+ public static PkiArchiveOptions GetInstance(object obj)
+ {
+ if (obj is PkiArchiveOptions)
+ return (PkiArchiveOptions)obj;
+
+ if (obj is Asn1TaggedObject)
+ return new PkiArchiveOptions((Asn1TaggedObject)obj);
+
+ throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+ }
+
+ private PkiArchiveOptions(Asn1TaggedObject tagged)
+ {
+ switch (tagged.TagNo)
+ {
+ case encryptedPrivKey:
+ value = EncryptedKey.GetInstance(tagged.GetObject());
+ break;
+ case keyGenParameters:
+ value = Asn1OctetString.GetInstance(tagged, false);
+ break;
+ case archiveRemGenPrivKey:
+ value = DerBoolean.GetInstance(tagged, false);
+ break;
+ default:
+ throw new ArgumentException("unknown tag number: " + tagged.TagNo, "tagged");
+ }
+ }
+
+ public PkiArchiveOptions(EncryptedKey encKey)
+ {
+ this.value = encKey;
+ }
+
+ public PkiArchiveOptions(Asn1OctetString keyGenParameters)
+ {
+ this.value = keyGenParameters;
+ }
+
+ public PkiArchiveOptions(bool archiveRemGenPrivKey)
+ {
+ this.value = DerBoolean.GetInstance(archiveRemGenPrivKey);
+ }
+
+ public virtual int Type
+ {
+ get
+ {
+ if (value is EncryptedKey)
+ return encryptedPrivKey;
+
+ if (value is Asn1OctetString)
+ return keyGenParameters;
+
+ return archiveRemGenPrivKey;
+ }
+ }
+
+ public virtual Asn1Encodable Value
+ {
+ get { return value; }
+ }
+
+ /**
+ *
+ * PkiArchiveOptions ::= CHOICE {
+ * encryptedPrivKey [0] EncryptedKey,
+ * -- the actual value of the private key
+ * keyGenParameters [1] KeyGenParameters,
+ * -- parameters which allow the private key to be re-generated
+ * archiveRemGenPrivKey [2] BOOLEAN }
+ * -- set to TRUE if sender wishes receiver to archive the private
+ * -- key of a key pair that the receiver generates in response to
+ * -- this request; set to FALSE if no archival is desired.
+ *
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ if (value is EncryptedKey)
+ {
+ return new DerTaggedObject(true, encryptedPrivKey, value); // choice
+ }
+
+ if (value is Asn1OctetString)
+ {
+ return new DerTaggedObject(false, keyGenParameters, value);
+ }
+
+ return new DerTaggedObject(false, archiveRemGenPrivKey, value);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PKIArchiveOptions.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PKIArchiveOptions.cs.meta
new file mode 100644
index 00000000..335884aa
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PKIArchiveOptions.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: eaa126763652fd9439d5bf4d5b5462b6
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PKIPublicationInfo.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PKIPublicationInfo.cs
new file mode 100644
index 00000000..0f6f4cac
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PKIPublicationInfo.cs
@@ -0,0 +1,70 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Crmf
+{
+ public class PkiPublicationInfo
+ : Asn1Encodable
+ {
+ private readonly DerInteger action;
+ private readonly Asn1Sequence pubInfos;
+
+ private PkiPublicationInfo(Asn1Sequence seq)
+ {
+ action = DerInteger.GetInstance(seq[0]);
+ pubInfos = Asn1Sequence.GetInstance(seq[1]);
+ }
+
+ public static PkiPublicationInfo GetInstance(object obj)
+ {
+ if (obj is PkiPublicationInfo)
+ return (PkiPublicationInfo)obj;
+
+ if (obj is Asn1Sequence)
+ return new PkiPublicationInfo((Asn1Sequence)obj);
+
+ throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+ }
+
+ public virtual DerInteger Action
+ {
+ get { return action; }
+ }
+
+ public virtual SinglePubInfo[] GetPubInfos()
+ {
+ if (pubInfos == null)
+ return null;
+
+ SinglePubInfo[] results = new SinglePubInfo[pubInfos.Count];
+ for (int i = 0; i != results.Length; ++i)
+ {
+ results[i] = SinglePubInfo.GetInstance(pubInfos[i]);
+ }
+ return results;
+ }
+
+ /**
+ *
+ * PkiPublicationInfo ::= SEQUENCE {
+ * action INTEGER {
+ * dontPublish (0),
+ * pleasePublish (1) },
+ * pubInfos SEQUENCE SIZE (1..MAX) OF SinglePubInfo OPTIONAL }
+ * -- pubInfos MUST NOT be present if action is "dontPublish"
+ * -- (if action is "pleasePublish" and pubInfos is omitted,
+ * -- "dontCare" is assumed)
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerSequence(action, pubInfos);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PKIPublicationInfo.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PKIPublicationInfo.cs.meta
new file mode 100644
index 00000000..84c2b54a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PKIPublicationInfo.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: de4b7fe794a82644eadd8807a60cd8f6
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PKMacValue.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PKMacValue.cs
new file mode 100644
index 00000000..5d0553ed
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PKMacValue.cs
@@ -0,0 +1,94 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Crmf
+{
+ /**
+ * Password-based MAC value for use with POPOSigningKeyInput.
+ */
+ public class PKMacValue
+ : Asn1Encodable
+ {
+ private readonly AlgorithmIdentifier algID;
+ private readonly DerBitString macValue;
+
+ private PKMacValue(Asn1Sequence seq)
+ {
+ this.algID = AlgorithmIdentifier.GetInstance(seq[0]);
+ this.macValue = DerBitString.GetInstance(seq[1]);
+ }
+
+ public static PKMacValue GetInstance(object obj)
+ {
+ if (obj is PKMacValue)
+ return (PKMacValue)obj;
+
+ if (obj is Asn1Sequence)
+ return new PKMacValue((Asn1Sequence)obj);
+
+ throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+ }
+
+ public static PKMacValue GetInstance(Asn1TaggedObject obj, bool isExplicit)
+ {
+ return GetInstance(Asn1Sequence.GetInstance(obj, isExplicit));
+ }
+
+ /**
+ * Creates a new PKMACValue.
+ * @param params parameters for password-based MAC
+ * @param value MAC of the DER-encoded SubjectPublicKeyInfo
+ */
+ public PKMacValue(
+ PbmParameter pbmParams,
+ DerBitString macValue)
+ : this(new AlgorithmIdentifier(CmpObjectIdentifiers.passwordBasedMac, pbmParams), macValue)
+ {
+ }
+
+ /**
+ * Creates a new PKMACValue.
+ * @param aid CMPObjectIdentifiers.passwordBasedMAC, with PBMParameter
+ * @param value MAC of the DER-encoded SubjectPublicKeyInfo
+ */
+ public PKMacValue(
+ AlgorithmIdentifier algID,
+ DerBitString macValue)
+ {
+ this.algID = algID;
+ this.macValue = macValue;
+ }
+
+ public virtual AlgorithmIdentifier AlgID
+ {
+ get { return algID; }
+ }
+
+ public virtual DerBitString MacValue
+ {
+ get { return macValue; }
+ }
+
+ /**
+ *
+ * PKMACValue ::= SEQUENCE {
+ * algId AlgorithmIdentifier,
+ * -- algorithm value shall be PasswordBasedMac 1.2.840.113533.7.66.13
+ * -- parameter value is PBMParameter
+ * value BIT STRING }
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerSequence(algID, macValue);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PKMacValue.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PKMacValue.cs.meta
new file mode 100644
index 00000000..72421417
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PKMacValue.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: d5c2d9623df92ba49b7e5fa1a8da0847
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PopoPrivKey.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PopoPrivKey.cs
new file mode 100644
index 00000000..a53773ee
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PopoPrivKey.cs
@@ -0,0 +1,88 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Crmf
+{
+ public class PopoPrivKey
+ : Asn1Encodable, IAsn1Choice
+ {
+ public const int thisMessage = 0;
+ public const int subsequentMessage = 1;
+ public const int dhMAC = 2;
+ public const int agreeMAC = 3;
+ public const int encryptedKey = 4;
+
+ private readonly int tagNo;
+ private readonly Asn1Encodable obj;
+
+ private PopoPrivKey(Asn1TaggedObject obj)
+ {
+ this.tagNo = obj.TagNo;
+
+ switch (tagNo)
+ {
+ case thisMessage:
+ this.obj = DerBitString.GetInstance(obj, false);
+ break;
+ case subsequentMessage:
+ this.obj = SubsequentMessage.ValueOf(DerInteger.GetInstance(obj, false).Value.IntValue);
+ break;
+ case dhMAC:
+ this.obj = DerBitString.GetInstance(obj, false);
+ break;
+ case agreeMAC:
+ this.obj = PKMacValue.GetInstance(obj, false);
+ break;
+ case encryptedKey:
+ this.obj = EnvelopedData.GetInstance(obj, false);
+ break;
+ default:
+ throw new ArgumentException("unknown tag in PopoPrivKey", "obj");
+ }
+ }
+
+ public static PopoPrivKey GetInstance(Asn1TaggedObject tagged, bool isExplicit)
+ {
+ return new PopoPrivKey(Asn1TaggedObject.GetInstance(tagged.GetObject()));
+ }
+
+ public PopoPrivKey(SubsequentMessage msg)
+ {
+ this.tagNo = subsequentMessage;
+ this.obj = msg;
+ }
+
+ public virtual int Type
+ {
+ get { return tagNo; }
+ }
+
+ public virtual Asn1Encodable Value
+ {
+ get { return obj; }
+ }
+
+ /**
+ *
+ * PopoPrivKey ::= CHOICE {
+ * thisMessage [0] BIT STRING, -- Deprecated
+ * -- possession is proven in this message (which contains the private
+ * -- key itself (encrypted for the CA))
+ * subsequentMessage [1] SubsequentMessage,
+ * -- possession will be proven in a subsequent message
+ * dhMAC [2] BIT STRING, -- Deprecated
+ * agreeMAC [3] PKMACValue,
+ * encryptedKey [4] EnvelopedData }
+ *
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerTaggedObject(false, tagNo, obj);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PopoPrivKey.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PopoPrivKey.cs.meta
new file mode 100644
index 00000000..53ec0130
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PopoPrivKey.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: d95dc5442df1cd644ab2f400b01d5596
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PopoSigningKey.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PopoSigningKey.cs
new file mode 100644
index 00000000..92c0e104
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PopoSigningKey.cs
@@ -0,0 +1,120 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Crmf
+{
+ public class PopoSigningKey
+ : Asn1Encodable
+ {
+ private readonly PopoSigningKeyInput poposkInput;
+ private readonly AlgorithmIdentifier algorithmIdentifier;
+ private readonly DerBitString signature;
+
+ private PopoSigningKey(Asn1Sequence seq)
+ {
+ int index = 0;
+
+ if (seq[index] is Asn1TaggedObject)
+ {
+ Asn1TaggedObject tagObj
+ = (Asn1TaggedObject) seq[index++];
+ if (tagObj.TagNo != 0)
+ {
+ throw new ArgumentException( "Unknown PopoSigningKeyInput tag: " + tagObj.TagNo, "seq");
+ }
+ poposkInput = PopoSigningKeyInput.GetInstance(tagObj.GetObject());
+ }
+ algorithmIdentifier = AlgorithmIdentifier.GetInstance(seq[index++]);
+ signature = DerBitString.GetInstance(seq[index]);
+ }
+
+ public static PopoSigningKey GetInstance(object obj)
+ {
+ if (obj is PopoSigningKey)
+ return (PopoSigningKey)obj;
+
+ if (obj is Asn1Sequence)
+ return new PopoSigningKey((Asn1Sequence)obj);
+
+ throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+ }
+
+ public static PopoSigningKey GetInstance(Asn1TaggedObject obj, bool isExplicit)
+ {
+ return GetInstance(Asn1Sequence.GetInstance(obj, isExplicit));
+ }
+
+ /**
+ * Creates a new Proof of Possession object for a signing key.
+ * @param poposkIn the PopoSigningKeyInput structure, or null if the
+ * CertTemplate includes both subject and publicKey values.
+ * @param aid the AlgorithmIdentifier used to sign the proof of possession.
+ * @param signature a signature over the DER-encoded value of poposkIn,
+ * or the DER-encoded value of certReq if poposkIn is null.
+ */
+ public PopoSigningKey(
+ PopoSigningKeyInput poposkIn,
+ AlgorithmIdentifier aid,
+ DerBitString signature)
+ {
+ this.poposkInput = poposkIn;
+ this.algorithmIdentifier = aid;
+ this.signature = signature;
+ }
+
+ public virtual PopoSigningKeyInput PoposkInput
+ {
+ get { return poposkInput; }
+ }
+
+ public virtual AlgorithmIdentifier AlgorithmIdentifier
+ {
+ get { return algorithmIdentifier; }
+ }
+
+ public virtual DerBitString Signature
+ {
+ get { return signature; }
+ }
+
+ /**
+ *
+ * PopoSigningKey ::= SEQUENCE {
+ * poposkInput [0] PopoSigningKeyInput OPTIONAL,
+ * algorithmIdentifier AlgorithmIdentifier,
+ * signature BIT STRING }
+ * -- The signature (using "algorithmIdentifier") is on the
+ * -- DER-encoded value of poposkInput. NOTE: If the CertReqMsg
+ * -- certReq CertTemplate contains the subject and publicKey values,
+ * -- then poposkInput MUST be omitted and the signature MUST be
+ * -- computed on the DER-encoded value of CertReqMsg certReq. If
+ * -- the CertReqMsg certReq CertTemplate does not contain the public
+ * -- key and subject values, then poposkInput MUST be present and
+ * -- MUST be signed. This strategy ensures that the public key is
+ * -- not present in both the poposkInput and CertReqMsg certReq
+ * -- CertTemplate fields.
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector();
+
+ if (poposkInput != null)
+ {
+ v.Add(new DerTaggedObject(false, 0, poposkInput));
+ }
+
+ v.Add(algorithmIdentifier);
+ v.Add(signature);
+
+ return new DerSequence(v);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PopoSigningKey.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PopoSigningKey.cs.meta
new file mode 100644
index 00000000..3f372b54
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PopoSigningKey.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ec8a4d88bfe18d741b1a1b7358aa692e
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PopoSigningKeyInput.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PopoSigningKeyInput.cs
new file mode 100644
index 00000000..7d7d3507
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PopoSigningKeyInput.cs
@@ -0,0 +1,120 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Crmf
+{
+ public class PopoSigningKeyInput
+ : Asn1Encodable
+ {
+ private readonly GeneralName sender;
+ private readonly PKMacValue publicKeyMac;
+ private readonly SubjectPublicKeyInfo publicKey;
+
+ private PopoSigningKeyInput(Asn1Sequence seq)
+ {
+ Asn1Encodable authInfo = (Asn1Encodable)seq[0];
+
+ if (authInfo is Asn1TaggedObject)
+ {
+ Asn1TaggedObject tagObj = (Asn1TaggedObject)authInfo;
+ if (tagObj.TagNo != 0)
+ {
+ throw new ArgumentException("Unknown authInfo tag: " + tagObj.TagNo, "seq");
+ }
+ sender = GeneralName.GetInstance(tagObj.GetObject());
+ }
+ else
+ {
+ publicKeyMac = PKMacValue.GetInstance(authInfo);
+ }
+
+ publicKey = SubjectPublicKeyInfo.GetInstance(seq[1]);
+ }
+
+ public static PopoSigningKeyInput GetInstance(object obj)
+ {
+ if (obj is PopoSigningKeyInput)
+ return (PopoSigningKeyInput)obj;
+
+ if (obj is Asn1Sequence)
+ return new PopoSigningKeyInput((Asn1Sequence)obj);
+
+ throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+ }
+
+ /** Creates a new PopoSigningKeyInput with sender name as authInfo. */
+ public PopoSigningKeyInput(
+ GeneralName sender,
+ SubjectPublicKeyInfo spki)
+ {
+ this.sender = sender;
+ this.publicKey = spki;
+ }
+
+ /** Creates a new PopoSigningKeyInput using password-based MAC. */
+ public PopoSigningKeyInput(
+ PKMacValue pkmac,
+ SubjectPublicKeyInfo spki)
+ {
+ this.publicKeyMac = pkmac;
+ this.publicKey = spki;
+ }
+
+ /** Returns the sender field, or null if authInfo is publicKeyMac */
+ public virtual GeneralName Sender
+ {
+ get { return sender; }
+ }
+
+ /** Returns the publicKeyMac field, or null if authInfo is sender */
+ public virtual PKMacValue PublicKeyMac
+ {
+ get { return publicKeyMac; }
+ }
+
+ public virtual SubjectPublicKeyInfo PublicKey
+ {
+ get { return publicKey; }
+ }
+
+ /**
+ *
+ * PopoSigningKeyInput ::= SEQUENCE {
+ * authInfo CHOICE {
+ * sender [0] GeneralName,
+ * -- used only if an authenticated identity has been
+ * -- established for the sender (e.g., a DN from a
+ * -- previously-issued and currently-valid certificate
+ * publicKeyMac PKMacValue },
+ * -- used if no authenticated GeneralName currently exists for
+ * -- the sender; publicKeyMac contains a password-based MAC
+ * -- on the DER-encoded value of publicKey
+ * publicKey SubjectPublicKeyInfo } -- from CertTemplate
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector();
+
+ if (sender != null)
+ {
+ v.Add(new DerTaggedObject(false, 0, sender));
+ }
+ else
+ {
+ v.Add(publicKeyMac);
+ }
+
+ v.Add(publicKey);
+
+ return new DerSequence(v);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PopoSigningKeyInput.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PopoSigningKeyInput.cs.meta
new file mode 100644
index 00000000..fe43e4b7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/PopoSigningKeyInput.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 905c188ed11f8c7409e765172165a1f5
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/ProofOfPossession.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/ProofOfPossession.cs
new file mode 100644
index 00000000..ad7ccbe3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/crmf/ProofOfPossession.cs
@@ -0,0 +1,104 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Crmf
+{
+ public class ProofOfPossession
+ : Asn1Encodable, IAsn1Choice
+ {
+ public const int TYPE_RA_VERIFIED = 0;
+ public const int TYPE_SIGNING_KEY = 1;
+ public const int TYPE_KEY_ENCIPHERMENT = 2;
+ public const int TYPE_KEY_AGREEMENT = 3;
+
+ private readonly int tagNo;
+ private readonly Asn1Encodable obj;
+
+ private ProofOfPossession(Asn1TaggedObject tagged)
+ {
+ tagNo = tagged.TagNo;
+ switch (tagNo)
+ {
+ case 0:
+ obj = DerNull.Instance;
+ break;
+ case 1:
+ obj = PopoSigningKey.GetInstance(tagged, false);
+ break;
+ case 2:
+ case 3:
+ obj = PopoPrivKey.GetInstance(tagged, false);
+ break;
+ default:
+ throw new ArgumentException("unknown tag: " + tagNo, "tagged");
+ }
+ }
+
+ public static ProofOfPossession GetInstance(object obj)
+ {
+ if (obj is ProofOfPossession)
+ return (ProofOfPossession)obj;
+
+ if (obj is Asn1TaggedObject)
+ return new ProofOfPossession((Asn1TaggedObject)obj);
+
+ throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+ }
+
+ /** Creates a ProofOfPossession with type raVerified. */
+ public ProofOfPossession()
+ {
+ tagNo = TYPE_RA_VERIFIED;
+ obj = DerNull.Instance;
+ }
+
+ /** Creates a ProofOfPossession for a signing key. */
+ public ProofOfPossession(PopoSigningKey Poposk)
+ {
+ tagNo = TYPE_SIGNING_KEY;
+ obj = Poposk;
+ }
+
+ /**
+ * Creates a ProofOfPossession for key encipherment or agreement.
+ * @param type one of TYPE_KEY_ENCIPHERMENT or TYPE_KEY_AGREEMENT
+ */
+ public ProofOfPossession(int type, PopoPrivKey privkey)
+ {
+ tagNo = type;
+ obj = privkey;
+ }
+
+ public virtual int Type
+ {
+ get { return tagNo; }
+ }
+
+ public virtual Asn1Encodable Object
+ {
+ get { return obj; }
+ }
+
+ /**
+ *
+ * ProofOfPossession ::= CHOICE {
+ * raVerified [0] NULL,
+ * -- used if the RA has already verified that the requester is in
+ * -- possession of the private key
+ * signature [1] PopoSigningKey,
+ * keyEncipherment [2] PopoPrivKey,
+ * keyAgreement [3] PopoPrivKey }
+ *
+ * @return
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerSequence(ldsVersion, unicodeVersion);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/icao/LDSVersionInfo.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/icao/LDSVersionInfo.cs.meta
new file mode 100644
index 00000000..f0b9007d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/icao/LDSVersionInfo.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: bc5cd50c808246b4ea60097a0befbc88
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/isismtt.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/isismtt.meta
new file mode 100644
index 00000000..d0ce4def
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/isismtt.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: f34c4124bf07f0a4a99df098156d3a27
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/isismtt/ISISMTTObjectIdentifiers.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/isismtt/ISISMTTObjectIdentifiers.cs
new file mode 100644
index 00000000..09678c5a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/isismtt/ISISMTTObjectIdentifiers.cs
@@ -0,0 +1,181 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.IsisMtt
+{
+ public abstract class IsisMttObjectIdentifiers
+ {
+ public static readonly DerObjectIdentifier IdIsisMtt = new DerObjectIdentifier("1.3.36.8");
+
+ public static readonly DerObjectIdentifier IdIsisMttCP = new DerObjectIdentifier(IdIsisMtt + ".1");
+
+ /**
+ * The id-isismtt-cp-accredited OID indicates that the certificate is a
+ * qualified certificate according to Directive 1999/93/EC of the European
+ * Parliament and of the Council of 13 December 1999 on a Community
+ * Framework for Electronic Signatures, which additionally conforms the
+ * special requirements of the SigG and has been issued by an accredited CA.
+ */
+ public static readonly DerObjectIdentifier IdIsisMttCPAccredited = new DerObjectIdentifier(IdIsisMttCP + ".1");
+
+ public static readonly DerObjectIdentifier IdIsisMttAT = new DerObjectIdentifier(IdIsisMtt + ".3");
+
+ /**
+ * Certificate extensionDate of certificate generation
+ *
+ *
+ * DateOfCertGenSyntax ::= GeneralizedTime
+ *
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATDateOfCertGen = new DerObjectIdentifier(IdIsisMttAT + ".1");
+
+ /**
+ * Attribute to indicate that the certificate holder may sign in the name of
+ * a third person. May also be used as extension in a certificate.
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATProcuration = new DerObjectIdentifier(IdIsisMttAT + ".2");
+
+ /**
+ * Attribute to indicate admissions to certain professions. May be used as
+ * attribute in attribute certificate or as extension in a certificate
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATAdmission = new DerObjectIdentifier(IdIsisMttAT + ".3");
+
+ /**
+ * Monetary limit for transactions. The QcEuMonetaryLimit QC statement MUST
+ * be used in new certificates in place of the extension/attribute
+ * MonetaryLimit since January 1, 2004. For the sake of backward
+ * compatibility with certificates already in use, SigG conforming
+ * components MUST support MonetaryLimit (as well as QcEuLimitValue).
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATMonetaryLimit = new DerObjectIdentifier(IdIsisMttAT + ".4");
+
+ /**
+ * A declaration of majority. May be used as attribute in attribute
+ * certificate or as extension in a certificate
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATDeclarationOfMajority = new DerObjectIdentifier(IdIsisMttAT + ".5");
+
+ /**
+ *
+ * Serial number of the smart card containing the corresponding private key
+ *
+ *
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATIccsn = new DerObjectIdentifier(IdIsisMttAT + ".6");
+
+ /**
+ *
+ * Reference for a file of a smartcard that stores the public key of this
+ * certificate and that is used as �security anchor�.
+ *
+ *
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATPKReference = new DerObjectIdentifier(IdIsisMttAT + ".7");
+
+ /**
+ * Some other restriction regarding the usage of this certificate. May be
+ * used as attribute in attribute certificate or as extension in a
+ * certificate.
+ *
+ *
+ *
+ * @see BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.IsisMtt.X509.Restriction
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATRestriction = new DerObjectIdentifier(IdIsisMttAT + ".8");
+
+ /**
+ *
+ * (Single)Request extension: Clients may include this extension in a
+ * (single) Request to request the responder to send the certificate in the
+ * response message along with the status information. Besides the LDAP
+ * service, this extension provides another mechanism for the distribution
+ * of certificates, which MAY optionally be provided by certificate
+ * repositories.
+ *
+ *
+ * RetrieveIfAllowed ::= BOOLEAN
+ *
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATRetrieveIfAllowed = new DerObjectIdentifier(IdIsisMttAT + ".9");
+
+ /**
+ * SingleOCSPResponse extension: The certificate requested by the client by
+ * inserting the RetrieveIfAllowed extension in the request, will be
+ * returned in this extension.
+ *
+ * @see BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.IsisMtt.Ocsp.RequestedCertificate
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATRequestedCertificate = new DerObjectIdentifier(IdIsisMttAT + ".10");
+
+ /**
+ * Base ObjectIdentifier for naming authorities
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATNamingAuthorities = new DerObjectIdentifier(IdIsisMttAT + ".11");
+
+ /**
+ * SingleOCSPResponse extension: Date, when certificate has been published
+ * in the directory and status information has become available. Currently,
+ * accrediting authorities enforce that SigG-conforming OCSP servers include
+ * this extension in the responses.
+ *
+ *
+ * CertInDirSince ::= GeneralizedTime
+ *
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATCertInDirSince = new DerObjectIdentifier(IdIsisMttAT + ".12");
+
+ /**
+ * Hash of a certificate in OCSP.
+ *
+ * @see BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.IsisMtt.Ocsp.CertHash
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATCertHash = new DerObjectIdentifier(IdIsisMttAT + ".13");
+
+ /**
+ *
+ *
+ * Used in
+ * {@link BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509.SubjectDirectoryAttributes SubjectDirectoryAttributes}
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATNameAtBirth = new DerObjectIdentifier(IdIsisMttAT + ".14");
+
+ /**
+ * Some other information of non-restrictive nature regarding the usage of
+ * this certificate. May be used as attribute in atribute certificate or as
+ * extension in a certificate.
+ *
+ *
+ *
+ * @see BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.IsisMtt.X509.AdditionalInformationSyntax
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATAdditionalInformation = new DerObjectIdentifier(IdIsisMttAT + ".15");
+
+ /**
+ * Indicates that an attribute certificate exists, which limits the
+ * usability of this public key certificate. Whenever verifying a signature
+ * with the help of this certificate, the content of the corresponding
+ * attribute certificate should be concerned. This extension MUST be
+ * included in a PKC, if a corresponding attribute certificate (having the
+ * PKC as base certificate) contains some attribute that restricts the
+ * usability of the PKC too. Attribute certificates with restricting content
+ * MUST always be included in the signed document.
+ *
+ *
+ * LiabilityLimitationFlagSyntax ::= BOOLEAN
+ *
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATLiabilityLimitationFlag = new DerObjectIdentifier("0.2.262.1.10.12.0");
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/isismtt/ISISMTTObjectIdentifiers.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/isismtt/ISISMTTObjectIdentifiers.cs.meta
new file mode 100644
index 00000000..f8acfcce
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/isismtt/ISISMTTObjectIdentifiers.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 5e3c9c5610f76c44f9193c35adb683d2
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/isismtt/ocsp.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/isismtt/ocsp.meta
new file mode 100644
index 00000000..6b8c4d03
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/isismtt/ocsp.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 253673684631a1e4e99ba19279b7cb38
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/isismtt/ocsp/CertHash.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/isismtt/ocsp/CertHash.cs
new file mode 100644
index 00000000..18a645b3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/isismtt/ocsp/CertHash.cs
@@ -0,0 +1,126 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.IsisMtt.Ocsp
+{
+ /**
+ * ISIS-MTT PROFILE: The responder may include this extension in a response to
+ * send the hash of the requested certificate to the responder. This hash is
+ * cryptographically bound to the certificate and serves as evidence that the
+ * certificate is known to the responder (i.e. it has been issued and is present
+ * in the directory). Hence, this extension is a means to provide a positive
+ * statement of availability as described in T8.[8]. As explained in T13.[1],
+ * clients may rely on this information to be able to validate signatures after
+ * the expiry of the corresponding certificate. Hence, clients MUST support this
+ * extension. If a positive statement of availability is to be delivered, this
+ * extension syntax and OID MUST be used.
+ *
+ *
+ *
+ *
+ * @return an Asn1Object
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerSequence(hashAlgorithm, new DerOctetString(certificateHash));
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/isismtt/ocsp/CertHash.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/isismtt/ocsp/CertHash.cs.meta
new file mode 100644
index 00000000..6b809fde
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/isismtt/ocsp/CertHash.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 49e52b41d04217249919b3502b7c9def
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/isismtt/ocsp/RequestedCertificate.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/isismtt/ocsp/RequestedCertificate.cs
new file mode 100644
index 00000000..a989a46d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/isismtt/ocsp/RequestedCertificate.cs
@@ -0,0 +1,192 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.IsisMtt.Ocsp
+{
+ /**
+ * ISIS-MTT-Optional: The certificate requested by the client by inserting the
+ * RetrieveIfAllowed extension in the request, will be returned in this
+ * extension.
+ *
+ * ISIS-MTT-SigG: The signature act allows publishing certificates only then,
+ * when the certificate owner gives his isExplicit permission. Accordingly, there
+ * may be �nondownloadable� certificates, about which the responder must provide
+ * status information, but MUST NOT include them in the response. Clients may
+ * get therefore the following three kind of answers on a single request
+ * including the RetrieveIfAllowed extension:
+ *
+ *
a) the responder supports the extension and is allowed to publish the
+ * certificate: RequestedCertificate returned including the requested
+ * certificate
+ *
b) the responder supports the extension but is NOT allowed to publish
+ * the certificate: RequestedCertificate returned including an empty OCTET
+ * STRING
+ *
c) the responder does not support the extension: RequestedCertificate is
+ * not included in the response
+ *
+ * Clients requesting RetrieveIfAllowed MUST be able to handle these cases. If
+ * any of the OCTET STRING options is used, it MUST contain the DER encoding of
+ * the requested certificate.
+ *
+ *
+ *
+ *
+ * ISIS-MTT PROFILE: The relatively complex structure of AdmissionSyntax
+ * supports the following concepts and requirements:
+ *
+ *
External institutions (e.g. professional associations, chambers, unions,
+ * administrative bodies, companies, etc.), which are responsible for granting
+ * and verifying professional admissions, are indicated by means of the data
+ * field admissionAuthority. An admission authority is indicated by a
+ * GeneralName object. Here an X.501 directory name (distinguished name) can be
+ * indicated in the field directoryName, a URL address can be indicated in the
+ * field uniformResourceIdentifier, and an object identifier can be indicated in
+ * the field registeredId.
+ *
The names of authorities which are responsible for the administration of
+ * title registers are indicated in the data field namingAuthority. The name of
+ * the authority can be identified by an object identifier in the field
+ * namingAuthorityId, by means of a text string in the field
+ * namingAuthorityText, by means of a URL address in the field
+ * namingAuthorityUrl, or by a combination of them. For example, the text string
+ * can contain the name of the authority, the country and the name of the title
+ * register. The URL-option refers to a web page which contains lists with
+ * officially registered professions (text and possibly OID) as well as
+ * further information on these professions. Object identifiers for the
+ * component namingAuthorityId are grouped under the OID-branch
+ * id-isis-at-namingAuthorities and must be applied for.
+ *
See http://www.teletrust.de/anwend.asp?Id=30200&Sprache=E_&HomePG=0
+ * for an application form and http://www.teletrust.de/links.asp?id=30220,11
+ * for an overview of registered naming authorities.
+ *
By means of the data type ProfessionInfo certain professions,
+ * specializations, disciplines, fields of activity, etc. are identified. A
+ * profession is represented by one or more text strings, resp. profession OIDs
+ * in the fields professionItems and professionOIDs and by a registration number
+ * in the field registrationNumber. An indication in text form must always be
+ * present, whereas the other indications are optional. The component
+ * addProfessionInfo may contain additional applicationspecific information in
+ * DER-encoded form.
+ *
+ *
+ * By means of different namingAuthority-OIDs or profession OIDs hierarchies of
+ * professions, specializations, disciplines, fields of activity, etc. can be
+ * expressed. The issuing admission authority should always be indicated (field
+ * admissionAuthority), whenever a registration number is presented. Still,
+ * information on admissions can be given without indicating an admission or a
+ * naming authority by the exclusive use of the component professionItems. In
+ * this case the certification authority is responsible for the verification of
+ * the admission information.
+ *
+ *
+ *
+ * This attribute is single-valued. Still, several admissions can be captured in
+ * the sequence structure of the component contentsOfAdmissions of
+ * AdmissionSyntax or in the component professionInfos of Admissions. The
+ * component admissionAuthority of AdmissionSyntax serves as default value for
+ * the component admissionAuthority of Admissions. Within the latter component
+ * the default value can be overwritten, in case that another authority is
+ * responsible. The component namingAuthority of Admissions serves as a default
+ * value for the component namingAuthority of ProfessionInfo. Within the latter
+ * component the default value can be overwritten, in case that another naming
+ * authority needs to be recorded.
+ *
+ * The length of the string objects is limited to 128 characters. It is
+ * recommended to indicate a namingAuthorityURL in all issued attribute
+ * certificates. If a namingAuthorityURL is indicated, the field professionItems
+ * of ProfessionInfo should contain only registered titles. If the field
+ * professionOIDs exists, it has to contain the OIDs of the professions listed
+ * in professionItems in the same order. In general, the field professionInfos
+ * should contain only one entry, unless the admissions that are to be listed
+ * are logically connected (e.g. they have been issued under the same admission
+ * number).
+ *
+ * @see BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.IsisMtt.X509.Admissions
+ * @see BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.IsisMtt.X509.ProfessionInfo
+ * @see BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.IsisMtt.X509.NamingAuthority
+ */
+ public class AdmissionSyntax
+ : Asn1Encodable
+ {
+ private readonly GeneralName admissionAuthority;
+ private readonly Asn1Sequence contentsOfAdmissions;
+
+ public static AdmissionSyntax GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is AdmissionSyntax)
+ {
+ return (AdmissionSyntax)obj;
+ }
+
+ if (obj is Asn1Sequence)
+ {
+ return new AdmissionSyntax((Asn1Sequence)obj);
+ }
+
+ throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+ }
+
+ /**
+ * Constructor from Asn1Sequence.
+ *
+ * The sequence is of type ProcurationSyntax:
+ *
+ *
+ *
+ * @return an Asn1Object
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector vec = new Asn1EncodableVector();
+ if (namingAuthorityID != null)
+ {
+ vec.Add(namingAuthorityID);
+ }
+ if (namingAuthorityUrl != null)
+ {
+ vec.Add(new DerIA5String(namingAuthorityUrl, true));
+ }
+ if (namingAuthorityText != null)
+ {
+ vec.Add(namingAuthorityText);
+ }
+ return new DerSequence(vec);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/isismtt/x509/NamingAuthority.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/isismtt/x509/NamingAuthority.cs.meta
new file mode 100644
index 00000000..2ab74baf
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/isismtt/x509/NamingAuthority.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 59bd2c22203ef6d459836bb7661ba720
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/isismtt/x509/ProcurationSyntax.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/isismtt/x509/ProcurationSyntax.cs
new file mode 100644
index 00000000..f03d959d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/isismtt/x509/ProcurationSyntax.cs
@@ -0,0 +1,237 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X500;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.IsisMtt.X509
+{
+ /**
+ * Attribute to indicate that the certificate holder may sign in the name of a
+ * third person.
+ *
+ * ISIS-MTT PROFILE: The corresponding ProcurationSyntax contains either the
+ * name of the person who is represented (subcomponent thirdPerson) or a
+ * reference to his/her base certificate (in the component signingFor,
+ * subcomponent certRef), furthermore the optional components country and
+ * typeSubstitution to indicate the country whose laws apply, and respectively
+ * the type of procuration (e.g. manager, procuration, custody).
+ *
+ *
+ * ISIS-MTT PROFILE: The GeneralName MUST be of type directoryName and MAY only
+ * contain: - RFC3039 attributes, except pseudonym (countryName, commonName,
+ * surname, givenName, serialNumber, organizationName, organizationalUnitName,
+ * stateOrProvincename, localityName, postalAddress) and - SubjectDirectoryName
+ * attributes (title, dateOfBirth, placeOfBirth, gender, countryOfCitizenship,
+ * countryOfResidence and NameAtBirth).
+ *
+ * MacData ::= SEQUENCE {
+ * mac DigestInfo,
+ * macSalt OCTET STRING,
+ * iterations INTEGER DEFAULT 1
+ * -- Note: The default is for historic reasons and its use is deprecated. A
+ * -- higher value, like 1024 is recommended.
+ *
+ * @return the basic DERObject construction.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector(digInfo, new DerOctetString(salt));
+
+ if (!iterationCount.Equals(BigInteger.One))
+ {
+ v.Add(new DerInteger(iterationCount));
+ }
+
+ return new DerSequence(v);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/MacData.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/MacData.cs.meta
new file mode 100644
index 00000000..8de127a6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/MacData.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 9cc5c731aedc89645813d9fe248b448d
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/PBEParameter.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/PBEParameter.cs
new file mode 100644
index 00000000..1814c798
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/PBEParameter.cs
@@ -0,0 +1,64 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs
+{
+ public class PbeParameter
+ : Asn1Encodable
+ {
+ private readonly Asn1OctetString salt;
+ private readonly DerInteger iterationCount;
+
+ public static PbeParameter GetInstance(object obj)
+ {
+ if (obj is PbeParameter || obj == null)
+ {
+ return (PbeParameter) obj;
+ }
+
+ if (obj is Asn1Sequence)
+ {
+ return new PbeParameter((Asn1Sequence) obj);
+ }
+
+ throw new ArgumentException("Unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+ }
+
+ private PbeParameter(Asn1Sequence seq)
+ {
+ if (seq.Count != 2)
+ throw new ArgumentException("Wrong number of elements in sequence", "seq");
+
+ salt = Asn1OctetString.GetInstance(seq[0]);
+ iterationCount = DerInteger.GetInstance(seq[1]);
+ }
+
+ public PbeParameter(byte[] salt, int iterationCount)
+ {
+ this.salt = new DerOctetString(salt);
+ this.iterationCount = new DerInteger(iterationCount);
+ }
+
+ public byte[] GetSalt()
+ {
+ return salt.GetOctets();
+ }
+
+ public BigInteger IterationCount
+ {
+ get { return iterationCount.Value; }
+ }
+
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerSequence(salt, iterationCount);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/PBEParameter.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/PBEParameter.cs.meta
new file mode 100644
index 00000000..47d8d868
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/PBEParameter.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a2905fb1449d42a488e211b8d8d0ab97
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/PBES2Parameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/PBES2Parameters.cs
new file mode 100644
index 00000000..23367382
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/PBES2Parameters.cs
@@ -0,0 +1,69 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs
+{
+ public class PbeS2Parameters
+ : Asn1Encodable
+ {
+ private readonly KeyDerivationFunc func;
+ private readonly EncryptionScheme scheme;
+
+ public static PbeS2Parameters GetInstance(object obj)
+ {
+ if (obj == null)
+ return null;
+ PbeS2Parameters existing = obj as PbeS2Parameters;
+ if (existing != null)
+ return existing;
+ return new PbeS2Parameters(Asn1Sequence.GetInstance(obj));
+ }
+
+ public PbeS2Parameters(KeyDerivationFunc keyDevFunc, EncryptionScheme encScheme)
+ {
+ this.func = keyDevFunc;
+ this.scheme = encScheme;
+ }
+
+ [Obsolete("Use GetInstance() instead")]
+ public PbeS2Parameters(
+ Asn1Sequence seq)
+ {
+ if (seq.Count != 2)
+ throw new ArgumentException("Wrong number of elements in sequence", "seq");
+
+ Asn1Sequence funcSeq = (Asn1Sequence)seq[0].ToAsn1Object();
+
+ // TODO Not sure if this special case is really necessary/appropriate
+ if (funcSeq[0].Equals(PkcsObjectIdentifiers.IdPbkdf2))
+ {
+ func = new KeyDerivationFunc(PkcsObjectIdentifiers.IdPbkdf2,
+ Pbkdf2Params.GetInstance(funcSeq[1]));
+ }
+ else
+ {
+ func = new KeyDerivationFunc(funcSeq);
+ }
+
+ scheme = EncryptionScheme.GetInstance(seq[1].ToAsn1Object());
+ }
+
+ public KeyDerivationFunc KeyDerivationFunc
+ {
+ get { return func; }
+ }
+
+ public EncryptionScheme EncryptionScheme
+ {
+ get { return scheme; }
+ }
+
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerSequence(func, scheme);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/PBES2Parameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/PBES2Parameters.cs.meta
new file mode 100644
index 00000000..24947f22
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/PBES2Parameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: bb3fc7932c18ad24bb197cf87989240d
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/PBKDF2Params.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/PBKDF2Params.cs
new file mode 100644
index 00000000..4f27a1a5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/PBKDF2Params.cs
@@ -0,0 +1,148 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs
+{
+ public class Pbkdf2Params
+ : Asn1Encodable
+ {
+ private static AlgorithmIdentifier algid_hmacWithSHA1 = new AlgorithmIdentifier(PkcsObjectIdentifiers.IdHmacWithSha1, DerNull.Instance);
+
+ private readonly Asn1OctetString octStr;
+ private readonly DerInteger iterationCount, keyLength;
+ private readonly AlgorithmIdentifier prf;
+
+ public static Pbkdf2Params GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is Pbkdf2Params)
+ return (Pbkdf2Params)obj;
+
+ if (obj is Asn1Sequence)
+ return new Pbkdf2Params((Asn1Sequence)obj);
+
+ throw new ArgumentException("Unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+ }
+
+ public Pbkdf2Params(
+ Asn1Sequence seq)
+ {
+ if (seq.Count < 2 || seq.Count > 4)
+ throw new ArgumentException("Wrong number of elements in sequence", "seq");
+
+ this.octStr = (Asn1OctetString)seq[0];
+ this.iterationCount = (DerInteger)seq[1];
+
+ Asn1Encodable kl = null, d = null;
+ if (seq.Count > 3)
+ {
+ kl = seq[2];
+ d = seq[3];
+ }
+ else if (seq.Count > 2)
+ {
+ if (seq[2] is DerInteger)
+ {
+ kl = seq[2];
+ }
+ else
+ {
+ d = seq[2];
+ }
+ }
+ if (kl != null)
+ {
+ keyLength = (DerInteger)kl;
+ }
+ if (d != null)
+ {
+ prf = AlgorithmIdentifier.GetInstance(d);
+ }
+ }
+
+ public Pbkdf2Params(
+ byte[] salt,
+ int iterationCount)
+ {
+ this.octStr = new DerOctetString(salt);
+ this.iterationCount = new DerInteger(iterationCount);
+ }
+
+ public Pbkdf2Params(
+ byte[] salt,
+ int iterationCount,
+ int keyLength)
+ : this(salt, iterationCount)
+ {
+ this.keyLength = new DerInteger(keyLength);
+ }
+
+ public Pbkdf2Params(
+ byte[] salt,
+ int iterationCount,
+ int keyLength,
+ AlgorithmIdentifier prf)
+ : this(salt, iterationCount, keyLength)
+ {
+ this.prf = prf;
+ }
+
+ public Pbkdf2Params(
+ byte[] salt,
+ int iterationCount,
+ AlgorithmIdentifier prf)
+ : this(salt, iterationCount)
+ {
+ this.prf = prf;
+ }
+
+ public byte[] GetSalt()
+ {
+ return octStr.GetOctets();
+ }
+
+ public BigInteger IterationCount
+ {
+ get { return iterationCount.Value; }
+ }
+
+ public BigInteger KeyLength
+ {
+ get { return keyLength == null ? null : keyLength.Value; }
+ }
+
+ public bool IsDefaultPrf
+ {
+ get { return prf == null || prf.Equals(algid_hmacWithSHA1); }
+ }
+
+ public AlgorithmIdentifier Prf
+ {
+ get { return prf != null ? prf : algid_hmacWithSHA1; }
+ }
+
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector(
+ octStr, iterationCount);
+
+ if (keyLength != null)
+ {
+ v.Add(keyLength);
+ }
+ if (!IsDefaultPrf)
+ {
+ v.Add(prf);
+ }
+
+ return new DerSequence(v);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/PBKDF2Params.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/PBKDF2Params.cs.meta
new file mode 100644
index 00000000..1d5d3048
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/PBKDF2Params.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 5ec42b2b8cbb37f4b99b10df913c771d
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/PKCS12PBEParams.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/PKCS12PBEParams.cs
new file mode 100644
index 00000000..6a0201a4
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/PKCS12PBEParams.cs
@@ -0,0 +1,67 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs
+{
+ public class Pkcs12PbeParams
+ : Asn1Encodable
+ {
+ private readonly DerInteger iterations;
+ private readonly Asn1OctetString iv;
+
+ public Pkcs12PbeParams(
+ byte[] salt,
+ int iterations)
+ {
+ this.iv = new DerOctetString(salt);
+ this.iterations = new DerInteger(iterations);
+ }
+
+ private Pkcs12PbeParams(
+ Asn1Sequence seq)
+ {
+ if (seq.Count != 2)
+ throw new ArgumentException("Wrong number of elements in sequence", "seq");
+
+ iv = Asn1OctetString.GetInstance(seq[0]);
+ iterations = DerInteger.GetInstance(seq[1]);
+ }
+
+ public static Pkcs12PbeParams GetInstance(
+ object obj)
+ {
+ if (obj is Pkcs12PbeParams)
+ {
+ return (Pkcs12PbeParams) obj;
+ }
+
+ if (obj is Asn1Sequence)
+ {
+ return new Pkcs12PbeParams((Asn1Sequence) obj);
+ }
+
+ throw new ArgumentException("Unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+ }
+
+ public BigInteger Iterations
+ {
+ get { return iterations.Value; }
+ }
+
+ public byte[] GetIV()
+ {
+ return iv.GetOctets();
+ }
+
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerSequence(iv, iterations);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/PKCS12PBEParams.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/PKCS12PBEParams.cs.meta
new file mode 100644
index 00000000..3d6a5fee
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/PKCS12PBEParams.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: dd66e6bf80ac29d439006d4145a1f961
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/PKCSObjectIdentifiers.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/PKCSObjectIdentifiers.cs
new file mode 100644
index 00000000..15e8278e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/pkcs/PKCSObjectIdentifiers.cs
@@ -0,0 +1,297 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs
+{
+ public abstract class PkcsObjectIdentifiers
+ {
+ //
+ // pkcs-1 OBJECT IDENTIFIER ::= {
+ // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
+ //
+ public const string Pkcs1 = "1.2.840.113549.1.1";
+ internal static readonly DerObjectIdentifier Pkcs1Oid = new DerObjectIdentifier(Pkcs1);
+
+ public static readonly DerObjectIdentifier RsaEncryption = Pkcs1Oid.Branch("1");
+ public static readonly DerObjectIdentifier MD2WithRsaEncryption = Pkcs1Oid.Branch("2");
+ public static readonly DerObjectIdentifier MD4WithRsaEncryption = Pkcs1Oid.Branch("3");
+ public static readonly DerObjectIdentifier MD5WithRsaEncryption = Pkcs1Oid.Branch("4");
+ public static readonly DerObjectIdentifier Sha1WithRsaEncryption = Pkcs1Oid.Branch("5");
+ public static readonly DerObjectIdentifier SrsaOaepEncryptionSet = Pkcs1Oid.Branch("6");
+ public static readonly DerObjectIdentifier IdRsaesOaep = Pkcs1Oid.Branch("7");
+ public static readonly DerObjectIdentifier IdMgf1 = Pkcs1Oid.Branch("8");
+ public static readonly DerObjectIdentifier IdPSpecified = Pkcs1Oid.Branch("9");
+ public static readonly DerObjectIdentifier IdRsassaPss = Pkcs1Oid.Branch("10");
+ public static readonly DerObjectIdentifier Sha256WithRsaEncryption = Pkcs1Oid.Branch("11");
+ public static readonly DerObjectIdentifier Sha384WithRsaEncryption = Pkcs1Oid.Branch("12");
+ public static readonly DerObjectIdentifier Sha512WithRsaEncryption = Pkcs1Oid.Branch("13");
+ public static readonly DerObjectIdentifier Sha224WithRsaEncryption = Pkcs1Oid.Branch("14");
+ /** PKCS#1: 1.2.840.113549.1.1.15 */
+ public static readonly DerObjectIdentifier Sha512_224WithRSAEncryption = Pkcs1Oid.Branch("15");
+ /** PKCS#1: 1.2.840.113549.1.1.16 */
+ public static readonly DerObjectIdentifier Sha512_256WithRSAEncryption = Pkcs1Oid.Branch("16");
+
+ //
+ // pkcs-3 OBJECT IDENTIFIER ::= {
+ // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 3 }
+ //
+ public const string Pkcs3 = "1.2.840.113549.1.3";
+
+ public static readonly DerObjectIdentifier DhKeyAgreement = new DerObjectIdentifier(Pkcs3 + ".1");
+
+ //
+ // pkcs-5 OBJECT IDENTIFIER ::= {
+ // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 5 }
+ //
+ public const string Pkcs5 = "1.2.840.113549.1.5";
+
+ public static readonly DerObjectIdentifier PbeWithMD2AndDesCbc = new DerObjectIdentifier(Pkcs5 + ".1");
+ public static readonly DerObjectIdentifier PbeWithMD2AndRC2Cbc = new DerObjectIdentifier(Pkcs5 + ".4");
+ public static readonly DerObjectIdentifier PbeWithMD5AndDesCbc = new DerObjectIdentifier(Pkcs5 + ".3");
+ public static readonly DerObjectIdentifier PbeWithMD5AndRC2Cbc = new DerObjectIdentifier(Pkcs5 + ".6");
+ public static readonly DerObjectIdentifier PbeWithSha1AndDesCbc = new DerObjectIdentifier(Pkcs5 + ".10");
+ public static readonly DerObjectIdentifier PbeWithSha1AndRC2Cbc = new DerObjectIdentifier(Pkcs5 + ".11");
+
+ public static readonly DerObjectIdentifier IdPbeS2 = new DerObjectIdentifier(Pkcs5 + ".13");
+ public static readonly DerObjectIdentifier IdPbkdf2 = new DerObjectIdentifier(Pkcs5 + ".12");
+
+ //
+ // encryptionAlgorithm OBJECT IDENTIFIER ::= {
+ // iso(1) member-body(2) us(840) rsadsi(113549) 3 }
+ //
+ public const string EncryptionAlgorithm = "1.2.840.113549.3";
+
+ public static readonly DerObjectIdentifier DesEde3Cbc = new DerObjectIdentifier(EncryptionAlgorithm + ".7");
+ public static readonly DerObjectIdentifier RC2Cbc = new DerObjectIdentifier(EncryptionAlgorithm + ".2");
+
+ //
+ // object identifiers for digests
+ //
+ public const string DigestAlgorithm = "1.2.840.113549.2";
+
+ //
+ // md2 OBJECT IDENTIFIER ::=
+ // {iso(1) member-body(2) US(840) rsadsi(113549) DigestAlgorithm(2) 2}
+ //
+ public static readonly DerObjectIdentifier MD2 = new DerObjectIdentifier(DigestAlgorithm + ".2");
+
+ //
+ // md4 OBJECT IDENTIFIER ::=
+ // {iso(1) member-body(2) US(840) rsadsi(113549) DigestAlgorithm(2) 4}
+ //
+ public static readonly DerObjectIdentifier MD4 = new DerObjectIdentifier(DigestAlgorithm + ".4");
+
+ //
+ // md5 OBJECT IDENTIFIER ::=
+ // {iso(1) member-body(2) US(840) rsadsi(113549) DigestAlgorithm(2) 5}
+ //
+ public static readonly DerObjectIdentifier MD5 = new DerObjectIdentifier(DigestAlgorithm + ".5");
+
+ public static readonly DerObjectIdentifier IdHmacWithSha1 = new DerObjectIdentifier(DigestAlgorithm + ".7");
+ public static readonly DerObjectIdentifier IdHmacWithSha224 = new DerObjectIdentifier(DigestAlgorithm + ".8");
+ public static readonly DerObjectIdentifier IdHmacWithSha256 = new DerObjectIdentifier(DigestAlgorithm + ".9");
+ public static readonly DerObjectIdentifier IdHmacWithSha384 = new DerObjectIdentifier(DigestAlgorithm + ".10");
+ public static readonly DerObjectIdentifier IdHmacWithSha512 = new DerObjectIdentifier(DigestAlgorithm + ".11");
+
+ //
+ // pkcs-7 OBJECT IDENTIFIER ::= {
+ // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 7 }
+ //
+ public const string Pkcs7 = "1.2.840.113549.1.7";
+
+ public static readonly DerObjectIdentifier Data = new DerObjectIdentifier(Pkcs7 + ".1");
+ public static readonly DerObjectIdentifier SignedData = new DerObjectIdentifier(Pkcs7 + ".2");
+ public static readonly DerObjectIdentifier EnvelopedData = new DerObjectIdentifier(Pkcs7 + ".3");
+ public static readonly DerObjectIdentifier SignedAndEnvelopedData = new DerObjectIdentifier(Pkcs7 + ".4");
+ public static readonly DerObjectIdentifier DigestedData = new DerObjectIdentifier(Pkcs7 + ".5");
+ public static readonly DerObjectIdentifier EncryptedData = new DerObjectIdentifier(Pkcs7 + ".6");
+
+ //
+ // pkcs-9 OBJECT IDENTIFIER ::= {
+ // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 9 }
+ //
+ public const string Pkcs9 = "1.2.840.113549.1.9";
+
+ public static readonly DerObjectIdentifier Pkcs9AtEmailAddress = new DerObjectIdentifier(Pkcs9 + ".1");
+ public static readonly DerObjectIdentifier Pkcs9AtUnstructuredName = new DerObjectIdentifier(Pkcs9 + ".2");
+ public static readonly DerObjectIdentifier Pkcs9AtContentType = new DerObjectIdentifier(Pkcs9 + ".3");
+ public static readonly DerObjectIdentifier Pkcs9AtMessageDigest = new DerObjectIdentifier(Pkcs9 + ".4");
+ public static readonly DerObjectIdentifier Pkcs9AtSigningTime = new DerObjectIdentifier(Pkcs9 + ".5");
+ public static readonly DerObjectIdentifier Pkcs9AtCounterSignature = new DerObjectIdentifier(Pkcs9 + ".6");
+ public static readonly DerObjectIdentifier Pkcs9AtChallengePassword = new DerObjectIdentifier(Pkcs9 + ".7");
+ public static readonly DerObjectIdentifier Pkcs9AtUnstructuredAddress = new DerObjectIdentifier(Pkcs9 + ".8");
+ public static readonly DerObjectIdentifier Pkcs9AtExtendedCertificateAttributes = new DerObjectIdentifier(Pkcs9 + ".9");
+ public static readonly DerObjectIdentifier Pkcs9AtSigningDescription = new DerObjectIdentifier(Pkcs9 + ".13");
+ public static readonly DerObjectIdentifier Pkcs9AtExtensionRequest = new DerObjectIdentifier(Pkcs9 + ".14");
+ public static readonly DerObjectIdentifier Pkcs9AtSmimeCapabilities = new DerObjectIdentifier(Pkcs9 + ".15");
+ public static readonly DerObjectIdentifier IdSmime = new DerObjectIdentifier(Pkcs9 + ".16");
+
+ public static readonly DerObjectIdentifier Pkcs9AtFriendlyName = new DerObjectIdentifier(Pkcs9 + ".20");
+ public static readonly DerObjectIdentifier Pkcs9AtLocalKeyID = new DerObjectIdentifier(Pkcs9 + ".21");
+
+ [Obsolete("Use X509Certificate instead")]
+ public static readonly DerObjectIdentifier X509CertType = new DerObjectIdentifier(Pkcs9 + ".22.1");
+
+ public const string CertTypes = Pkcs9 + ".22";
+ public static readonly DerObjectIdentifier X509Certificate = new DerObjectIdentifier(CertTypes + ".1");
+ public static readonly DerObjectIdentifier SdsiCertificate = new DerObjectIdentifier(CertTypes + ".2");
+
+ public const string CrlTypes = Pkcs9 + ".23";
+ public static readonly DerObjectIdentifier X509Crl = new DerObjectIdentifier(CrlTypes + ".1");
+
+ public static readonly DerObjectIdentifier IdAlg = IdSmime.Branch("3");
+
+ public static readonly DerObjectIdentifier IdAlgEsdh = IdAlg.Branch("5");
+ public static readonly DerObjectIdentifier IdAlgCms3DesWrap = IdAlg.Branch("6");
+ public static readonly DerObjectIdentifier IdAlgCmsRC2Wrap = IdAlg.Branch("7");
+ public static readonly DerObjectIdentifier IdAlgPwriKek = IdAlg.Branch("9");
+ public static readonly DerObjectIdentifier IdAlgSsdh = IdAlg.Branch("10");
+
+ /*
+ *
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerSequence(hashAlgorithm, new DerOctetString(hashedMessage));
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/tsp/MessageImprint.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/tsp/MessageImprint.cs.meta
new file mode 100644
index 00000000..fa90faf6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/tsp/MessageImprint.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 835f6babba6da8b469b31289b68395ca
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/tsp/TSTInfo.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/tsp/TSTInfo.cs
new file mode 100644
index 00000000..65de2c4b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/tsp/TSTInfo.cs
@@ -0,0 +1,254 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Tsp
+{
+ public class TstInfo
+ : Asn1Encodable
+ {
+ private readonly DerInteger version;
+ private readonly DerObjectIdentifier tsaPolicyId;
+ private readonly MessageImprint messageImprint;
+ private readonly DerInteger serialNumber;
+ private readonly DerGeneralizedTime genTime;
+ private readonly Accuracy accuracy;
+ private readonly DerBoolean ordering;
+ private readonly DerInteger nonce;
+ private readonly GeneralName tsa;
+ private readonly X509Extensions extensions;
+
+ public static TstInfo GetInstance(
+ object o)
+ {
+ if (o == null || o is TstInfo)
+ {
+ return (TstInfo) o;
+ }
+
+ if (o is Asn1Sequence)
+ {
+ return new TstInfo((Asn1Sequence) o);
+ }
+
+ if (o is Asn1OctetString)
+ {
+ try
+ {
+ byte[] octets = ((Asn1OctetString)o).GetOctets();
+ return GetInstance(Asn1Object.FromByteArray(octets));
+ }
+ catch (IOException)
+ {
+ throw new ArgumentException(
+ "Bad object format in 'TstInfo' factory.");
+ }
+ }
+
+ throw new ArgumentException(
+ "Unknown object in 'TstInfo' factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(o));
+ }
+
+ private TstInfo(
+ Asn1Sequence seq)
+ {
+ IEnumerator e = seq.GetEnumerator();
+
+ // version
+ e.MoveNext();
+ version = DerInteger.GetInstance(e.Current);
+
+ // tsaPolicy
+ e.MoveNext();
+ tsaPolicyId = DerObjectIdentifier.GetInstance(e.Current);
+
+ // messageImprint
+ e.MoveNext();
+ messageImprint = MessageImprint.GetInstance(e.Current);
+
+ // serialNumber
+ e.MoveNext();
+ serialNumber = DerInteger.GetInstance(e.Current);
+
+ // genTime
+ e.MoveNext();
+ genTime = DerGeneralizedTime.GetInstance(e.Current);
+
+ // default for ordering
+ ordering = DerBoolean.False;
+
+ while (e.MoveNext())
+ {
+ Asn1Object o = (Asn1Object) e.Current;
+
+ if (o is Asn1TaggedObject)
+ {
+ DerTaggedObject tagged = (DerTaggedObject) o;
+
+ switch (tagged.TagNo)
+ {
+ case 0:
+ tsa = GeneralName.GetInstance(tagged, true);
+ break;
+ case 1:
+ extensions = X509Extensions.GetInstance(tagged, false);
+ break;
+ default:
+ throw new ArgumentException("Unknown tag value " + tagged.TagNo);
+ }
+ }
+
+ if (o is DerSequence)
+ {
+ accuracy = Accuracy.GetInstance(o);
+ }
+
+ if (o is DerBoolean)
+ {
+ ordering = DerBoolean.GetInstance(o);
+ }
+
+ if (o is DerInteger)
+ {
+ nonce = DerInteger.GetInstance(o);
+ }
+ }
+ }
+
+ public TstInfo(
+ DerObjectIdentifier tsaPolicyId,
+ MessageImprint messageImprint,
+ DerInteger serialNumber,
+ DerGeneralizedTime genTime,
+ Accuracy accuracy,
+ DerBoolean ordering,
+ DerInteger nonce,
+ GeneralName tsa,
+ X509Extensions extensions)
+ {
+ this.version = new DerInteger(1);
+ this.tsaPolicyId = tsaPolicyId;
+ this.messageImprint = messageImprint;
+ this.serialNumber = serialNumber;
+ this.genTime = genTime;
+ this.accuracy = accuracy;
+ this.ordering = ordering;
+ this.nonce = nonce;
+ this.tsa = tsa;
+ this.extensions = extensions;
+ }
+
+ public DerInteger Version
+ {
+ get { return version; }
+ }
+
+ public MessageImprint MessageImprint
+ {
+ get { return messageImprint; }
+ }
+
+ public DerObjectIdentifier Policy
+ {
+ get { return tsaPolicyId; }
+ }
+
+ public DerInteger SerialNumber
+ {
+ get { return serialNumber; }
+ }
+
+ public Accuracy Accuracy
+ {
+ get { return accuracy; }
+ }
+
+ public DerGeneralizedTime GenTime
+ {
+ get { return genTime; }
+ }
+
+ public DerBoolean Ordering
+ {
+ get { return ordering; }
+ }
+
+ public DerInteger Nonce
+ {
+ get { return nonce; }
+ }
+
+ public GeneralName Tsa
+ {
+ get { return tsa; }
+ }
+
+ public X509Extensions Extensions
+ {
+ get { return extensions; }
+ }
+
+ /**
+ *
+ *
+ * TstInfo ::= SEQUENCE {
+ * version INTEGER { v1(1) },
+ * policy TSAPolicyId,
+ * messageImprint MessageImprint,
+ * -- MUST have the same value as the similar field in
+ * -- TimeStampReq
+ * serialNumber INTEGER,
+ * -- Time-Stamping users MUST be ready to accommodate integers
+ * -- up to 160 bits.
+ * genTime GeneralizedTime,
+ * accuracy Accuracy OPTIONAL,
+ * ordering BOOLEAN DEFAULT FALSE,
+ * nonce INTEGER OPTIONAL,
+ * -- MUST be present if the similar field was present
+ * -- in TimeStampReq. In that case it MUST have the same value.
+ * tsa [0] GeneralName OPTIONAL,
+ * extensions [1] IMPLICIT Extensions OPTIONAL }
+ *
+ *
The forward elements of the crossCertificatePair attribute of a
+ * CA's directory entry shall be used to store all, except self-issued
+ * certificates issued to this CA. Optionally, the reverse elements of the
+ * crossCertificatePair attribute, of a CA's directory entry may contain a
+ * subset of certificates issued by this CA to other CAs. When both the forward
+ * and the reverse elements are present in a single attribute value, issuer name
+ * in one certificate shall match the subject name in the other and vice versa,
+ * and the subject public key in one certificate shall be capable of verifying
+ * the digital signature on the other certificate and vice versa.
+ *
+ * When a reverse element is present, the forward element value and the reverse
+ * element value need not be stored in the same attribute value; in other words,
+ * they can be stored in either a single attribute value or two attribute
+ * values.
+ *
+ *
+ * CertificatePair ::= SEQUENCE {
+ * forward [0] Certificate OPTIONAL,
+ * reverse [1] Certificate OPTIONAL,
+ * -- at least one of the pair shall be present -- }
+ *
+ */
+ public class CertificatePair
+ : Asn1Encodable
+ {
+ private X509CertificateStructure forward, reverse;
+
+ public static CertificatePair GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is CertificatePair)
+ {
+ return (CertificatePair) obj;
+ }
+
+ if (obj is Asn1Sequence)
+ {
+ return new CertificatePair((Asn1Sequence) obj);
+ }
+
+ throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+ }
+
+ /**
+ * Constructor from Asn1Sequence.
+ *
+ * The sequence is of type CertificatePair:
+ *
+ *
+ * CertificatePair ::= SEQUENCE {
+ * forward [0] Certificate OPTIONAL,
+ * reverse [1] Certificate OPTIONAL,
+ * -- at least one of the pair shall be present -- }
+ *
+ *
+ * @param seq The ASN.1 sequence.
+ */
+ private CertificatePair(
+ Asn1Sequence seq)
+ {
+ if (seq.Count != 1 && seq.Count != 2)
+ {
+ throw new ArgumentException("Bad sequence size: " + seq.Count, "seq");
+ }
+
+ foreach (object obj in seq)
+ {
+ Asn1TaggedObject o = Asn1TaggedObject.GetInstance(obj);
+ if (o.TagNo == 0)
+ {
+ forward = X509CertificateStructure.GetInstance(o, true);
+ }
+ else if (o.TagNo == 1)
+ {
+ reverse = X509CertificateStructure.GetInstance(o, true);
+ }
+ else
+ {
+ throw new ArgumentException("Bad tag number: " + o.TagNo);
+ }
+ }
+ }
+
+ /**
+ * Constructor from a given details.
+ *
+ * @param forward Certificates issued to this CA.
+ * @param reverse Certificates issued by this CA to other CAs.
+ */
+ public CertificatePair(
+ X509CertificateStructure forward,
+ X509CertificateStructure reverse)
+ {
+ this.forward = forward;
+ this.reverse = reverse;
+ }
+
+ /**
+ * Produce an object suitable for an Asn1OutputStream.
+ *
+ * Returns:
+ *
+ *
+ * CertificatePair ::= SEQUENCE {
+ * forward [0] Certificate OPTIONAL,
+ * reverse [1] Certificate OPTIONAL,
+ * -- at least one of the pair shall be present -- }
+ *
+ *
+ * @return a DERObject
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector vec = new Asn1EncodableVector();
+
+ if (forward != null)
+ {
+ vec.Add(new DerTaggedObject(0, forward));
+ }
+
+ if (reverse != null)
+ {
+ vec.Add(new DerTaggedObject(1, reverse));
+ }
+
+ return new DerSequence(vec);
+ }
+
+ /**
+ * @return Returns the forward.
+ */
+ public X509CertificateStructure Forward
+ {
+ get { return forward; }
+ }
+
+ /**
+ * @return Returns the reverse.
+ */
+ public X509CertificateStructure Reverse
+ {
+ get { return reverse; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/CertificatePair.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/CertificatePair.cs.meta
new file mode 100644
index 00000000..a7499e2a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/CertificatePair.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 4bac5cc073bdfcf45b1f1fb0763c43c8
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/CertificatePolicies.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/CertificatePolicies.cs
new file mode 100644
index 00000000..03861a01
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/CertificatePolicies.cs
@@ -0,0 +1,85 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Text;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509
+{
+ public class CertificatePolicies
+ : Asn1Encodable
+ {
+ private readonly PolicyInformation[] policyInformation;
+
+ public static CertificatePolicies GetInstance(object obj)
+ {
+ if (obj == null || obj is CertificatePolicies)
+ return (CertificatePolicies)obj;
+
+ return new CertificatePolicies(Asn1Sequence.GetInstance(obj));
+ }
+
+ public static CertificatePolicies GetInstance(Asn1TaggedObject obj, bool isExplicit)
+ {
+ return GetInstance(Asn1Sequence.GetInstance(obj, isExplicit));
+ }
+
+ /**
+ * Construct a CertificatePolicies object containing one PolicyInformation.
+ *
+ * @param name the name to be contained.
+ */
+ public CertificatePolicies(PolicyInformation name)
+ {
+ this.policyInformation = new PolicyInformation[] { name };
+ }
+
+ public CertificatePolicies(PolicyInformation[] policyInformation)
+ {
+ this.policyInformation = policyInformation;
+ }
+
+ private CertificatePolicies(Asn1Sequence seq)
+ {
+ this.policyInformation = new PolicyInformation[seq.Count];
+
+ for (int i = 0; i < seq.Count; ++i)
+ {
+ policyInformation[i] = PolicyInformation.GetInstance(seq[i]);
+ }
+ }
+
+ public virtual PolicyInformation[] GetPolicyInformation()
+ {
+ return (PolicyInformation[])policyInformation.Clone();
+ }
+
+ /**
+ * Produce an object suitable for an ASN1OutputStream.
+ *
+ */
+ public class GeneralName
+ : Asn1Encodable, IAsn1Choice
+ {
+ public const int OtherName = 0;
+ public const int Rfc822Name = 1;
+ public const int DnsName = 2;
+ public const int X400Address = 3;
+ public const int DirectoryName = 4;
+ public const int EdiPartyName = 5;
+ public const int UniformResourceIdentifier = 6;
+ public const int IPAddress = 7;
+ public const int RegisteredID = 8;
+
+ internal readonly Asn1Encodable obj;
+ internal readonly int tag;
+
+ public GeneralName(
+ X509Name directoryName)
+ {
+ this.obj = directoryName;
+ this.tag = 4;
+ }
+
+ /**
+ * When the subjectAltName extension contains an Internet mail address,
+ * the address MUST be included as an rfc822Name. The format of an
+ * rfc822Name is an "addr-spec" as defined in RFC 822 [RFC 822].
+ *
+ * When the subjectAltName extension contains a domain name service
+ * label, the domain name MUST be stored in the dNSName (an IA5String).
+ * The name MUST be in the "preferred name syntax," as specified by RFC
+ * 1034 [RFC 1034].
+ *
+ * When the subjectAltName extension contains a URI, the name MUST be
+ * stored in the uniformResourceIdentifier (an IA5String). The name MUST
+ * be a non-relative URL, and MUST follow the URL syntax and encoding
+ * rules specified in [RFC 1738]. The name must include both a scheme
+ * (e.g., "http" or "ftp") and a scheme-specific-part. The scheme-
+ * specific-part must include a fully qualified domain name or IP
+ * address as the host.
+ *
+ * When the subjectAltName extension contains a iPAddress, the address
+ * MUST be stored in the octet string in "network byte order," as
+ * specified in RFC 791 [RFC 791]. The least significant bit (LSB) of
+ * each octet is the LSB of the corresponding byte in the network
+ * address. For IP Version 4, as specified in RFC 791, the octet string
+ * MUST contain exactly four octets. For IP Version 6, as specified in
+ * RFC 1883, the octet string MUST contain exactly sixteen octets [RFC
+ * 1883].
+ */
+ public GeneralName(
+ Asn1Object name,
+ int tag)
+ {
+ this.obj = name;
+ this.tag = tag;
+ }
+
+ public GeneralName(
+ int tag,
+ Asn1Encodable name)
+ {
+ this.obj = name;
+ this.tag = tag;
+ }
+
+ /**
+ * Create a GeneralName for the given tag from the passed in string.
+ *
+ * This constructor can handle:
+ *
+ *
rfc822Name
+ *
iPAddress
+ *
directoryName
+ *
dNSName
+ *
uniformResourceIdentifier
+ *
registeredID
+ *
+ * For x400Address, otherName and ediPartyName there is no common string
+ * format defined.
+ *
+ * Note: A directory name can be encoded in different ways into a byte
+ * representation. Be aware of this if the byte representation is used for
+ * comparing results.
+ *
+ *
+ * @param tag tag number
+ * @param name string representation of name
+ * @throws ArgumentException if the string encoding is not correct or
+ * not supported.
+ */
+ public GeneralName(
+ int tag,
+ string name)
+ {
+ this.tag = tag;
+
+ if (tag == Rfc822Name || tag == DnsName || tag == UniformResourceIdentifier)
+ {
+ this.obj = new DerIA5String(name);
+ }
+ else if (tag == RegisteredID)
+ {
+ this.obj = new DerObjectIdentifier(name);
+ }
+ else if (tag == DirectoryName)
+ {
+ this.obj = new X509Name(name);
+ }
+ else if (tag == IPAddress)
+ {
+ byte[] enc = toGeneralNameEncoding(name);
+ if (enc == null)
+ throw new ArgumentException("IP Address is invalid", "name");
+
+ this.obj = new DerOctetString(enc);
+ }
+ else
+ {
+ throw new ArgumentException("can't process string for tag: " + tag, "tag");
+ }
+ }
+
+ public static GeneralName GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is GeneralName)
+ {
+ return (GeneralName) obj;
+ }
+
+ if (obj is Asn1TaggedObject)
+ {
+ Asn1TaggedObject tagObj = (Asn1TaggedObject) obj;
+ int tag = tagObj.TagNo;
+
+ switch (tag)
+ {
+ case OtherName:
+ return new GeneralName(tag, Asn1Sequence.GetInstance(tagObj, false));
+ case Rfc822Name:
+ return new GeneralName(tag, DerIA5String.GetInstance(tagObj, false));
+ case DnsName:
+ return new GeneralName(tag, DerIA5String.GetInstance(tagObj, false));
+ case X400Address:
+ throw new ArgumentException("unknown tag: " + tag);
+ case DirectoryName:
+ return new GeneralName(tag, X509Name.GetInstance(tagObj, true));
+ case EdiPartyName:
+ return new GeneralName(tag, Asn1Sequence.GetInstance(tagObj, false));
+ case UniformResourceIdentifier:
+ return new GeneralName(tag, DerIA5String.GetInstance(tagObj, false));
+ case IPAddress:
+ return new GeneralName(tag, Asn1OctetString.GetInstance(tagObj, false));
+ case RegisteredID:
+ return new GeneralName(tag, DerObjectIdentifier.GetInstance(tagObj, false));
+ }
+ }
+
+ if (obj is byte[])
+ {
+ try
+ {
+ return GetInstance(Asn1Object.FromByteArray((byte[])obj));
+ }
+ catch (IOException)
+ {
+ throw new ArgumentException("unable to parse encoded general name");
+ }
+ }
+
+ throw new ArgumentException("unknown object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+ }
+
+ public static GeneralName GetInstance(
+ Asn1TaggedObject tagObj,
+ bool explicitly)
+ {
+ return GetInstance(Asn1TaggedObject.GetInstance(tagObj, true));
+ }
+
+ public int TagNo
+ {
+ get { return tag; }
+ }
+
+ public Asn1Encodable Name
+ {
+ get { return obj; }
+ }
+
+ public override string ToString()
+ {
+ StringBuilder buf = new StringBuilder();
+ buf.Append(tag);
+ buf.Append(": ");
+
+ switch (tag)
+ {
+ case Rfc822Name:
+ case DnsName:
+ case UniformResourceIdentifier:
+ buf.Append(DerIA5String.GetInstance(obj).GetString());
+ break;
+ case DirectoryName:
+ buf.Append(X509Name.GetInstance(obj).ToString());
+ break;
+ default:
+ buf.Append(obj.ToString());
+ break;
+ }
+
+ return buf.ToString();
+ }
+
+ private byte[] toGeneralNameEncoding(
+ string ip)
+ {
+ if (NetUtils.IPAddress.IsValidIPv6WithNetmask(ip) || NetUtils.IPAddress.IsValidIPv6(ip))
+ {
+ int slashIndex = ip.IndexOf('/');
+
+ if (slashIndex < 0)
+ {
+ byte[] addr = new byte[16];
+ int[] parsedIp = parseIPv6(ip);
+ copyInts(parsedIp, addr, 0);
+
+ return addr;
+ }
+ else
+ {
+ byte[] addr = new byte[32];
+ int[] parsedIp = parseIPv6(ip.Substring(0, slashIndex));
+ copyInts(parsedIp, addr, 0);
+ string mask = ip.Substring(slashIndex + 1);
+ if (mask.IndexOf(':') > 0)
+ {
+ parsedIp = parseIPv6(mask);
+ }
+ else
+ {
+ parsedIp = parseMask(mask);
+ }
+ copyInts(parsedIp, addr, 16);
+
+ return addr;
+ }
+ }
+ else if (NetUtils.IPAddress.IsValidIPv4WithNetmask(ip) || NetUtils.IPAddress.IsValidIPv4(ip))
+ {
+ int slashIndex = ip.IndexOf('/');
+
+ if (slashIndex < 0)
+ {
+ byte[] addr = new byte[4];
+
+ parseIPv4(ip, addr, 0);
+
+ return addr;
+ }
+ else
+ {
+ byte[] addr = new byte[8];
+
+ parseIPv4(ip.Substring(0, slashIndex), addr, 0);
+
+ string mask = ip.Substring(slashIndex + 1);
+ if (mask.IndexOf('.') > 0)
+ {
+ parseIPv4(mask, addr, 4);
+ }
+ else
+ {
+ parseIPv4Mask(mask, addr, 4);
+ }
+
+ return addr;
+ }
+ }
+
+ return null;
+ }
+
+ private void parseIPv4Mask(string mask, byte[] addr, int offset)
+ {
+ int maskVal = Int32.Parse(mask);
+
+ for (int i = 0; i != maskVal; i++)
+ {
+ addr[(i / 8) + offset] |= (byte)(1 << (i % 8));
+ }
+ }
+
+ private void parseIPv4(string ip, byte[] addr, int offset)
+ {
+ foreach (string token in ip.Split('.', '/'))
+ {
+ addr[offset++] = (byte)Int32.Parse(token);
+ }
+ }
+
+ private int[] parseMask(string mask)
+ {
+ int[] res = new int[8];
+ int maskVal = Int32.Parse(mask);
+
+ for (int i = 0; i != maskVal; i++)
+ {
+ res[i / 16] |= 1 << (i % 16);
+ }
+ return res;
+ }
+
+ private void copyInts(int[] parsedIp, byte[] addr, int offSet)
+ {
+ for (int i = 0; i != parsedIp.Length; i++)
+ {
+ addr[(i * 2) + offSet] = (byte)(parsedIp[i] >> 8);
+ addr[(i * 2 + 1) + offSet] = (byte)parsedIp[i];
+ }
+ }
+
+ private int[] parseIPv6(string ip)
+ {
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(ip, "::"))
+ {
+ ip = ip.Substring(1);
+ }
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(ip, "::"))
+ {
+ ip = ip.Substring(0, ip.Length - 1);
+ }
+
+ IEnumerator sEnum = ip.Split(':').GetEnumerator();
+
+ int index = 0;
+ int[] val = new int[8];
+
+ int doubleColon = -1;
+
+ while (sEnum.MoveNext())
+ {
+ string e = (string) sEnum.Current;
+
+ if (e.Length == 0)
+ {
+ doubleColon = index;
+ val[index++] = 0;
+ }
+ else
+ {
+ if (e.IndexOf('.') < 0)
+ {
+ val[index++] = Int32.Parse(e, NumberStyles.AllowHexSpecifier);
+ }
+ else
+ {
+ string[] tokens = e.Split('.');
+
+ val[index++] = (Int32.Parse(tokens[0]) << 8) | Int32.Parse(tokens[1]);
+ val[index++] = (Int32.Parse(tokens[2]) << 8) | Int32.Parse(tokens[3]);
+ }
+ }
+ }
+
+ if (index != val.Length)
+ {
+ Array.Copy(val, doubleColon, val, val.Length - (index - doubleColon), index - doubleColon);
+ for (int i = doubleColon; i != val.Length - (index - doubleColon); i++)
+ {
+ val[i] = 0;
+ }
+ }
+
+ return val;
+ }
+
+ public override Asn1Object ToAsn1Object()
+ {
+ // Explicitly tagged if DirectoryName
+ return new DerTaggedObject(tag == DirectoryName, tag, obj);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/GeneralName.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/GeneralName.cs.meta
new file mode 100644
index 00000000..2ce0ce85
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/GeneralName.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 8f9fa15cc99df23488aa1a0f35bb278d
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/GeneralNames.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/GeneralNames.cs
new file mode 100644
index 00000000..c1c887ff
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/GeneralNames.cs
@@ -0,0 +1,99 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509
+{
+ public class GeneralNames
+ : Asn1Encodable
+ {
+ private readonly GeneralName[] names;
+
+ public static GeneralNames GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is GeneralNames)
+ {
+ return (GeneralNames) obj;
+ }
+
+ if (obj is Asn1Sequence)
+ {
+ return new GeneralNames((Asn1Sequence) obj);
+ }
+
+ throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+ }
+
+ public static GeneralNames GetInstance(
+ Asn1TaggedObject obj,
+ bool explicitly)
+ {
+ return GetInstance(Asn1Sequence.GetInstance(obj, explicitly));
+ }
+
+ /// Construct a GeneralNames object containing one GeneralName.
+ /// The name to be contained.
+ public GeneralNames(
+ GeneralName name)
+ {
+ names = new GeneralName[]{ name };
+ }
+
+ public GeneralNames(
+ GeneralName[] names)
+ {
+ this.names = (GeneralName[])names.Clone();
+ }
+
+ private GeneralNames(
+ Asn1Sequence seq)
+ {
+ this.names = new GeneralName[seq.Count];
+
+ for (int i = 0; i != seq.Count; i++)
+ {
+ names[i] = GeneralName.GetInstance(seq[i]);
+ }
+ }
+
+ public GeneralName[] GetNames()
+ {
+ return (GeneralName[]) names.Clone();
+ }
+
+ /**
+ * Produce an object suitable for an Asn1OutputStream.
+ *
+ * For an v2 attribute certificate this is:
+ *
+ *
+ * Holder ::= SEQUENCE {
+ * baseCertificateID [0] IssuerSerial OPTIONAL,
+ * -- the issuer and serial number of
+ * -- the holder's Public Key Certificate
+ * entityName [1] GeneralNames OPTIONAL,
+ * -- the name of the claimant or role
+ * objectDigestInfo [2] ObjectDigestInfo OPTIONAL
+ * -- used to directly authenticate the holder,
+ * -- for example, an executable
+ * }
+ *
+ *
+ *
+ * For an v1 attribute certificate this is:
+ *
+ *
+ * subject CHOICE {
+ * baseCertificateID [0] IssuerSerial,
+ * -- associated with a Public Key Certificate
+ * subjectName [1] GeneralNames },
+ * -- associated with a name
+ *
+ *
+ */
+ public class Holder
+ : Asn1Encodable
+ {
+ internal readonly IssuerSerial baseCertificateID;
+ internal readonly GeneralNames entityName;
+ internal readonly ObjectDigestInfo objectDigestInfo;
+ private readonly int version;
+
+ public static Holder GetInstance(
+ object obj)
+ {
+ if (obj is Holder)
+ {
+ return (Holder) obj;
+ }
+
+ if (obj is Asn1Sequence)
+ {
+ return new Holder((Asn1Sequence) obj);
+ }
+
+ if (obj is Asn1TaggedObject)
+ {
+ return new Holder((Asn1TaggedObject) obj);
+ }
+
+ throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+ }
+
+ /**
+ * Constructor for a holder for an v1 attribute certificate.
+ *
+ * @param tagObj The ASN.1 tagged holder object.
+ */
+ public Holder(
+ Asn1TaggedObject tagObj)
+ {
+ switch (tagObj.TagNo)
+ {
+ case 0:
+ baseCertificateID = IssuerSerial.GetInstance(tagObj, false);
+ break;
+ case 1:
+ entityName = GeneralNames.GetInstance(tagObj, false);
+ break;
+ default:
+ throw new ArgumentException("unknown tag in Holder");
+ }
+
+ this.version = 0;
+ }
+
+ /**
+ * Constructor for a holder for an v2 attribute certificate. *
+ *
+ * @param seq The ASN.1 sequence.
+ */
+ private Holder(
+ Asn1Sequence seq)
+ {
+ if (seq.Count > 3)
+ throw new ArgumentException("Bad sequence size: " + seq.Count);
+
+ for (int i = 0; i != seq.Count; i++)
+ {
+ Asn1TaggedObject tObj = Asn1TaggedObject.GetInstance(seq[i]);
+
+ switch (tObj.TagNo)
+ {
+ case 0:
+ baseCertificateID = IssuerSerial.GetInstance(tObj, false);
+ break;
+ case 1:
+ entityName = GeneralNames.GetInstance(tObj, false);
+ break;
+ case 2:
+ objectDigestInfo = ObjectDigestInfo.GetInstance(tObj, false);
+ break;
+ default:
+ throw new ArgumentException("unknown tag in Holder");
+ }
+ }
+
+ this.version = 1;
+ }
+
+ public Holder(
+ IssuerSerial baseCertificateID)
+ : this(baseCertificateID, 1)
+ {
+ }
+
+ /**
+ * Constructs a holder from a IssuerSerial.
+ * @param baseCertificateID The IssuerSerial.
+ * @param version The version of the attribute certificate.
+ */
+ public Holder(
+ IssuerSerial baseCertificateID,
+ int version)
+ {
+ this.baseCertificateID = baseCertificateID;
+ this.version = version;
+ }
+
+ /**
+ * Returns 1 for v2 attribute certificates or 0 for v1 attribute
+ * certificates.
+ * @return The version of the attribute certificate.
+ */
+ public int Version
+ {
+ get { return version; }
+ }
+
+ /**
+ * Constructs a holder with an entityName for v2 attribute certificates or
+ * with a subjectName for v1 attribute certificates.
+ *
+ * @param entityName The entity or subject name.
+ */
+ public Holder(
+ GeneralNames entityName)
+ : this(entityName, 1)
+ {
+ }
+
+ /**
+ * Constructs a holder with an entityName for v2 attribute certificates or
+ * with a subjectName for v1 attribute certificates.
+ *
+ * @param entityName The entity or subject name.
+ * @param version The version of the attribute certificate.
+ */
+ public Holder(
+ GeneralNames entityName,
+ int version)
+ {
+ this.entityName = entityName;
+ this.version = version;
+ }
+
+ /**
+ * Constructs a holder from an object digest info.
+ *
+ * @param objectDigestInfo The object digest info object.
+ */
+ public Holder(
+ ObjectDigestInfo objectDigestInfo)
+ {
+ this.objectDigestInfo = objectDigestInfo;
+ this.version = 1;
+ }
+
+ public IssuerSerial BaseCertificateID
+ {
+ get { return baseCertificateID; }
+ }
+
+ /**
+ * Returns the entityName for an v2 attribute certificate or the subjectName
+ * for an v1 attribute certificate.
+ *
+ * @return The entityname or subjectname.
+ */
+ public GeneralNames EntityName
+ {
+ get { return entityName; }
+ }
+
+ public ObjectDigestInfo ObjectDigestInfo
+ {
+ get { return objectDigestInfo; }
+ }
+
+ /**
+ * The Holder object.
+ *
+ * Holder ::= Sequence {
+ * baseCertificateID [0] IssuerSerial OPTIONAL,
+ * -- the issuer and serial number of
+ * -- the holder's Public Key Certificate
+ * entityName [1] GeneralNames OPTIONAL,
+ * -- the name of the claimant or role
+ * objectDigestInfo [2] ObjectDigestInfo OPTIONAL
+ * -- used to directly authenticate the holder,
+ * -- for example, an executable
+ * }
+ *
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ if (version == 1)
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector();
+
+ if (baseCertificateID != null)
+ {
+ v.Add(new DerTaggedObject(false, 0, baseCertificateID));
+ }
+
+ if (entityName != null)
+ {
+ v.Add(new DerTaggedObject(false, 1, entityName));
+ }
+
+ if (objectDigestInfo != null)
+ {
+ v.Add(new DerTaggedObject(false, 2, objectDigestInfo));
+ }
+
+ return new DerSequence(v);
+ }
+
+ if (entityName != null)
+ {
+ return new DerTaggedObject(false, 1, entityName);
+ }
+
+ return new DerTaggedObject(false, 0, baseCertificateID);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/Holder.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/Holder.cs.meta
new file mode 100644
index 00000000..64ecd73c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/Holder.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c9e8d3105c3fd874f887aff60be61f33
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/IetfAttrSyntax.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/IetfAttrSyntax.cs
new file mode 100644
index 00000000..5d2d03eb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/IetfAttrSyntax.cs
@@ -0,0 +1,165 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509
+{
+ /**
+ * Implementation of IetfAttrSyntax as specified by RFC3281.
+ */
+ public class IetfAttrSyntax
+ : Asn1Encodable
+ {
+ public const int ValueOctets = 1;
+ public const int ValueOid = 2;
+ public const int ValueUtf8 = 3;
+
+ internal readonly GeneralNames policyAuthority;
+ internal readonly Asn1EncodableVector values = new Asn1EncodableVector();
+
+ internal int valueChoice = -1;
+
+ /**
+ *
+ */
+ public IetfAttrSyntax(
+ Asn1Sequence seq)
+ {
+ int i = 0;
+
+ if (seq[0] is Asn1TaggedObject)
+ {
+ policyAuthority = GeneralNames.GetInstance(((Asn1TaggedObject)seq[0]), false);
+ i++;
+ }
+ else if (seq.Count == 2)
+ { // VOMS fix
+ policyAuthority = GeneralNames.GetInstance(seq[0]);
+ i++;
+ }
+
+ if (!(seq[i] is Asn1Sequence))
+ {
+ throw new ArgumentException("Non-IetfAttrSyntax encoding");
+ }
+
+ seq = (Asn1Sequence) seq[i];
+
+ foreach (Asn1Object obj in seq)
+ {
+ int type;
+
+ if (obj is DerObjectIdentifier)
+ {
+ type = ValueOid;
+ }
+ else if (obj is DerUtf8String)
+ {
+ type = ValueUtf8;
+ }
+ else if (obj is DerOctetString)
+ {
+ type = ValueOctets;
+ }
+ else
+ {
+ throw new ArgumentException("Bad value type encoding IetfAttrSyntax");
+ }
+
+ if (valueChoice < 0)
+ {
+ valueChoice = type;
+ }
+
+ if (type != valueChoice)
+ {
+ throw new ArgumentException("Mix of value types in IetfAttrSyntax");
+ }
+
+ values.Add(obj);
+ }
+ }
+
+ public GeneralNames PolicyAuthority
+ {
+ get { return policyAuthority; }
+ }
+
+ public int ValueType
+ {
+ get { return valueChoice; }
+ }
+
+ public object[] GetValues()
+ {
+ if (this.ValueType == ValueOctets)
+ {
+ Asn1OctetString[] tmp = new Asn1OctetString[values.Count];
+
+ for (int i = 0; i != tmp.Length; i++)
+ {
+ tmp[i] = (Asn1OctetString) values[i];
+ }
+
+ return tmp;
+ }
+
+ if (this.ValueType == ValueOid)
+ {
+ DerObjectIdentifier[] tmp = new DerObjectIdentifier[values.Count];
+
+ for (int i = 0; i != tmp.Length; i++)
+ {
+ tmp[i] = (DerObjectIdentifier) values[i];
+ }
+
+ return tmp;
+ }
+
+ {
+ DerUtf8String[] tmp = new DerUtf8String[values.Count];
+
+ for (int i = 0; i != tmp.Length; i++)
+ {
+ tmp[i] = (DerUtf8String) values[i];
+ }
+
+ return tmp;
+ }
+ }
+
+ /**
+ *
+ *
+ */
+ public class RoleSyntax
+ : Asn1Encodable
+ {
+ private readonly GeneralNames roleAuthority;
+ private readonly GeneralName roleName;
+
+ /**
+ * RoleSyntax factory method.
+ * @param obj the object used to construct an instance of
+ * RoleSyntax. It must be an instance of RoleSyntax
+ * or Asn1Sequence.
+ * @return the instance of RoleSyntax built from the
+ * supplied object.
+ * @throws java.lang.ArgumentException if the object passed
+ * to the factory is not an instance of RoleSyntax or
+ * Asn1Sequence.
+ */
+ public static RoleSyntax GetInstance(
+ object obj)
+ {
+ if (obj is RoleSyntax)
+ return (RoleSyntax)obj;
+
+ if (obj != null)
+ return new RoleSyntax(Asn1Sequence.GetInstance(obj));
+
+ return null;
+ }
+
+ /**
+ * Constructor.
+ * @param roleAuthority the role authority of this RoleSyntax.
+ * @param roleName the role name of this RoleSyntax.
+ */
+ public RoleSyntax(
+ GeneralNames roleAuthority,
+ GeneralName roleName)
+ {
+ if (roleName == null
+ || roleName.TagNo != GeneralName.UniformResourceIdentifier
+ || ((IAsn1String) roleName.Name).GetString().Equals(""))
+ {
+ throw new ArgumentException("the role name MUST be non empty and MUST " +
+ "use the URI option of GeneralName");
+ }
+
+ this.roleAuthority = roleAuthority;
+ this.roleName = roleName;
+ }
+
+ /**
+ * Constructor. Invoking this constructor is the same as invoking
+ * new RoleSyntax(null, roleName).
+ * @param roleName the role name of this RoleSyntax.
+ */
+ public RoleSyntax(
+ GeneralName roleName)
+ : this(null, roleName)
+ {
+ }
+
+ /**
+ * Utility constructor. Takes a string argument representing
+ * the role name, builds a GeneralName to hold the role name
+ * and calls the constructor that takes a GeneralName.
+ * @param roleName
+ */
+ public RoleSyntax(
+ string roleName)
+ : this(new GeneralName(GeneralName.UniformResourceIdentifier,
+ (roleName == null)? "": roleName))
+ {
+ }
+
+ /**
+ * Constructor that builds an instance of RoleSyntax by
+ * extracting the encoded elements from the Asn1Sequence
+ * object supplied.
+ * @param seq an instance of Asn1Sequence that holds
+ * the encoded elements used to build this RoleSyntax.
+ */
+ private RoleSyntax(
+ Asn1Sequence seq)
+ {
+ if (seq.Count < 1 || seq.Count > 2)
+ {
+ throw new ArgumentException("Bad sequence size: " + seq.Count);
+ }
+
+ for (int i = 0; i != seq.Count; i++)
+ {
+ Asn1TaggedObject taggedObject = Asn1TaggedObject.GetInstance(seq[i]);
+ switch (taggedObject.TagNo)
+ {
+ case 0:
+ roleAuthority = GeneralNames.GetInstance(taggedObject, false);
+ break;
+ case 1:
+ roleName = GeneralName.GetInstance(taggedObject, true);
+ break;
+ default:
+ throw new ArgumentException("Unknown tag in RoleSyntax");
+ }
+ }
+ }
+
+ /**
+ * Gets the role authority of this RoleSyntax.
+ * @return an instance of GeneralNames holding the
+ * role authority of this RoleSyntax.
+ */
+ public GeneralNames RoleAuthority
+ {
+ get { return this.roleAuthority; }
+ }
+
+ /**
+ * Gets the role name of this RoleSyntax.
+ * @return an instance of GeneralName holding the
+ * role name of this RoleSyntax.
+ */
+ public GeneralName RoleName
+ {
+ get { return this.roleName; }
+ }
+
+ /**
+ * Gets the role name as a java.lang.string object.
+ * @return the role name of this RoleSyntax represented as a
+ * string object.
+ */
+ public string GetRoleNameAsString()
+ {
+ return ((IAsn1String) this.roleName.Name).GetString();
+ }
+
+ /**
+ * Gets the role authority as a string[] object.
+ * @return the role authority of this RoleSyntax represented as a
+ * string[] array.
+ */
+ public string[] GetRoleAuthorityAsString()
+ {
+ if (roleAuthority == null)
+ {
+ return new string[0];
+ }
+
+ GeneralName[] names = roleAuthority.GetNames();
+ string[] namesString = new string[names.Length];
+ for(int i = 0; i < names.Length; i++)
+ {
+ Asn1Encodable asn1Value = names[i].Name;
+ if (asn1Value is IAsn1String)
+ {
+ namesString[i] = ((IAsn1String) asn1Value).GetString();
+ }
+ else
+ {
+ namesString[i] = asn1Value.ToString();
+ }
+ }
+
+ return namesString;
+ }
+
+ /**
+ * Implementation of the method ToAsn1Object as
+ * required by the superclass ASN1Encodable.
+ *
+ *
+ */
+ public class SubjectKeyIdentifier
+ : Asn1Encodable
+ {
+ private readonly byte[] keyIdentifier;
+
+ public static SubjectKeyIdentifier GetInstance(
+ Asn1TaggedObject obj,
+ bool explicitly)
+ {
+ return GetInstance(Asn1OctetString.GetInstance(obj, explicitly));
+ }
+
+ public static SubjectKeyIdentifier GetInstance(
+ object obj)
+ {
+ if (obj is SubjectKeyIdentifier)
+ {
+ return (SubjectKeyIdentifier) obj;
+ }
+
+ if (obj is SubjectPublicKeyInfo)
+ {
+ return new SubjectKeyIdentifier((SubjectPublicKeyInfo) obj);
+ }
+
+ if (obj is Asn1OctetString)
+ {
+ return new SubjectKeyIdentifier((Asn1OctetString) obj);
+ }
+
+ if (obj is X509Extension)
+ {
+ return GetInstance(X509Extension.ConvertValueToObject((X509Extension) obj));
+ }
+
+ throw new ArgumentException("Invalid SubjectKeyIdentifier: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj));
+ }
+
+ public SubjectKeyIdentifier(
+ byte[] keyID)
+ {
+ if (keyID == null)
+ throw new ArgumentNullException("keyID");
+
+ this.keyIdentifier = keyID;
+ }
+
+ public SubjectKeyIdentifier(
+ Asn1OctetString keyID)
+ {
+ this.keyIdentifier = keyID.GetOctets();
+ }
+
+ /**
+ * Calculates the keyIdentifier using a SHA1 hash over the BIT STRING
+ * from SubjectPublicKeyInfo as defined in RFC3280.
+ *
+ * @param spki the subject public key info.
+ */
+ public SubjectKeyIdentifier(
+ SubjectPublicKeyInfo spki)
+ {
+ this.keyIdentifier = GetDigest(spki);
+ }
+
+ public byte[] GetKeyIdentifier()
+ {
+ return keyIdentifier;
+ }
+
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerOctetString(keyIdentifier);
+ }
+
+ /**
+ * Return a RFC 3280 type 1 key identifier. As in:
+ *
+ * (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the
+ * value of the BIT STRING subjectPublicKey (excluding the tag,
+ * length, and number of unused bits).
+ *
+ * @param keyInfo the key info object containing the subjectPublicKey field.
+ * @return the key identifier.
+ */
+ public static SubjectKeyIdentifier CreateSha1KeyIdentifier(
+ SubjectPublicKeyInfo keyInfo)
+ {
+ return new SubjectKeyIdentifier(keyInfo);
+ }
+
+ /**
+ * Return a RFC 3280 type 2 key identifier. As in:
+ *
+ * (2) The keyIdentifier is composed of a four bit type field with
+ * the value 0100 followed by the least significant 60 bits of the
+ * SHA-1 hash of the value of the BIT STRING subjectPublicKey.
+ *
+ * Note: issuerUniqueID and subjectUniqueID are both deprecated by the IETF. This class
+ * will parse them, but you really shouldn't be creating new ones.
+ */
+ public class TbsCertificateStructure
+ : Asn1Encodable
+ {
+ internal Asn1Sequence seq;
+ internal DerInteger version;
+ internal DerInteger serialNumber;
+ internal AlgorithmIdentifier signature;
+ internal X509Name issuer;
+ internal Time startDate, endDate;
+ internal X509Name subject;
+ internal SubjectPublicKeyInfo subjectPublicKeyInfo;
+ internal DerBitString issuerUniqueID;
+ internal DerBitString subjectUniqueID;
+ internal X509Extensions extensions;
+
+ public static TbsCertificateStructure GetInstance(
+ Asn1TaggedObject obj,
+ bool explicitly)
+ {
+ return GetInstance(Asn1Sequence.GetInstance(obj, explicitly));
+ }
+
+ public static TbsCertificateStructure GetInstance(
+ object obj)
+ {
+ if (obj is TbsCertificateStructure)
+ return (TbsCertificateStructure) obj;
+
+ if (obj != null)
+ return new TbsCertificateStructure(Asn1Sequence.GetInstance(obj));
+
+ return null;
+ }
+
+ internal TbsCertificateStructure(
+ Asn1Sequence seq)
+ {
+ int seqStart = 0;
+
+ this.seq = seq;
+
+ //
+ // some certficates don't include a version number - we assume v1
+ //
+ if (seq[0] is DerTaggedObject)
+ {
+ version = DerInteger.GetInstance((Asn1TaggedObject)seq[0], true);
+ }
+ else
+ {
+ seqStart = -1; // field 0 is missing!
+ version = new DerInteger(0);
+ }
+
+ bool isV1 = false;
+ bool isV2 = false;
+
+ if (version.Value.Equals(BigInteger.Zero))
+ {
+ isV1 = true;
+ }
+ else if (version.Value.Equals(BigInteger.One))
+ {
+ isV2 = true;
+ }
+ else if (!version.Value.Equals(BigInteger.Two))
+ {
+ throw new ArgumentException("version number not recognised");
+ }
+
+ serialNumber = DerInteger.GetInstance(seq[seqStart + 1]);
+
+ signature = AlgorithmIdentifier.GetInstance(seq[seqStart + 2]);
+ issuer = X509Name.GetInstance(seq[seqStart + 3]);
+
+ //
+ // before and after dates
+ //
+ Asn1Sequence dates = (Asn1Sequence)seq[seqStart + 4];
+
+ startDate = Time.GetInstance(dates[0]);
+ endDate = Time.GetInstance(dates[1]);
+
+ subject = X509Name.GetInstance(seq[seqStart + 5]);
+
+ //
+ // public key info.
+ //
+ subjectPublicKeyInfo = SubjectPublicKeyInfo.GetInstance(seq[seqStart + 6]);
+
+ int extras = seq.Count - (seqStart + 6) - 1;
+ if (extras != 0 && isV1)
+ throw new ArgumentException("version 1 certificate contains extra data");
+
+ while (extras > 0)
+ {
+ DerTaggedObject extra = (DerTaggedObject)seq[seqStart + 6 + extras];
+
+ switch (extra.TagNo)
+ {
+ case 1:
+ {
+ issuerUniqueID = DerBitString.GetInstance(extra, false);
+ break;
+ }
+ case 2:
+ {
+ subjectUniqueID = DerBitString.GetInstance(extra, false);
+ break;
+ }
+ case 3:
+ {
+ if (isV2)
+ throw new ArgumentException("version 2 certificate cannot contain extensions");
+
+ extensions = X509Extensions.GetInstance(Asn1Sequence.GetInstance(extra, true));
+ break;
+ }
+ default:
+ {
+ throw new ArgumentException("Unknown tag encountered in structure: " + extra.TagNo);
+ }
+ }
+ extras--;
+ }
+ }
+
+ public int Version
+ {
+ get { return version.Value.IntValue + 1; }
+ }
+
+ public DerInteger VersionNumber
+ {
+ get { return version; }
+ }
+
+ public DerInteger SerialNumber
+ {
+ get { return serialNumber; }
+ }
+
+ public AlgorithmIdentifier Signature
+ {
+ get { return signature; }
+ }
+
+ public X509Name Issuer
+ {
+ get { return issuer; }
+ }
+
+ public Time StartDate
+ {
+ get { return startDate; }
+ }
+
+ public Time EndDate
+ {
+ get { return endDate; }
+ }
+
+ public X509Name Subject
+ {
+ get { return subject; }
+ }
+
+ public SubjectPublicKeyInfo SubjectPublicKeyInfo
+ {
+ get { return subjectPublicKeyInfo; }
+ }
+
+ public DerBitString IssuerUniqueID
+ {
+ get { return issuerUniqueID; }
+ }
+
+ public DerBitString SubjectUniqueID
+ {
+ get { return subjectUniqueID; }
+ }
+
+ public X509Extensions Extensions
+ {
+ get { return extensions; }
+ }
+
+ public override Asn1Object ToAsn1Object()
+ {
+ return seq;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/TBSCertificateStructure.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/TBSCertificateStructure.cs.meta
new file mode 100644
index 00000000..d3edbb24
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/TBSCertificateStructure.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ebe58b240e863284fa86f16c303f818a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/Target.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/Target.cs
new file mode 100644
index 00000000..b3e84cf1
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/Target.cs
@@ -0,0 +1,145 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509
+{
+ /**
+ * Target structure used in target information extension for attribute
+ * certificates from RFC 3281.
+ *
+ *
+ *
+ * @return an Asn1Object
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ // GeneralName is a choice already so most be explicitly tagged
+ if (targetName != null)
+ {
+ return new DerTaggedObject(true, 0, targetName);
+ }
+
+ return new DerTaggedObject(true, 1, targetGroup);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/Target.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/Target.cs.meta
new file mode 100644
index 00000000..fe1c7fd1
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/Target.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: b4ad4b705590a2048ab897084fba3cd8
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/TargetInformation.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/TargetInformation.cs
new file mode 100644
index 00000000..3edd2c4a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/TargetInformation.cs
@@ -0,0 +1,129 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509
+{
+ /**
+ * Target information extension for attributes certificates according to RFC
+ * 3281.
+ *
+ *
+ * SEQUENCE OF Targets
+ *
+ *
+ */
+ public class TargetInformation
+ : Asn1Encodable
+ {
+ private readonly Asn1Sequence targets;
+
+ /**
+ * Creates an instance of a TargetInformation from the given object.
+ *
+ * obj can be a TargetInformation or a {@link Asn1Sequence}
+ *
+ * @param obj The object.
+ * @return A TargetInformation instance.
+ * @throws ArgumentException if the given object cannot be interpreted as TargetInformation.
+ */
+ public static TargetInformation GetInstance(
+ object obj)
+ {
+ if (obj is TargetInformation)
+ {
+ return (TargetInformation) obj;
+ }
+
+ if (obj is Asn1Sequence)
+ {
+ return new TargetInformation((Asn1Sequence) obj);
+ }
+
+ throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+ }
+
+ /**
+ * Constructor from a Asn1Sequence.
+ *
+ * @param seq The Asn1Sequence.
+ * @throws ArgumentException if the sequence does not contain
+ * correctly encoded Targets elements.
+ */
+ private TargetInformation(
+ Asn1Sequence targets)
+ {
+ this.targets = targets;
+ }
+
+ /**
+ * Returns the targets in this target information extension.
+ *
+ * The ArrayList is cloned before it is returned.
+ *
+ * @return Returns the targets.
+ */
+ public virtual Targets[] GetTargetsObjects()
+ {
+ Targets[] result = new Targets[targets.Count];
+
+ for (int i = 0; i < targets.Count; ++i)
+ {
+ result[i] = Targets.GetInstance(targets[i]);
+ }
+
+ return result;
+ }
+
+ /**
+ * Constructs a target information from a single targets element.
+ * According to RFC 3281 only one targets element must be produced.
+ *
+ * @param targets A Targets instance.
+ */
+ public TargetInformation(
+ Targets targets)
+ {
+ this.targets = new DerSequence(targets);
+ }
+
+ /**
+ * According to RFC 3281 only one targets element must be produced. If
+ * multiple targets are given they must be merged in
+ * into one targets element.
+ *
+ * @param targets An array with {@link Targets}.
+ */
+ public TargetInformation(
+ Target[] targets)
+ : this(new Targets(targets))
+ {
+ }
+
+ /**
+ * Produce an object suitable for an Asn1OutputStream.
+ *
+ * Returns:
+ *
+ *
+ * SEQUENCE OF Targets
+ *
+ *
+ *
+ * According to RFC 3281 only one targets element must be produced. If
+ * multiple targets are given in the constructor they are merged into one
+ * targets element. If this was produced from a
+ * {@link BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Asn1Sequence} the encoding is kept.
+ *
+ * @see PolicyQualifierId
+ * @see PolicyInformation
+ */
+ public class UserNotice
+ : Asn1Encodable
+ {
+ private readonly NoticeReference noticeRef;
+ private readonly DisplayText explicitText;
+
+ /**
+ * Creates a new UserNotice instance.
+ *
+ * @param noticeRef a NoticeReference value
+ * @param explicitText a DisplayText value
+ */
+ public UserNotice(
+ NoticeReference noticeRef,
+ DisplayText explicitText)
+ {
+ this.noticeRef = noticeRef;
+ this.explicitText = explicitText;
+ }
+
+ /**
+ * Creates a new UserNotice instance.
+ *
+ * @param noticeRef a NoticeReference value
+ * @param str the explicitText field as a string.
+ */
+ public UserNotice(
+ NoticeReference noticeRef,
+ string str)
+ : this(noticeRef, new DisplayText(str))
+ {
+ }
+
+ /**
+ * Creates a new UserNotice instance.
+ *
Useful from reconstructing a UserNotice instance
+ * from its encodable/encoded form.
+ *
+ * @param as an ASN1Sequence value obtained from either
+ * calling @{link toASN1Object()} for a UserNotice
+ * instance or from parsing it from a DER-encoded stream.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector vec = new Asn1EncodableVector();
+
+ foreach (DerObjectIdentifier oid in ordering)
+ {
+ X509Extension ext = (X509Extension) extensions[oid];
+ Asn1EncodableVector v = new Asn1EncodableVector(oid);
+
+ if (ext.IsCritical)
+ {
+ v.Add(DerBoolean.True);
+ }
+
+ v.Add(ext.Value);
+
+ vec.Add(new DerSequence(v));
+ }
+
+ return new DerSequence(vec);
+ }
+
+ public bool Equivalent(
+ X509Extensions other)
+ {
+ if (extensions.Count != other.extensions.Count)
+ return false;
+
+ foreach (DerObjectIdentifier oid in extensions.Keys)
+ {
+ if (!extensions[oid].Equals(other.extensions[oid]))
+ return false;
+ }
+
+ return true;
+ }
+
+ public DerObjectIdentifier[] GetExtensionOids()
+ {
+ return ToOidArray(ordering);
+ }
+
+ public DerObjectIdentifier[] GetNonCriticalExtensionOids()
+ {
+ return GetExtensionOids(false);
+ }
+
+ public DerObjectIdentifier[] GetCriticalExtensionOids()
+ {
+ return GetExtensionOids(true);
+ }
+
+ private DerObjectIdentifier[] GetExtensionOids(bool isCritical)
+ {
+ IList oids = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+
+ foreach (DerObjectIdentifier oid in this.ordering)
+ {
+ X509Extension ext = (X509Extension)extensions[oid];
+ if (ext.IsCritical == isCritical)
+ {
+ oids.Add(oid);
+ }
+ }
+
+ return ToOidArray(oids);
+ }
+
+ private static DerObjectIdentifier[] ToOidArray(IList oids)
+ {
+ DerObjectIdentifier[] oidArray = new DerObjectIdentifier[oids.Count];
+ oids.CopyTo(oidArray, 0);
+ return oidArray;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/X509Extensions.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/X509Extensions.cs.meta
new file mode 100644
index 00000000..3b11f40a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/X509Extensions.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 00b54aa58571c6e429b23126f5560710
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/X509ExtensionsGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/X509ExtensionsGenerator.cs
new file mode 100644
index 00000000..675d7dc9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/X509ExtensionsGenerator.cs
@@ -0,0 +1,85 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509
+{
+ /// Generator for X.509 extensions
+ public class X509ExtensionsGenerator
+ {
+ private IDictionary extensions = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ private IList extOrdering = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+
+ /// Reset the generator
+ public void Reset()
+ {
+ extensions = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ extOrdering = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ }
+
+ ///
+ /// Add an extension with the given oid and the passed in value to be included
+ /// in the OCTET STRING associated with the extension.
+ ///
+ /// OID for the extension.
+ /// True if critical, false otherwise.
+ /// The ASN.1 object to be included in the extension.
+ public void AddExtension(
+ DerObjectIdentifier oid,
+ bool critical,
+ Asn1Encodable extValue)
+ {
+ byte[] encoded;
+ try
+ {
+ encoded = extValue.GetDerEncoded();
+ }
+ catch (Exception e)
+ {
+ throw new ArgumentException("error encoding value: " + e);
+ }
+
+ this.AddExtension(oid, critical, encoded);
+ }
+
+ ///
+ /// Add an extension with the given oid and the passed in byte array to be wrapped
+ /// in the OCTET STRING associated with the extension.
+ ///
+ /// OID for the extension.
+ /// True if critical, false otherwise.
+ /// The byte array to be wrapped.
+ public void AddExtension(
+ DerObjectIdentifier oid,
+ bool critical,
+ byte[] extValue)
+ {
+ if (extensions.Contains(oid))
+ {
+ throw new ArgumentException("extension " + oid + " already added");
+ }
+
+ extOrdering.Add(oid);
+ extensions.Add(oid, new X509Extension(critical, new DerOctetString(extValue)));
+ }
+
+ /// Return true if there are no extension present in this generator.
+ /// True if empty, false otherwise
+ public bool IsEmpty
+ {
+ get { return extOrdering.Count < 1; }
+ }
+
+ /// Generate an X509Extensions object based on the current state of the generator.
+ /// An X509Extensions object
+ public X509Extensions Generate()
+ {
+ return new X509Extensions(extOrdering, extensions);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/X509ExtensionsGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/X509ExtensionsGenerator.cs.meta
new file mode 100644
index 00000000..e4a7e8a7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/X509ExtensionsGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 17d0bf23e5bd4634286e5be7869c8ab4
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/X509Name.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/X509Name.cs
new file mode 100644
index 00000000..f43189af
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/X509Name.cs
@@ -0,0 +1,1086 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+using System.Text;
+
+#if SILVERLIGHT || PORTABLE || NETFX_CORE
+using System.Collections.Generic;
+#endif
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509
+{
+ /**
+ *
+ * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
+ *
+ * RelativeDistinguishedName ::= SET SIZE (1..MAX) OF AttributeTypeAndValue
+ *
+ * AttributeTypeAndValue ::= SEQUENCE {
+ * type OBJECT IDENTIFIER,
+ * value ANY }
+ *
+ */
+ public class X509Name
+ : Asn1Encodable
+ {
+ /**
+ * country code - StringType(SIZE(2))
+ */
+ public static readonly DerObjectIdentifier C = new DerObjectIdentifier("2.5.4.6");
+
+ /**
+ * organization - StringType(SIZE(1..64))
+ */
+ public static readonly DerObjectIdentifier O = new DerObjectIdentifier("2.5.4.10");
+
+ /**
+ * organizational unit name - StringType(SIZE(1..64))
+ */
+ public static readonly DerObjectIdentifier OU = new DerObjectIdentifier("2.5.4.11");
+
+ /**
+ * Title
+ */
+ public static readonly DerObjectIdentifier T = new DerObjectIdentifier("2.5.4.12");
+
+ /**
+ * common name - StringType(SIZE(1..64))
+ */
+ public static readonly DerObjectIdentifier CN = new DerObjectIdentifier("2.5.4.3");
+
+ /**
+ * street - StringType(SIZE(1..64))
+ */
+ public static readonly DerObjectIdentifier Street = new DerObjectIdentifier("2.5.4.9");
+
+ /**
+ * device serial number name - StringType(SIZE(1..64))
+ */
+ public static readonly DerObjectIdentifier SerialNumber = new DerObjectIdentifier("2.5.4.5");
+
+ /**
+ * locality name - StringType(SIZE(1..64))
+ */
+ public static readonly DerObjectIdentifier L = new DerObjectIdentifier("2.5.4.7");
+
+ /**
+ * state, or province name - StringType(SIZE(1..64))
+ */
+ public static readonly DerObjectIdentifier ST = new DerObjectIdentifier("2.5.4.8");
+
+ /**
+ * Naming attributes of type X520name
+ */
+ public static readonly DerObjectIdentifier Surname = new DerObjectIdentifier("2.5.4.4");
+ public static readonly DerObjectIdentifier GivenName = new DerObjectIdentifier("2.5.4.42");
+ public static readonly DerObjectIdentifier Initials = new DerObjectIdentifier("2.5.4.43");
+ public static readonly DerObjectIdentifier Generation = new DerObjectIdentifier("2.5.4.44");
+ public static readonly DerObjectIdentifier UniqueIdentifier = new DerObjectIdentifier("2.5.4.45");
+
+ /**
+ * businessCategory - DirectoryString(SIZE(1..128)
+ */
+ public static readonly DerObjectIdentifier BusinessCategory = new DerObjectIdentifier(
+ "2.5.4.15");
+
+ /**
+ * postalCode - DirectoryString(SIZE(1..40)
+ */
+ public static readonly DerObjectIdentifier PostalCode = new DerObjectIdentifier(
+ "2.5.4.17");
+
+ /**
+ * dnQualifier - DirectoryString(SIZE(1..64)
+ */
+ public static readonly DerObjectIdentifier DnQualifier = new DerObjectIdentifier(
+ "2.5.4.46");
+
+ /**
+ * RFC 3039 Pseudonym - DirectoryString(SIZE(1..64)
+ */
+ public static readonly DerObjectIdentifier Pseudonym = new DerObjectIdentifier(
+ "2.5.4.65");
+
+ /**
+ * RFC 3039 DateOfBirth - GeneralizedTime - YYYYMMDD000000Z
+ */
+ public static readonly DerObjectIdentifier DateOfBirth = new DerObjectIdentifier(
+ "1.3.6.1.5.5.7.9.1");
+
+ /**
+ * RFC 3039 PlaceOfBirth - DirectoryString(SIZE(1..128)
+ */
+ public static readonly DerObjectIdentifier PlaceOfBirth = new DerObjectIdentifier(
+ "1.3.6.1.5.5.7.9.2");
+
+ /**
+ * RFC 3039 DateOfBirth - PrintableString (SIZE(1)) -- "M", "F", "m" or "f"
+ */
+ public static readonly DerObjectIdentifier Gender = new DerObjectIdentifier(
+ "1.3.6.1.5.5.7.9.3");
+
+ /**
+ * RFC 3039 CountryOfCitizenship - PrintableString (SIZE (2)) -- ISO 3166
+ * codes only
+ */
+ public static readonly DerObjectIdentifier CountryOfCitizenship = new DerObjectIdentifier(
+ "1.3.6.1.5.5.7.9.4");
+
+ /**
+ * RFC 3039 CountryOfCitizenship - PrintableString (SIZE (2)) -- ISO 3166
+ * codes only
+ */
+ public static readonly DerObjectIdentifier CountryOfResidence = new DerObjectIdentifier(
+ "1.3.6.1.5.5.7.9.5");
+
+ /**
+ * ISIS-MTT NameAtBirth - DirectoryString(SIZE(1..64)
+ */
+ public static readonly DerObjectIdentifier NameAtBirth = new DerObjectIdentifier("1.3.36.8.3.14");
+
+ /**
+ * RFC 3039 PostalAddress - SEQUENCE SIZE (1..6) OF
+ * DirectoryString(SIZE(1..30))
+ */
+ public static readonly DerObjectIdentifier PostalAddress = new DerObjectIdentifier("2.5.4.16");
+
+ /**
+ * RFC 2256 dmdName
+ */
+ public static readonly DerObjectIdentifier DmdName = new DerObjectIdentifier("2.5.4.54");
+
+ /**
+ * id-at-telephoneNumber
+ */
+ public static readonly DerObjectIdentifier TelephoneNumber = X509ObjectIdentifiers.id_at_telephoneNumber;
+
+ /**
+ * id-at-organizationIdentifier
+ */
+ public static readonly DerObjectIdentifier OrganizationIdentifier = X509ObjectIdentifiers.id_at_organizationIdentifier;
+
+ /**
+ * id-at-name
+ */
+ public static readonly DerObjectIdentifier Name = X509ObjectIdentifiers.id_at_name;
+
+ /**
+ * Email address (RSA PKCS#9 extension) - IA5String.
+ *
Note: if you're trying to be ultra orthodox, don't use this! It shouldn't be in here.
+ */
+ public static readonly DerObjectIdentifier EmailAddress = PkcsObjectIdentifiers.Pkcs9AtEmailAddress;
+
+ /**
+ * more from PKCS#9
+ */
+ public static readonly DerObjectIdentifier UnstructuredName = PkcsObjectIdentifiers.Pkcs9AtUnstructuredName;
+ public static readonly DerObjectIdentifier UnstructuredAddress = PkcsObjectIdentifiers.Pkcs9AtUnstructuredAddress;
+
+ /**
+ * email address in Verisign certificates
+ */
+ public static readonly DerObjectIdentifier E = EmailAddress;
+
+ /*
+ * others...
+ */
+ public static readonly DerObjectIdentifier DC = new DerObjectIdentifier("0.9.2342.19200300.100.1.25");
+
+ /**
+ * LDAP User id.
+ */
+ public static readonly DerObjectIdentifier UID = new DerObjectIdentifier("0.9.2342.19200300.100.1.1");
+
+ /**
+ * determines whether or not strings should be processed and printed
+ * from back to front.
+ */
+// public static bool DefaultReverse = false;
+ public static bool DefaultReverse
+ {
+ get { return defaultReverse[0]; }
+ set { defaultReverse[0] = value; }
+ }
+
+ private static readonly bool[] defaultReverse = { false };
+
+#if SILVERLIGHT || PORTABLE || NETFX_CORE
+ /**
+ * default look up table translating OID values into their common symbols following
+ * the convention in RFC 2253 with a few extras
+ */
+ public static readonly IDictionary DefaultSymbols = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+
+ /**
+ * look up table translating OID values into their common symbols following the convention in RFC 2253
+ */
+ public static readonly IDictionary RFC2253Symbols = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+
+ /**
+ * look up table translating OID values into their common symbols following the convention in RFC 1779
+ *
+ */
+ public static readonly IDictionary RFC1779Symbols = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+
+ /**
+ * look up table translating common symbols into their OIDS.
+ */
+ public static readonly IDictionary DefaultLookup = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+#else
+ /**
+ * default look up table translating OID values into their common symbols following
+ * the convention in RFC 2253 with a few extras
+ */
+ public static readonly Hashtable DefaultSymbols = new Hashtable();
+
+ /**
+ * look up table translating OID values into their common symbols following the convention in RFC 2253
+ */
+ public static readonly Hashtable RFC2253Symbols = new Hashtable();
+
+ /**
+ * look up table translating OID values into their common symbols following the convention in RFC 1779
+ *
+ */
+ public static readonly Hashtable RFC1779Symbols = new Hashtable();
+
+ /**
+ * look up table translating common symbols into their OIDS.
+ */
+ public static readonly Hashtable DefaultLookup = new Hashtable();
+#endif
+
+ static X509Name()
+ {
+ DefaultSymbols.Add(C, "C");
+ DefaultSymbols.Add(O, "O");
+ DefaultSymbols.Add(T, "T");
+ DefaultSymbols.Add(OU, "OU");
+ DefaultSymbols.Add(CN, "CN");
+ DefaultSymbols.Add(L, "L");
+ DefaultSymbols.Add(ST, "ST");
+ DefaultSymbols.Add(SerialNumber, "SERIALNUMBER");
+ DefaultSymbols.Add(EmailAddress, "E");
+ DefaultSymbols.Add(DC, "DC");
+ DefaultSymbols.Add(UID, "UID");
+ DefaultSymbols.Add(Street, "STREET");
+ DefaultSymbols.Add(Surname, "SURNAME");
+ DefaultSymbols.Add(GivenName, "GIVENNAME");
+ DefaultSymbols.Add(Initials, "INITIALS");
+ DefaultSymbols.Add(Generation, "GENERATION");
+ DefaultSymbols.Add(UnstructuredAddress, "unstructuredAddress");
+ DefaultSymbols.Add(UnstructuredName, "unstructuredName");
+ DefaultSymbols.Add(UniqueIdentifier, "UniqueIdentifier");
+ DefaultSymbols.Add(DnQualifier, "DN");
+ DefaultSymbols.Add(Pseudonym, "Pseudonym");
+ DefaultSymbols.Add(PostalAddress, "PostalAddress");
+ DefaultSymbols.Add(NameAtBirth, "NameAtBirth");
+ DefaultSymbols.Add(CountryOfCitizenship, "CountryOfCitizenship");
+ DefaultSymbols.Add(CountryOfResidence, "CountryOfResidence");
+ DefaultSymbols.Add(Gender, "Gender");
+ DefaultSymbols.Add(PlaceOfBirth, "PlaceOfBirth");
+ DefaultSymbols.Add(DateOfBirth, "DateOfBirth");
+ DefaultSymbols.Add(PostalCode, "PostalCode");
+ DefaultSymbols.Add(BusinessCategory, "BusinessCategory");
+ DefaultSymbols.Add(TelephoneNumber, "TelephoneNumber");
+
+ RFC2253Symbols.Add(C, "C");
+ RFC2253Symbols.Add(O, "O");
+ RFC2253Symbols.Add(OU, "OU");
+ RFC2253Symbols.Add(CN, "CN");
+ RFC2253Symbols.Add(L, "L");
+ RFC2253Symbols.Add(ST, "ST");
+ RFC2253Symbols.Add(Street, "STREET");
+ RFC2253Symbols.Add(DC, "DC");
+ RFC2253Symbols.Add(UID, "UID");
+
+ RFC1779Symbols.Add(C, "C");
+ RFC1779Symbols.Add(O, "O");
+ RFC1779Symbols.Add(OU, "OU");
+ RFC1779Symbols.Add(CN, "CN");
+ RFC1779Symbols.Add(L, "L");
+ RFC1779Symbols.Add(ST, "ST");
+ RFC1779Symbols.Add(Street, "STREET");
+
+ DefaultLookup.Add("c", C);
+ DefaultLookup.Add("o", O);
+ DefaultLookup.Add("t", T);
+ DefaultLookup.Add("ou", OU);
+ DefaultLookup.Add("cn", CN);
+ DefaultLookup.Add("l", L);
+ DefaultLookup.Add("st", ST);
+ DefaultLookup.Add("serialnumber", SerialNumber);
+ DefaultLookup.Add("street", Street);
+ DefaultLookup.Add("emailaddress", E);
+ DefaultLookup.Add("dc", DC);
+ DefaultLookup.Add("e", E);
+ DefaultLookup.Add("uid", UID);
+ DefaultLookup.Add("surname", Surname);
+ DefaultLookup.Add("givenname", GivenName);
+ DefaultLookup.Add("initials", Initials);
+ DefaultLookup.Add("generation", Generation);
+ DefaultLookup.Add("unstructuredaddress", UnstructuredAddress);
+ DefaultLookup.Add("unstructuredname", UnstructuredName);
+ DefaultLookup.Add("uniqueidentifier", UniqueIdentifier);
+ DefaultLookup.Add("dn", DnQualifier);
+ DefaultLookup.Add("pseudonym", Pseudonym);
+ DefaultLookup.Add("postaladdress", PostalAddress);
+ DefaultLookup.Add("nameofbirth", NameAtBirth);
+ DefaultLookup.Add("countryofcitizenship", CountryOfCitizenship);
+ DefaultLookup.Add("countryofresidence", CountryOfResidence);
+ DefaultLookup.Add("gender", Gender);
+ DefaultLookup.Add("placeofbirth", PlaceOfBirth);
+ DefaultLookup.Add("dateofbirth", DateOfBirth);
+ DefaultLookup.Add("postalcode", PostalCode);
+ DefaultLookup.Add("businesscategory", BusinessCategory);
+ DefaultLookup.Add("telephonenumber", TelephoneNumber);
+ }
+
+ private readonly IList ordering = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ private readonly X509NameEntryConverter converter;
+
+ private IList values = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ private IList added = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ private Asn1Sequence seq;
+
+ /**
+ * Return a X509Name based on the passed in tagged object.
+ *
+ * @param obj tag object holding name.
+ * @param explicitly true if explicitly tagged false otherwise.
+ * @return the X509Name
+ */
+ public static X509Name GetInstance(
+ Asn1TaggedObject obj,
+ bool explicitly)
+ {
+ return GetInstance(Asn1Sequence.GetInstance(obj, explicitly));
+ }
+
+ public static X509Name GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is X509Name)
+ return (X509Name)obj;
+
+ if (obj != null)
+ return new X509Name(Asn1Sequence.GetInstance(obj));
+
+ throw new ArgumentException("null object in factory", "obj");
+ }
+
+ protected X509Name()
+ {
+ }
+
+ /**
+ * Constructor from Asn1Sequence
+ *
+ * the principal will be a list of constructed sets, each containing an (OID, string) pair.
+ */
+ protected X509Name(
+ Asn1Sequence seq)
+ {
+ this.seq = seq;
+
+ foreach (Asn1Encodable asn1Obj in seq)
+ {
+ Asn1Set asn1Set = Asn1Set.GetInstance(asn1Obj.ToAsn1Object());
+
+ for (int i = 0; i < asn1Set.Count; i++)
+ {
+ Asn1Sequence s = Asn1Sequence.GetInstance(asn1Set[i].ToAsn1Object());
+
+ if (s.Count != 2)
+ throw new ArgumentException("badly sized pair");
+
+ ordering.Add(DerObjectIdentifier.GetInstance(s[0].ToAsn1Object()));
+
+ Asn1Object derValue = s[1].ToAsn1Object();
+ if (derValue is IAsn1String && !(derValue is DerUniversalString))
+ {
+ string v = ((IAsn1String)derValue).GetString();
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(v, "#"))
+ {
+ v = "\\" + v;
+ }
+
+ values.Add(v);
+ }
+ else
+ {
+ values.Add("#" + Hex.ToHexString(derValue.GetEncoded()));
+ }
+
+ added.Add(i != 0);
+ }
+ }
+ }
+
+ /**
+ * Constructor from a table of attributes with ordering.
+ *
+ * it's is assumed the table contains OID/string pairs, and the contents
+ * of the table are copied into an internal table as part of the
+ * construction process. The ordering ArrayList should contain the OIDs
+ * in the order they are meant to be encoded or printed in ToString.
+ */
+ public X509Name(
+ IList ordering,
+ IDictionary attributes)
+ : this(ordering, attributes, new X509DefaultEntryConverter())
+ {
+ }
+
+ /**
+ * Constructor from a table of attributes with ordering.
+ *
+ * it's is assumed the table contains OID/string pairs, and the contents
+ * of the table are copied into an internal table as part of the
+ * construction process. The ordering ArrayList should contain the OIDs
+ * in the order they are meant to be encoded or printed in ToString.
+ *
+ * The passed in converter will be used to convert the strings into their
+ * ASN.1 counterparts.
+ */
+ public X509Name(
+ IList ordering,
+ IDictionary attributes,
+ X509NameEntryConverter converter)
+ {
+ this.converter = converter;
+
+ foreach (DerObjectIdentifier oid in ordering)
+ {
+ object attribute = attributes[oid];
+ if (attribute == null)
+ {
+ throw new ArgumentException("No attribute for object id - " + oid + " - passed to distinguished name");
+ }
+
+ this.ordering.Add(oid);
+ this.added.Add(false);
+ this.values.Add(attribute); // copy the hash table
+ }
+ }
+
+ /**
+ * Takes two vectors one of the oids and the other of the values.
+ */
+ public X509Name(
+ IList oids,
+ IList values)
+ : this(oids, values, new X509DefaultEntryConverter())
+ {
+ }
+
+ /**
+ * Takes two vectors one of the oids and the other of the values.
+ *
+ * The passed in converter will be used to convert the strings into their
+ * ASN.1 counterparts.
+ */
+ public X509Name(
+ IList oids,
+ IList values,
+ X509NameEntryConverter converter)
+ {
+ this.converter = converter;
+
+ if (oids.Count != values.Count)
+ {
+ throw new ArgumentException("'oids' must be same length as 'values'.");
+ }
+
+ for (int i = 0; i < oids.Count; i++)
+ {
+ this.ordering.Add(oids[i]);
+ this.values.Add(values[i]);
+ this.added.Add(false);
+ }
+ }
+
+ /**
+ * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
+ * some such, converting it into an ordered set of name attributes.
+ */
+ public X509Name(
+ string dirName)
+ : this(DefaultReverse, (IDictionary)DefaultLookup, dirName)
+ {
+ }
+
+ /**
+ * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
+ * some such, converting it into an ordered set of name attributes with each
+ * string value being converted to its associated ASN.1 type using the passed
+ * in converter.
+ */
+ public X509Name(
+ string dirName,
+ X509NameEntryConverter converter)
+ : this(DefaultReverse, DefaultLookup, dirName, converter)
+ {
+ }
+
+ /**
+ * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
+ * some such, converting it into an ordered set of name attributes. If reverse
+ * is true, create the encoded version of the sequence starting from the
+ * last element in the string.
+ */
+ public X509Name(
+ bool reverse,
+ string dirName)
+ : this(reverse, (IDictionary)DefaultLookup, dirName)
+ {
+ }
+
+ /**
+ * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
+ * some such, converting it into an ordered set of name attributes with each
+ * string value being converted to its associated ASN.1 type using the passed
+ * in converter. If reverse is true the ASN.1 sequence representing the DN will
+ * be built by starting at the end of the string, rather than the start.
+ */
+ public X509Name(
+ bool reverse,
+ string dirName,
+ X509NameEntryConverter converter)
+ : this(reverse, DefaultLookup, dirName, converter)
+ {
+ }
+
+ /**
+ * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
+ * some such, converting it into an ordered set of name attributes. lookUp
+ * should provide a table of lookups, indexed by lowercase only strings and
+ * yielding a DerObjectIdentifier, other than that OID. and numeric oids
+ * will be processed automatically.
+ *
+ * If reverse is true, create the encoded version of the sequence
+ * starting from the last element in the string.
+ * @param reverse true if we should start scanning from the end (RFC 2553).
+ * @param lookUp table of names and their oids.
+ * @param dirName the X.500 string to be parsed.
+ */
+ public X509Name(
+ bool reverse,
+ IDictionary lookUp,
+ string dirName)
+ : this(reverse, lookUp, dirName, new X509DefaultEntryConverter())
+ {
+ }
+
+ private DerObjectIdentifier DecodeOid(
+ string name,
+ IDictionary lookUp)
+ {
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(name), "OID."))
+ {
+ return new DerObjectIdentifier(name.Substring(4));
+ }
+ else if (name[0] >= '0' && name[0] <= '9')
+ {
+ return new DerObjectIdentifier(name);
+ }
+
+ DerObjectIdentifier oid = (DerObjectIdentifier)lookUp[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToLowerInvariant(name)];
+ if (oid == null)
+ {
+ throw new ArgumentException("Unknown object id - " + name + " - passed to distinguished name");
+ }
+
+ return oid;
+ }
+
+ /**
+ * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
+ * some such, converting it into an ordered set of name attributes. lookUp
+ * should provide a table of lookups, indexed by lowercase only strings and
+ * yielding a DerObjectIdentifier, other than that OID. and numeric oids
+ * will be processed automatically. The passed in converter is used to convert the
+ * string values to the right of each equals sign to their ASN.1 counterparts.
+ *
+ * @param reverse true if we should start scanning from the end, false otherwise.
+ * @param lookUp table of names and oids.
+ * @param dirName the string dirName
+ * @param converter the converter to convert string values into their ASN.1 equivalents
+ */
+ public X509Name(
+ bool reverse,
+ IDictionary lookUp,
+ string dirName,
+ X509NameEntryConverter converter)
+ {
+ this.converter = converter;
+ X509NameTokenizer nTok = new X509NameTokenizer(dirName);
+
+ while (nTok.HasMoreTokens())
+ {
+ string token = nTok.NextToken();
+ int index = token.IndexOf('=');
+
+ if (index == -1)
+ {
+ throw new ArgumentException("badly formated directory string");
+ }
+
+ string name = token.Substring(0, index);
+ string value = token.Substring(index + 1);
+ DerObjectIdentifier oid = DecodeOid(name, lookUp);
+
+ if (value.IndexOf('+') > 0)
+ {
+ X509NameTokenizer vTok = new X509NameTokenizer(value, '+');
+ string v = vTok.NextToken();
+
+ this.ordering.Add(oid);
+ this.values.Add(v);
+ this.added.Add(false);
+
+ while (vTok.HasMoreTokens())
+ {
+ string sv = vTok.NextToken();
+ int ndx = sv.IndexOf('=');
+
+ string nm = sv.Substring(0, ndx);
+ string vl = sv.Substring(ndx + 1);
+ this.ordering.Add(DecodeOid(nm, lookUp));
+ this.values.Add(vl);
+ this.added.Add(true);
+ }
+ }
+ else
+ {
+ this.ordering.Add(oid);
+ this.values.Add(value);
+ this.added.Add(false);
+ }
+ }
+
+ if (reverse)
+ {
+// this.ordering.Reverse();
+// this.values.Reverse();
+// this.added.Reverse();
+ IList o = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ IList v = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ IList a = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ int count = 1;
+
+ for (int i = 0; i < this.ordering.Count; i++)
+ {
+ if (!((bool) this.added[i]))
+ {
+ count = 0;
+ }
+
+ int index = count++;
+
+ o.Insert(index, this.ordering[i]);
+ v.Insert(index, this.values[i]);
+ a.Insert(index, this.added[i]);
+ }
+
+ this.ordering = o;
+ this.values = v;
+ this.added = a;
+ }
+ }
+
+ /**
+ * return an IList of the oids in the name, in the order they were found.
+ */
+ public IList GetOidList()
+ {
+ return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(ordering);
+ }
+
+ /**
+ * return an IList of the values found in the name, in the order they
+ * were found.
+ */
+ public IList GetValueList()
+ {
+ return GetValueList(null);
+ }
+
+ /**
+ * return an IList of the values found in the name, in the order they
+ * were found, with the DN label corresponding to passed in oid.
+ */
+ public IList GetValueList(DerObjectIdentifier oid)
+ {
+ IList v = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ for (int i = 0; i != values.Count; i++)
+ {
+ if (null == oid || oid.Equals(ordering[i]))
+ {
+ string val = (string)values[i];
+
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(val, "\\#"))
+ {
+ val = val.Substring(1);
+ }
+
+ v.Add(val);
+ }
+ }
+ return v;
+ }
+
+ public override Asn1Object ToAsn1Object()
+ {
+ if (seq == null)
+ {
+ Asn1EncodableVector vec = new Asn1EncodableVector();
+ Asn1EncodableVector sVec = new Asn1EncodableVector();
+ DerObjectIdentifier lstOid = null;
+
+ for (int i = 0; i != ordering.Count; i++)
+ {
+ DerObjectIdentifier oid = (DerObjectIdentifier)ordering[i];
+ string str = (string)values[i];
+
+ if (lstOid == null
+ || ((bool)this.added[i]))
+ {
+ }
+ else
+ {
+ vec.Add(new DerSet(sVec));
+ sVec = new Asn1EncodableVector();
+ }
+
+ sVec.Add(
+ new DerSequence(
+ oid,
+ converter.GetConvertedValue(oid, str)));
+
+ lstOid = oid;
+ }
+
+ vec.Add(new DerSet(sVec));
+
+ seq = new DerSequence(vec);
+ }
+
+ return seq;
+ }
+
+ /// The X509Name object to test equivalency against.
+ /// If true, the order of elements must be the same,
+ /// as well as the values associated with each element.
+ public bool Equivalent(
+ X509Name other,
+ bool inOrder)
+ {
+ if (!inOrder)
+ return this.Equivalent(other);
+
+ if (other == null)
+ return false;
+
+ if (other == this)
+ return true;
+
+ int orderingSize = ordering.Count;
+
+ if (orderingSize != other.ordering.Count)
+ return false;
+
+ for (int i = 0; i < orderingSize; i++)
+ {
+ DerObjectIdentifier oid = (DerObjectIdentifier) ordering[i];
+ DerObjectIdentifier oOid = (DerObjectIdentifier) other.ordering[i];
+
+ if (!oid.Equals(oOid))
+ return false;
+
+ string val = (string) values[i];
+ string oVal = (string) other.values[i];
+
+ if (!equivalentStrings(val, oVal))
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * test for equivalence - note: case is ignored.
+ */
+ public bool Equivalent(
+ X509Name other)
+ {
+ if (other == null)
+ return false;
+
+ if (other == this)
+ return true;
+
+ int orderingSize = ordering.Count;
+
+ if (orderingSize != other.ordering.Count)
+ {
+ return false;
+ }
+
+ bool[] indexes = new bool[orderingSize];
+ int start, end, delta;
+
+ if (ordering[0].Equals(other.ordering[0])) // guess forward
+ {
+ start = 0;
+ end = orderingSize;
+ delta = 1;
+ }
+ else // guess reversed - most common problem
+ {
+ start = orderingSize - 1;
+ end = -1;
+ delta = -1;
+ }
+
+ for (int i = start; i != end; i += delta)
+ {
+ bool found = false;
+ DerObjectIdentifier oid = (DerObjectIdentifier)ordering[i];
+ string value = (string)values[i];
+
+ for (int j = 0; j < orderingSize; j++)
+ {
+ if (indexes[j])
+ {
+ continue;
+ }
+
+ DerObjectIdentifier oOid = (DerObjectIdentifier)other.ordering[j];
+
+ if (oid.Equals(oOid))
+ {
+ string oValue = (string)other.values[j];
+
+ if (equivalentStrings(value, oValue))
+ {
+ indexes[j] = true;
+ found = true;
+ break;
+ }
+ }
+ }
+
+ if (!found)
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private static bool equivalentStrings(
+ string s1,
+ string s2)
+ {
+ string v1 = canonicalize(s1);
+ string v2 = canonicalize(s2);
+
+ if (!v1.Equals(v2))
+ {
+ v1 = stripInternalSpaces(v1);
+ v2 = stripInternalSpaces(v2);
+
+ if (!v1.Equals(v2))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private static string canonicalize(
+ string s)
+ {
+ string v = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToLowerInvariant(s).Trim();
+
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(v, "#"))
+ {
+ Asn1Object obj = decodeObject(v);
+
+ if (obj is IAsn1String)
+ {
+ v = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToLowerInvariant(((IAsn1String)obj).GetString()).Trim();
+ }
+ }
+
+ return v;
+ }
+
+ private static Asn1Object decodeObject(
+ string v)
+ {
+ try
+ {
+ return Asn1Object.FromByteArray(Hex.Decode(v.Substring(1)));
+ }
+ catch (IOException e)
+ {
+ throw new InvalidOperationException("unknown encoding in name: " + e.Message, e);
+ }
+ }
+
+ private static string stripInternalSpaces(
+ string str)
+ {
+ StringBuilder res = new StringBuilder();
+
+ if (str.Length != 0)
+ {
+ char c1 = str[0];
+
+ res.Append(c1);
+
+ for (int k = 1; k < str.Length; k++)
+ {
+ char c2 = str[k];
+ if (!(c1 == ' ' && c2 == ' '))
+ {
+ res.Append(c2);
+ }
+ c1 = c2;
+ }
+ }
+
+ return res.ToString();
+ }
+
+ private void AppendValue(
+ StringBuilder buf,
+ IDictionary oidSymbols,
+ DerObjectIdentifier oid,
+ string val)
+ {
+ string sym = (string)oidSymbols[oid];
+
+ if (sym != null)
+ {
+ buf.Append(sym);
+ }
+ else
+ {
+ buf.Append(oid.Id);
+ }
+
+ buf.Append('=');
+
+ int index = buf.Length;
+
+ buf.Append(val);
+
+ int end = buf.Length;
+
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(val, "\\#"))
+ {
+ index += 2;
+ }
+
+ while (index != end)
+ {
+ if ((buf[index] == ',')
+ || (buf[index] == '"')
+ || (buf[index] == '\\')
+ || (buf[index] == '+')
+ || (buf[index] == '=')
+ || (buf[index] == '<')
+ || (buf[index] == '>')
+ || (buf[index] == ';'))
+ {
+ buf.Insert(index++, "\\");
+ end++;
+ }
+
+ index++;
+ }
+ }
+
+ /**
+ * convert the structure to a string - if reverse is true the
+ * oids and values are listed out starting with the last element
+ * in the sequence (ala RFC 2253), otherwise the string will begin
+ * with the first element of the structure. If no string definition
+ * for the oid is found in oidSymbols the string value of the oid is
+ * added. Two standard symbol tables are provided DefaultSymbols, and
+ * RFC2253Symbols as part of this class.
+ *
+ * @param reverse if true start at the end of the sequence and work back.
+ * @param oidSymbols look up table strings for oids.
+ */
+ public string ToString(
+ bool reverse,
+ IDictionary oidSymbols)
+ {
+#if SILVERLIGHT || PORTABLE || NETFX_CORE
+ List components = new List();
+#else
+ ArrayList components = new ArrayList();
+#endif
+
+ StringBuilder ava = null;
+
+ for (int i = 0; i < ordering.Count; i++)
+ {
+ if ((bool) added[i])
+ {
+ ava.Append('+');
+ AppendValue(ava, oidSymbols,
+ (DerObjectIdentifier)ordering[i],
+ (string)values[i]);
+ }
+ else
+ {
+ ava = new StringBuilder();
+ AppendValue(ava, oidSymbols,
+ (DerObjectIdentifier)ordering[i],
+ (string)values[i]);
+ components.Add(ava);
+ }
+ }
+
+ if (reverse)
+ {
+ components.Reverse();
+ }
+
+ StringBuilder buf = new StringBuilder();
+
+ if (components.Count > 0)
+ {
+ buf.Append(components[0].ToString());
+
+ for (int i = 1; i < components.Count; ++i)
+ {
+ buf.Append(',');
+ buf.Append(components[i].ToString());
+ }
+ }
+
+ return buf.ToString();
+ }
+
+ public override string ToString()
+ {
+ return ToString(DefaultReverse, (IDictionary)DefaultSymbols);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/X509Name.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/X509Name.cs.meta
new file mode 100644
index 00000000..e65200e0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/X509Name.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c09a00533763e16488d5e052d2be7956
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/X509NameEntryConverter.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/X509NameEntryConverter.cs
new file mode 100644
index 00000000..343240b0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/X509NameEntryConverter.cs
@@ -0,0 +1,93 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Globalization;
+using System.IO;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509
+{
+ /**
+ * It turns out that the number of standard ways the fields in a DN should be
+ * encoded into their ASN.1 counterparts is rapidly approaching the
+ * number of machines on the internet. By default the X509Name class
+ * will produce UTF8Strings in line with the current recommendations (RFC 3280).
+ *
+ * Iso4217CurrencyCode ::= CHOICE {
+ * alphabetic PrintableString (SIZE 3), --Recommended
+ * numeric INTEGER (1..999) }
+ * -- Alphabetic or numeric currency code as defined in ISO 4217
+ * -- It is recommended that the Alphabetic form is used
+ *
+ */
+ public class Iso4217CurrencyCode
+ : Asn1Encodable, IAsn1Choice
+ {
+ internal const int AlphabeticMaxSize = 3;
+ internal const int NumericMinSize = 1;
+ internal const int NumericMaxSize = 999;
+
+ internal Asn1Encodable obj;
+// internal int numeric;
+
+ public static Iso4217CurrencyCode GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is Iso4217CurrencyCode)
+ {
+ return (Iso4217CurrencyCode) obj;
+ }
+
+ if (obj is DerInteger)
+ {
+ DerInteger numericobj = DerInteger.GetInstance(obj);
+ int numeric = numericobj.Value.IntValue;
+ return new Iso4217CurrencyCode(numeric);
+ }
+
+ if (obj is DerPrintableString)
+ {
+ DerPrintableString alphabetic = DerPrintableString.GetInstance(obj);
+ return new Iso4217CurrencyCode(alphabetic.GetString());
+ }
+
+ throw new ArgumentException("unknown object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+ }
+
+ public Iso4217CurrencyCode(
+ int numeric)
+ {
+ if (numeric > NumericMaxSize || numeric < NumericMinSize)
+ {
+ throw new ArgumentException("wrong size in numeric code : not in (" + NumericMinSize + ".." + NumericMaxSize + ")");
+ }
+
+ obj = new DerInteger(numeric);
+ }
+
+ public Iso4217CurrencyCode(
+ string alphabetic)
+ {
+ if (alphabetic.Length > AlphabeticMaxSize)
+ {
+ throw new ArgumentException("wrong size in alphabetic code : max size is " + AlphabeticMaxSize);
+ }
+
+ obj = new DerPrintableString(alphabetic);
+ }
+
+ public bool IsAlphabetic { get { return obj is DerPrintableString; } }
+
+ public string Alphabetic { get { return ((DerPrintableString) obj).GetString(); } }
+
+ public int Numeric { get { return ((DerInteger)obj).Value.IntValue; } }
+
+ public override Asn1Object ToAsn1Object()
+ {
+ return obj.ToAsn1Object();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/qualified/Iso4217CurrencyCode.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/qualified/Iso4217CurrencyCode.cs.meta
new file mode 100644
index 00000000..6f654ebe
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/qualified/Iso4217CurrencyCode.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c7ad8cb705970a4409c018bb003ee423
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/qualified/MonetaryValue.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/qualified/MonetaryValue.cs
new file mode 100644
index 00000000..9ce3b118
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x509/qualified/MonetaryValue.cs
@@ -0,0 +1,87 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509.Qualified
+{
+ /**
+ * The MonetaryValue object.
+ *
+ * Octet string produced using ECPoint.GetEncoded().
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ return encoding;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x9/X9ECPoint.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x9/X9ECPoint.cs.meta
new file mode 100644
index 00000000..1fdf979e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x9/X9ECPoint.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 7836651622621b946bda8dac7d8d97e8
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x9/X9FieldElement.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x9/X9FieldElement.cs
new file mode 100644
index 00000000..e99c877f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x9/X9FieldElement.cs
@@ -0,0 +1,75 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9
+{
+ /**
+ * Class for processing an ECFieldElement as a DER object.
+ */
+ public class X9FieldElement
+ : Asn1Encodable
+ {
+ private ECFieldElement f;
+
+ public X9FieldElement(
+ ECFieldElement f)
+ {
+ this.f = f;
+ }
+
+ [Obsolete("Will be removed")]
+ public X9FieldElement(
+ BigInteger p,
+ Asn1OctetString s)
+ : this(new FpFieldElement(p, new BigInteger(1, s.GetOctets())))
+ {
+ }
+
+ [Obsolete("Will be removed")]
+ public X9FieldElement(
+ int m,
+ int k1,
+ int k2,
+ int k3,
+ Asn1OctetString s)
+ : this(new F2mFieldElement(m, k1, k2, k3, new BigInteger(1, s.GetOctets())))
+ {
+ }
+
+ public ECFieldElement Value
+ {
+ get { return f; }
+ }
+
+ /**
+ * Produce an object suitable for an Asn1OutputStream.
+ *
+ * FieldElement ::= OCTET STRING
+ *
+ *
+ *
+ *
if q is an odd prime then the field element is
+ * processed as an Integer and converted to an octet string
+ * according to x 9.62 4.3.1.
+ *
if q is 2m then the bit string
+ * contained in the field element is converted into an octet
+ * string with the same ordering padded at the front if necessary.
+ *
+ *
+ *
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ int byteCount = X9IntegerConverter.GetByteLength(f);
+ byte[] paddedBigInteger = X9IntegerConverter.IntegerToBytes(f.ToBigInteger(), byteCount);
+
+ return new DerOctetString(paddedBigInteger);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x9/X9FieldElement.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x9/X9FieldElement.cs.meta
new file mode 100644
index 00000000..1902c9bd
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x9/X9FieldElement.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: f9abf4b8380cc5f4fae08ae4356c3729
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x9/X9FieldID.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x9/X9FieldID.cs
new file mode 100644
index 00000000..d58dc5c0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/asn1/x9/X9FieldID.cs
@@ -0,0 +1,136 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9
+{
+ /**
+ * ASN.1 def for Elliptic-Curve Field ID structure. See
+ * X9.62, for further details.
+ */
+ public class X9FieldID
+ : Asn1Encodable
+ {
+ private readonly DerObjectIdentifier id;
+ private readonly Asn1Object parameters;
+
+ /**
+ * Constructor for elliptic curves over prime fields
+ * F2.
+ * @param primeP The prime p defining the prime field.
+ */
+ public X9FieldID(
+ BigInteger primeP)
+ {
+ this.id = X9ObjectIdentifiers.PrimeField;
+ this.parameters = new DerInteger(primeP);
+ }
+
+ /**
+ * Constructor for elliptic curves over binary fields
+ * F2m.
+ * @param m The exponent m of
+ * F2m.
+ * @param k1 The integer k1 where xm +
+ * xk1 + 1
+ * represents the reduction polynomial f(z).
+ */
+ public X9FieldID(int m, int k1)
+ : this(m, k1, 0, 0)
+ {
+ }
+
+ /**
+ * Constructor for elliptic curves over binary fields
+ * F2m.
+ * @param m The exponent m of
+ * F2m.
+ * @param k1 The integer k1 where xm +
+ * xk3 + xk2 + xk1 + 1
+ * represents the reduction polynomial f(z).
+ * @param k2 The integer k2 where xm +
+ * xk3 + xk2 + xk1 + 1
+ * represents the reduction polynomial f(z).
+ * @param k3 The integer k3 where xm +
+ * xk3 + xk2 + xk1 + 1
+ * represents the reduction polynomial f(z)..
+ */
+ public X9FieldID(
+ int m,
+ int k1,
+ int k2,
+ int k3)
+ {
+ this.id = X9ObjectIdentifiers.CharacteristicTwoField;
+
+ Asn1EncodableVector fieldIdParams = new Asn1EncodableVector(new DerInteger(m));
+
+ if (k2 == 0)
+ {
+ if (k3 != 0)
+ throw new ArgumentException("inconsistent k values");
+
+ fieldIdParams.Add(
+ X9ObjectIdentifiers.TPBasis,
+ new DerInteger(k1));
+ }
+ else
+ {
+ if (k2 <= k1 || k3 <= k2)
+ throw new ArgumentException("inconsistent k values");
+
+ fieldIdParams.Add(
+ X9ObjectIdentifiers.PPBasis,
+ new DerSequence(
+ new DerInteger(k1),
+ new DerInteger(k2),
+ new DerInteger(k3)));
+ }
+
+ this.parameters = new DerSequence(fieldIdParams);
+ }
+
+ private X9FieldID(Asn1Sequence seq)
+ {
+ this.id = DerObjectIdentifier.GetInstance(seq[0]);
+ this.parameters = seq[1].ToAsn1Object();
+ }
+
+ public static X9FieldID GetInstance(object obj)
+ {
+ if (obj is X9FieldID)
+ return (X9FieldID)obj;
+ if (obj == null)
+ return null;
+ return new X9FieldID(Asn1Sequence.GetInstance(obj));
+ }
+
+ public DerObjectIdentifier Identifier
+ {
+ get { return id; }
+ }
+
+ public Asn1Object Parameters
+ {
+ get { return parameters; }
+ }
+
+ /**
+ * Produce a Der encoding of the following structure.
+ *
+ */
+ public class CmsAuthenticatedDataGenerator
+ : CmsAuthenticatedGenerator
+ {
+ /**
+ * base constructor
+ */
+ public CmsAuthenticatedDataGenerator()
+ {
+ }
+
+ /**
+ * constructor allowing specific source of randomness
+ * @param rand instance of SecureRandom to use
+ */
+ public CmsAuthenticatedDataGenerator(
+ SecureRandom rand)
+ : base(rand)
+ {
+ }
+
+ /**
+ * generate an enveloped object that contains an CMS Enveloped Data
+ * object using the given provider and the passed in key generator.
+ */
+ private CmsAuthenticatedData Generate(
+ CmsProcessable content,
+ string macOid,
+ CipherKeyGenerator keyGen)
+ {
+ AlgorithmIdentifier macAlgId;
+ KeyParameter encKey;
+ Asn1OctetString encContent;
+ Asn1OctetString macResult;
+
+ try
+ {
+ // FIXME Will this work for macs?
+ byte[] encKeyBytes = keyGen.GenerateKey();
+ encKey = ParameterUtilities.CreateKeyParameter(macOid, encKeyBytes);
+
+ Asn1Encodable asn1Params = GenerateAsn1Parameters(macOid, encKeyBytes);
+
+ ICipherParameters cipherParameters;
+ macAlgId = GetAlgorithmIdentifier(
+ macOid, encKey, asn1Params, out cipherParameters);
+
+ IMac mac = MacUtilities.GetMac(macOid);
+ // TODO Confirm no ParametersWithRandom needed
+ // FIXME Only passing key at the moment
+// mac.Init(cipherParameters);
+ mac.Init(encKey);
+
+ MemoryStream bOut = new MemoryStream();
+ Stream mOut = new TeeOutputStream(bOut, new MacSink(mac));
+
+ content.Write(mOut);
+
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(mOut);
+
+ encContent = new BerOctetString(bOut.ToArray());
+
+ byte[] macOctets = MacUtilities.DoFinal(mac);
+ macResult = new DerOctetString(macOctets);
+ }
+ catch (SecurityUtilityException e)
+ {
+ throw new CmsException("couldn't create cipher.", e);
+ }
+ catch (InvalidKeyException e)
+ {
+ throw new CmsException("key invalid in message.", e);
+ }
+ catch (IOException e)
+ {
+ throw new CmsException("exception decoding algorithm parameters.", e);
+ }
+
+ Asn1EncodableVector recipientInfos = new Asn1EncodableVector();
+
+ foreach (RecipientInfoGenerator rig in recipientInfoGenerators)
+ {
+ try
+ {
+ recipientInfos.Add(rig.Generate(encKey, rand));
+ }
+ catch (InvalidKeyException e)
+ {
+ throw new CmsException("key inappropriate for algorithm.", e);
+ }
+ catch (GeneralSecurityException e)
+ {
+ throw new CmsException("error making encrypted content.", e);
+ }
+ }
+
+ ContentInfo eci = new ContentInfo(CmsObjectIdentifiers.Data, encContent);
+
+ ContentInfo contentInfo = new ContentInfo(
+ CmsObjectIdentifiers.AuthenticatedData,
+ new AuthenticatedData(null, new DerSet(recipientInfos), macAlgId, null, eci, null, macResult, null));
+
+ return new CmsAuthenticatedData(contentInfo);
+ }
+
+ /**
+ * generate an authenticated object that contains an CMS Authenticated Data object
+ */
+ public CmsAuthenticatedData Generate(
+ CmsProcessable content,
+ string encryptionOid)
+ {
+ try
+ {
+ // FIXME Will this work for macs?
+ CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid);
+
+ keyGen.Init(new KeyGenerationParameters(rand, keyGen.DefaultStrength));
+
+ return Generate(content, encryptionOid, keyGen);
+ }
+ catch (SecurityUtilityException e)
+ {
+ throw new CmsException("can't find key generation algorithm.", e);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSAuthenticatedDataGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSAuthenticatedDataGenerator.cs.meta
new file mode 100644
index 00000000..b9390d76
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSAuthenticatedDataGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 5a8b41fa9a2f17b45ba2fd190514a66c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSAuthenticatedDataParser.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSAuthenticatedDataParser.cs
new file mode 100644
index 00000000..6198e343
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSAuthenticatedDataParser.cs
@@ -0,0 +1,218 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ /**
+ * Parsing class for an CMS Authenticated Data object from an input stream.
+ *
+ * Note: that because we are in a streaming mode only one recipient can be tried and it is important
+ * that the methods on the parser are called in the appropriate order.
+ *
+ *
+ * Example of use - assuming the first recipient matches the private key we have.
+ *
+ ///
+ public class CmsEnvelopedDataGenerator
+ : CmsEnvelopedGenerator
+ {
+ public CmsEnvelopedDataGenerator()
+ {
+ }
+
+ /// Constructor allowing specific source of randomness
+ /// Instance of SecureRandom to use.
+ public CmsEnvelopedDataGenerator(
+ SecureRandom rand)
+ : base(rand)
+ {
+ }
+
+ ///
+ /// Generate an enveloped object that contains a CMS Enveloped Data
+ /// object using the passed in key generator.
+ ///
+ private CmsEnvelopedData Generate(
+ CmsProcessable content,
+ string encryptionOid,
+ CipherKeyGenerator keyGen)
+ {
+ AlgorithmIdentifier encAlgId = null;
+ KeyParameter encKey;
+ Asn1OctetString encContent;
+
+ try
+ {
+ byte[] encKeyBytes = keyGen.GenerateKey();
+ encKey = ParameterUtilities.CreateKeyParameter(encryptionOid, encKeyBytes);
+
+ Asn1Encodable asn1Params = GenerateAsn1Parameters(encryptionOid, encKeyBytes);
+
+ ICipherParameters cipherParameters;
+ encAlgId = GetAlgorithmIdentifier(
+ encryptionOid, encKey, asn1Params, out cipherParameters);
+
+ IBufferedCipher cipher = CipherUtilities.GetCipher(encryptionOid);
+ cipher.Init(true, new ParametersWithRandom(cipherParameters, rand));
+
+ MemoryStream bOut = new MemoryStream();
+ CipherStream cOut = new CipherStream(bOut, null, cipher);
+
+ content.Write(cOut);
+
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(cOut);
+
+ encContent = new BerOctetString(bOut.ToArray());
+ }
+ catch (SecurityUtilityException e)
+ {
+ throw new CmsException("couldn't create cipher.", e);
+ }
+ catch (InvalidKeyException e)
+ {
+ throw new CmsException("key invalid in message.", e);
+ }
+ catch (IOException e)
+ {
+ throw new CmsException("exception decoding algorithm parameters.", e);
+ }
+
+
+ Asn1EncodableVector recipientInfos = new Asn1EncodableVector();
+
+ foreach (RecipientInfoGenerator rig in recipientInfoGenerators)
+ {
+ try
+ {
+ recipientInfos.Add(rig.Generate(encKey, rand));
+ }
+ catch (InvalidKeyException e)
+ {
+ throw new CmsException("key inappropriate for algorithm.", e);
+ }
+ catch (GeneralSecurityException e)
+ {
+ throw new CmsException("error making encrypted content.", e);
+ }
+ }
+
+ EncryptedContentInfo eci = new EncryptedContentInfo(
+ CmsObjectIdentifiers.Data,
+ encAlgId,
+ encContent);
+
+ Asn1Set unprotectedAttrSet = null;
+ if (unprotectedAttributeGenerator != null)
+ {
+ Asn1.Cms.AttributeTable attrTable = unprotectedAttributeGenerator.GetAttributes(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable());
+
+ unprotectedAttrSet = new BerSet(attrTable.ToAsn1EncodableVector());
+ }
+
+ ContentInfo contentInfo = new ContentInfo(
+ CmsObjectIdentifiers.EnvelopedData,
+ new EnvelopedData(null, new DerSet(recipientInfos), eci, unprotectedAttrSet));
+
+ return new CmsEnvelopedData(contentInfo);
+ }
+
+ /// Generate an enveloped object that contains an CMS Enveloped Data object.
+ public CmsEnvelopedData Generate(
+ CmsProcessable content,
+ string encryptionOid)
+ {
+ try
+ {
+ CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid);
+
+ keyGen.Init(new KeyGenerationParameters(rand, keyGen.DefaultStrength));
+
+ return Generate(content, encryptionOid, keyGen);
+ }
+ catch (SecurityUtilityException e)
+ {
+ throw new CmsException("can't find key generation algorithm.", e);
+ }
+ }
+
+ /// Generate an enveloped object that contains an CMS Enveloped Data object.
+ public CmsEnvelopedData Generate(
+ CmsProcessable content,
+ string encryptionOid,
+ int keySize)
+ {
+ try
+ {
+ CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid);
+
+ keyGen.Init(new KeyGenerationParameters(rand, keySize));
+
+ return Generate(content, encryptionOid, keyGen);
+ }
+ catch (SecurityUtilityException e)
+ {
+ throw new CmsException("can't find key generation algorithm.", e);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSEnvelopedDataGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSEnvelopedDataGenerator.cs.meta
new file mode 100644
index 00000000..acbbe221
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSEnvelopedDataGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: aa4d4e34c5881f74ca33adf98582b07c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSEnvelopedDataParser.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSEnvelopedDataParser.cs
new file mode 100644
index 00000000..57fcc7bc
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSEnvelopedDataParser.cs
@@ -0,0 +1,165 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ /**
+ * Parsing class for an CMS Enveloped Data object from an input stream.
+ *
+ * Note: that because we are in a streaming mode only one recipient can be tried and it is important
+ * that the methods on the parser are called in the appropriate order.
+ *
+ *
+ * Example of use - assuming the first recipient matches the private key we have.
+ *
+ *
+ */
+ public class CmsSignedDataGenerator
+ : CmsSignedGenerator
+ {
+ private static readonly CmsSignedHelper Helper = CmsSignedHelper.Instance;
+
+ private readonly IList signerInfs = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+
+ private class SignerInf
+ {
+ private readonly CmsSignedGenerator outer;
+
+ private readonly ISignatureFactory sigCalc;
+ private readonly SignerIdentifier signerIdentifier;
+ private readonly string digestOID;
+ private readonly string encOID;
+ private readonly CmsAttributeTableGenerator sAttr;
+ private readonly CmsAttributeTableGenerator unsAttr;
+ private readonly Asn1.Cms.AttributeTable baseSignedTable;
+
+ internal SignerInf(
+ CmsSignedGenerator outer,
+ AsymmetricKeyParameter key,
+ SignerIdentifier signerIdentifier,
+ string digestOID,
+ string encOID,
+ CmsAttributeTableGenerator sAttr,
+ CmsAttributeTableGenerator unsAttr,
+ Asn1.Cms.AttributeTable baseSignedTable)
+ {
+ string digestName = Helper.GetDigestAlgName(digestOID);
+
+ string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID);
+
+ this.outer = outer;
+ this.sigCalc = new Asn1SignatureFactory(signatureName, key);
+ this.signerIdentifier = signerIdentifier;
+ this.digestOID = digestOID;
+ this.encOID = encOID;
+ this.sAttr = sAttr;
+ this.unsAttr = unsAttr;
+ this.baseSignedTable = baseSignedTable;
+ }
+
+ internal SignerInf(
+ CmsSignedGenerator outer,
+ ISignatureFactory sigCalc,
+ SignerIdentifier signerIdentifier,
+ CmsAttributeTableGenerator sAttr,
+ CmsAttributeTableGenerator unsAttr,
+ Asn1.Cms.AttributeTable baseSignedTable)
+ {
+ this.outer = outer;
+ this.sigCalc = sigCalc;
+ this.signerIdentifier = signerIdentifier;
+ this.digestOID = new DefaultDigestAlgorithmIdentifierFinder().find((AlgorithmIdentifier)sigCalc.AlgorithmDetails).Algorithm.Id;
+ this.encOID = ((AlgorithmIdentifier)sigCalc.AlgorithmDetails).Algorithm.Id;
+ this.sAttr = sAttr;
+ this.unsAttr = unsAttr;
+ this.baseSignedTable = baseSignedTable;
+ }
+
+ internal AlgorithmIdentifier DigestAlgorithmID
+ {
+ get { return new AlgorithmIdentifier(new DerObjectIdentifier(digestOID), DerNull.Instance); }
+ }
+
+ internal CmsAttributeTableGenerator SignedAttributes
+ {
+ get { return sAttr; }
+ }
+
+ internal CmsAttributeTableGenerator UnsignedAttributes
+ {
+ get { return unsAttr; }
+ }
+
+ internal SignerInfo ToSignerInfo(
+ DerObjectIdentifier contentType,
+ CmsProcessable content,
+ SecureRandom random)
+ {
+ AlgorithmIdentifier digAlgId = DigestAlgorithmID;
+ string digestName = Helper.GetDigestAlgName(digestOID);
+
+ string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID);
+
+ byte[] hash;
+ if (outer._digests.Contains(digestOID))
+ {
+ hash = (byte[])outer._digests[digestOID];
+ }
+ else
+ {
+ IDigest dig = Helper.GetDigestInstance(digestName);
+ if (content != null)
+ {
+ content.Write(new DigestSink(dig));
+ }
+ hash = DigestUtilities.DoFinal(dig);
+ outer._digests.Add(digestOID, hash.Clone());
+ }
+
+ IStreamCalculator calculator = sigCalc.CreateCalculator();
+
+#if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE
+ Stream sigStr = calculator.Stream;
+#else
+ Stream sigStr = new BufferedStream(calculator.Stream);
+#endif
+
+ Asn1Set signedAttr = null;
+ if (sAttr != null)
+ {
+ IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash);
+
+// Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(Collections.unmodifiableMap(parameters));
+ Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(parameters);
+
+ if (contentType == null) //counter signature
+ {
+ if (signed != null && signed[CmsAttributes.ContentType] != null)
+ {
+ IDictionary tmpSigned = signed.ToDictionary();
+ tmpSigned.Remove(CmsAttributes.ContentType);
+ signed = new Asn1.Cms.AttributeTable(tmpSigned);
+ }
+ }
+
+ // TODO Validate proposed signed attributes
+
+ signedAttr = outer.GetAttributeSet(signed);
+
+ // sig must be composed from the DER encoding.
+ new DerOutputStream(sigStr).WriteObject(signedAttr);
+ }
+ else if (content != null)
+ {
+ // TODO Use raw signature of the hash value instead
+ content.Write(sigStr);
+ }
+
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(sigStr);
+ byte[] sigBytes = ((IBlockResult)calculator.GetResult()).Collect();
+
+ Asn1Set unsignedAttr = null;
+ if (unsAttr != null)
+ {
+ IDictionary baseParameters = outer.GetBaseParameters(contentType, digAlgId, hash);
+ baseParameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone();
+
+// Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(Collections.unmodifiableMap(baseParameters));
+ Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(baseParameters);
+
+ // TODO Validate proposed unsigned attributes
+
+ unsignedAttr = outer.GetAttributeSet(unsigned);
+ }
+
+ // TODO[RSAPSS] Need the ability to specify non-default parameters
+ Asn1Encodable sigX509Parameters = SignerUtilities.GetDefaultX509Parameters(signatureName);
+ AlgorithmIdentifier encAlgId = Helper.GetEncAlgorithmIdentifier(
+ new DerObjectIdentifier(encOID), sigX509Parameters);
+
+ return new SignerInfo(signerIdentifier, digAlgId,
+ signedAttr, encAlgId, new DerOctetString(sigBytes), unsignedAttr);
+ }
+ }
+
+ public CmsSignedDataGenerator()
+ {
+ }
+
+ /// Constructor allowing specific source of randomness
+ /// Instance of SecureRandom to use.
+ public CmsSignedDataGenerator(
+ SecureRandom rand)
+ : base(rand)
+ {
+ }
+
+ /**
+ * add a signer - no attributes other than the default ones will be
+ * provided here.
+ *
+ * @param key signing key to use
+ * @param cert certificate containing corresponding public key
+ * @param digestOID digest algorithm OID
+ */
+ public void AddSigner(
+ AsymmetricKeyParameter privateKey,
+ X509Certificate cert,
+ string digestOID)
+ {
+ AddSigner(privateKey, cert, Helper.GetEncOid(privateKey, digestOID), digestOID);
+ }
+
+ /**
+ * add a signer, specifying the digest encryption algorithm to use - no attributes other than the default ones will be
+ * provided here.
+ *
+ * @param key signing key to use
+ * @param cert certificate containing corresponding public key
+ * @param encryptionOID digest encryption algorithm OID
+ * @param digestOID digest algorithm OID
+ */
+ public void AddSigner(
+ AsymmetricKeyParameter privateKey,
+ X509Certificate cert,
+ string encryptionOID,
+ string digestOID)
+ {
+ doAddSigner(privateKey, GetSignerIdentifier(cert), encryptionOID, digestOID,
+ new DefaultSignedAttributeTableGenerator(), null, null);
+ }
+
+ /**
+ * add a signer - no attributes other than the default ones will be
+ * provided here.
+ */
+ public void AddSigner(
+ AsymmetricKeyParameter privateKey,
+ byte[] subjectKeyID,
+ string digestOID)
+ {
+ AddSigner(privateKey, subjectKeyID, Helper.GetEncOid(privateKey, digestOID), digestOID);
+ }
+
+ /**
+ * add a signer, specifying the digest encryption algorithm to use - no attributes other than the default ones will be
+ * provided here.
+ */
+ public void AddSigner(
+ AsymmetricKeyParameter privateKey,
+ byte[] subjectKeyID,
+ string encryptionOID,
+ string digestOID)
+ {
+ doAddSigner(privateKey, GetSignerIdentifier(subjectKeyID), encryptionOID, digestOID,
+ new DefaultSignedAttributeTableGenerator(), null, null);
+ }
+
+ /**
+ * add a signer with extra signed/unsigned attributes.
+ *
+ * @param key signing key to use
+ * @param cert certificate containing corresponding public key
+ * @param digestOID digest algorithm OID
+ * @param signedAttr table of attributes to be included in signature
+ * @param unsignedAttr table of attributes to be included as unsigned
+ */
+ public void AddSigner(
+ AsymmetricKeyParameter privateKey,
+ X509Certificate cert,
+ string digestOID,
+ Asn1.Cms.AttributeTable signedAttr,
+ Asn1.Cms.AttributeTable unsignedAttr)
+ {
+ AddSigner(privateKey, cert, Helper.GetEncOid(privateKey, digestOID), digestOID,
+ signedAttr, unsignedAttr);
+ }
+
+ /**
+ * add a signer, specifying the digest encryption algorithm, with extra signed/unsigned attributes.
+ *
+ * @param key signing key to use
+ * @param cert certificate containing corresponding public key
+ * @param encryptionOID digest encryption algorithm OID
+ * @param digestOID digest algorithm OID
+ * @param signedAttr table of attributes to be included in signature
+ * @param unsignedAttr table of attributes to be included as unsigned
+ */
+ public void AddSigner(
+ AsymmetricKeyParameter privateKey,
+ X509Certificate cert,
+ string encryptionOID,
+ string digestOID,
+ Asn1.Cms.AttributeTable signedAttr,
+ Asn1.Cms.AttributeTable unsignedAttr)
+ {
+ doAddSigner(privateKey, GetSignerIdentifier(cert), encryptionOID, digestOID,
+ new DefaultSignedAttributeTableGenerator(signedAttr),
+ new SimpleAttributeTableGenerator(unsignedAttr),
+ signedAttr);
+ }
+
+ /**
+ * add a signer with extra signed/unsigned attributes.
+ *
+ * @param key signing key to use
+ * @param subjectKeyID subjectKeyID of corresponding public key
+ * @param digestOID digest algorithm OID
+ * @param signedAttr table of attributes to be included in signature
+ * @param unsignedAttr table of attributes to be included as unsigned
+ */
+ public void AddSigner(
+ AsymmetricKeyParameter privateKey,
+ byte[] subjectKeyID,
+ string digestOID,
+ Asn1.Cms.AttributeTable signedAttr,
+ Asn1.Cms.AttributeTable unsignedAttr)
+ {
+ AddSigner(privateKey, subjectKeyID, Helper.GetEncOid(privateKey, digestOID), digestOID,
+ signedAttr, unsignedAttr);
+ }
+
+ /**
+ * add a signer, specifying the digest encryption algorithm, with extra signed/unsigned attributes.
+ *
+ * @param key signing key to use
+ * @param subjectKeyID subjectKeyID of corresponding public key
+ * @param encryptionOID digest encryption algorithm OID
+ * @param digestOID digest algorithm OID
+ * @param signedAttr table of attributes to be included in signature
+ * @param unsignedAttr table of attributes to be included as unsigned
+ */
+ public void AddSigner(
+ AsymmetricKeyParameter privateKey,
+ byte[] subjectKeyID,
+ string encryptionOID,
+ string digestOID,
+ Asn1.Cms.AttributeTable signedAttr,
+ Asn1.Cms.AttributeTable unsignedAttr)
+ {
+ doAddSigner(privateKey, GetSignerIdentifier(subjectKeyID), encryptionOID, digestOID,
+ new DefaultSignedAttributeTableGenerator(signedAttr),
+ new SimpleAttributeTableGenerator(unsignedAttr),
+ signedAttr);
+ }
+
+ /**
+ * add a signer with extra signed/unsigned attributes based on generators.
+ */
+ public void AddSigner(
+ AsymmetricKeyParameter privateKey,
+ X509Certificate cert,
+ string digestOID,
+ CmsAttributeTableGenerator signedAttrGen,
+ CmsAttributeTableGenerator unsignedAttrGen)
+ {
+ AddSigner(privateKey, cert, Helper.GetEncOid(privateKey, digestOID), digestOID,
+ signedAttrGen, unsignedAttrGen);
+ }
+
+ /**
+ * add a signer, specifying the digest encryption algorithm, with extra signed/unsigned attributes based on generators.
+ */
+ public void AddSigner(
+ AsymmetricKeyParameter privateKey,
+ X509Certificate cert,
+ string encryptionOID,
+ string digestOID,
+ CmsAttributeTableGenerator signedAttrGen,
+ CmsAttributeTableGenerator unsignedAttrGen)
+ {
+ doAddSigner(privateKey, GetSignerIdentifier(cert), encryptionOID, digestOID, signedAttrGen,
+ unsignedAttrGen, null);
+ }
+
+ /**
+ * add a signer with extra signed/unsigned attributes based on generators.
+ */
+ public void AddSigner(
+ AsymmetricKeyParameter privateKey,
+ byte[] subjectKeyID,
+ string digestOID,
+ CmsAttributeTableGenerator signedAttrGen,
+ CmsAttributeTableGenerator unsignedAttrGen)
+ {
+ AddSigner(privateKey, subjectKeyID, Helper.GetEncOid(privateKey, digestOID), digestOID,
+ signedAttrGen, unsignedAttrGen);
+ }
+
+ /**
+ * add a signer, including digest encryption algorithm, with extra signed/unsigned attributes based on generators.
+ */
+ public void AddSigner(
+ AsymmetricKeyParameter privateKey,
+ byte[] subjectKeyID,
+ string encryptionOID,
+ string digestOID,
+ CmsAttributeTableGenerator signedAttrGen,
+ CmsAttributeTableGenerator unsignedAttrGen)
+ {
+ doAddSigner(privateKey, GetSignerIdentifier(subjectKeyID), encryptionOID, digestOID,
+ signedAttrGen, unsignedAttrGen, null);
+ }
+
+ public void AddSignerInfoGenerator(SignerInfoGenerator signerInfoGenerator)
+ {
+ signerInfs.Add(new SignerInf(this, signerInfoGenerator.contentSigner, signerInfoGenerator.sigId,
+ signerInfoGenerator.signedGen, signerInfoGenerator.unsignedGen, null));
+ }
+
+ private void doAddSigner(
+ AsymmetricKeyParameter privateKey,
+ SignerIdentifier signerIdentifier,
+ string encryptionOID,
+ string digestOID,
+ CmsAttributeTableGenerator signedAttrGen,
+ CmsAttributeTableGenerator unsignedAttrGen,
+ Asn1.Cms.AttributeTable baseSignedTable)
+ {
+ signerInfs.Add(new SignerInf(this, privateKey, signerIdentifier, digestOID, encryptionOID,
+ signedAttrGen, unsignedAttrGen, baseSignedTable));
+ }
+
+ /**
+ * generate a signed object that for a CMS Signed Data object
+ */
+ public CmsSignedData Generate(
+ CmsProcessable content)
+ {
+ return Generate(content, false);
+ }
+
+ /**
+ * generate a signed object that for a CMS Signed Data
+ * object - if encapsulate is true a copy
+ * of the message will be included in the signature. The content type
+ * is set according to the OID represented by the string signedContentType.
+ */
+ public CmsSignedData Generate(
+ string signedContentType,
+ // FIXME Avoid accessing more than once to support CmsProcessableInputStream
+ CmsProcessable content,
+ bool encapsulate)
+ {
+ Asn1EncodableVector digestAlgs = new Asn1EncodableVector();
+ Asn1EncodableVector signerInfos = new Asn1EncodableVector();
+
+ _digests.Clear(); // clear the current preserved digest state
+
+ //
+ // add the precalculated SignerInfo objects.
+ //
+ foreach (SignerInformation signer in _signers)
+ {
+ digestAlgs.Add(Helper.FixAlgID(signer.DigestAlgorithmID));
+
+ // TODO Verify the content type and calculated digest match the precalculated SignerInfo
+ signerInfos.Add(signer.ToSignerInfo());
+ }
+
+ //
+ // add the SignerInfo objects
+ //
+ bool isCounterSignature = (signedContentType == null);
+
+ DerObjectIdentifier contentTypeOid = isCounterSignature
+ ? null
+ : new DerObjectIdentifier(signedContentType);
+
+ foreach (SignerInf signer in signerInfs)
+ {
+ try
+ {
+ digestAlgs.Add(signer.DigestAlgorithmID);
+ signerInfos.Add(signer.ToSignerInfo(contentTypeOid, content, rand));
+ }
+ catch (IOException e)
+ {
+ throw new CmsException("encoding error.", e);
+ }
+ catch (InvalidKeyException e)
+ {
+ throw new CmsException("key inappropriate for signature.", e);
+ }
+ catch (SignatureException e)
+ {
+ throw new CmsException("error creating signature.", e);
+ }
+ catch (CertificateEncodingException e)
+ {
+ throw new CmsException("error creating sid.", e);
+ }
+ }
+
+ Asn1Set certificates = null;
+
+ if (_certs.Count != 0)
+ {
+ certificates = UseDerForCerts
+ ? CmsUtilities.CreateDerSetFromList(_certs)
+ : CmsUtilities.CreateBerSetFromList(_certs);
+ }
+
+ Asn1Set certrevlist = null;
+
+ if (_crls.Count != 0)
+ {
+ certrevlist = UseDerForCrls
+ ? CmsUtilities.CreateDerSetFromList(_crls)
+ : CmsUtilities.CreateBerSetFromList(_crls);
+ }
+
+ Asn1OctetString octs = null;
+ if (encapsulate)
+ {
+ MemoryStream bOut = new MemoryStream();
+ if (content != null)
+ {
+ try
+ {
+ content.Write(bOut);
+ }
+ catch (IOException e)
+ {
+ throw new CmsException("encapsulation error.", e);
+ }
+ }
+ octs = new BerOctetString(bOut.ToArray());
+ }
+
+ ContentInfo encInfo = new ContentInfo(contentTypeOid, octs);
+
+ SignedData sd = new SignedData(
+ new DerSet(digestAlgs),
+ encInfo,
+ certificates,
+ certrevlist,
+ new DerSet(signerInfos));
+
+ ContentInfo contentInfo = new ContentInfo(CmsObjectIdentifiers.SignedData, sd);
+
+ return new CmsSignedData(content, contentInfo);
+ }
+
+ /**
+ * generate a signed object that for a CMS Signed Data
+ * object - if encapsulate is true a copy
+ * of the message will be included in the signature with the
+ * default content type "data".
+ */
+ public CmsSignedData Generate(
+ CmsProcessable content,
+ bool encapsulate)
+ {
+ return this.Generate(Data, content, encapsulate);
+ }
+
+ /**
+ * generate a set of one or more SignerInformation objects representing counter signatures on
+ * the passed in SignerInformation object.
+ *
+ * @param signer the signer to be countersigned
+ * @param sigProvider the provider to be used for counter signing.
+ * @return a store containing the signers.
+ */
+ public SignerInformationStore GenerateCounterSigners(
+ SignerInformation signer)
+ {
+ return this.Generate(null, new CmsProcessableByteArray(signer.GetSignature()), false).GetSignerInfos();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSSignedDataGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSSignedDataGenerator.cs.meta
new file mode 100644
index 00000000..4c34f1eb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSSignedDataGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 027a8f21814c46547a37d4ef8abcb9f2
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSSignedDataParser.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSSignedDataParser.cs
new file mode 100644
index 00000000..e1df8efb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSSignedDataParser.cs
@@ -0,0 +1,454 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.IO;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ /**
+ * Parsing class for an CMS Signed Data object from an input stream.
+ *
+ * Note: that because we are in a streaming mode only one signer can be tried and it is important
+ * that the methods on the parser are called in the appropriate order.
+ *
+ *
+ * A simple example of usage for an encapsulated signature.
+ *
+ *
+ * Two notes: first, in the example below the validity of
+ * the certificate isn't verified, just the fact that one of the certs
+ * matches the given signer, and, second, because we are in a streaming
+ * mode the order of the operations is important.
+ *
+ * Note also: this class does not introduce buffering - if you are processing large files you should create
+ * the parser with:
+ *
+ * CmsSignedDataParser ep = new CmsSignedDataParser(new BufferedInputStream(encapSigData, bufSize));
+ *
+ * where bufSize is a suitably large buffer size.
+ */
+ public class CmsSignedDataParser
+ : CmsContentInfoParser
+ {
+ private static readonly CmsSignedHelper Helper = CmsSignedHelper.Instance;
+
+ private SignedDataParser _signedData;
+ private DerObjectIdentifier _signedContentType;
+ private CmsTypedStream _signedContent;
+ private IDictionary _digests;
+ private ISet _digestOids;
+
+ private SignerInformationStore _signerInfoStore;
+ private Asn1Set _certSet, _crlSet;
+ private bool _isCertCrlParsed;
+ private IX509Store _attributeStore;
+ private IX509Store _certificateStore;
+ private IX509Store _crlStore;
+
+ public CmsSignedDataParser(
+ byte[] sigBlock)
+ : this(new MemoryStream(sigBlock, false))
+ {
+ }
+
+ public CmsSignedDataParser(
+ CmsTypedStream signedContent,
+ byte[] sigBlock)
+ : this(signedContent, new MemoryStream(sigBlock, false))
+ {
+ }
+
+ /**
+ * base constructor - with encapsulated content
+ */
+ public CmsSignedDataParser(
+ Stream sigData)
+ : this(null, sigData)
+ {
+ }
+
+ /**
+ * base constructor
+ *
+ * @param signedContent the content that was signed.
+ * @param sigData the signature object.
+ */
+ public CmsSignedDataParser(
+ CmsTypedStream signedContent,
+ Stream sigData)
+ : base(sigData)
+ {
+ try
+ {
+ this._signedContent = signedContent;
+ this._signedData = SignedDataParser.GetInstance(this.contentInfo.GetContent(Asn1Tags.Sequence));
+ this._digests = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ this._digestOids = new HashSet();
+
+ Asn1SetParser digAlgs = _signedData.GetDigestAlgorithms();
+ IAsn1Convertible o;
+
+ while ((o = digAlgs.ReadObject()) != null)
+ {
+ AlgorithmIdentifier id = AlgorithmIdentifier.GetInstance(o.ToAsn1Object());
+
+ try
+ {
+ string digestOid = id.Algorithm.Id;
+ string digestName = Helper.GetDigestAlgName(digestOid);
+
+ if (!this._digests.Contains(digestName))
+ {
+ this._digests[digestName] = Helper.GetDigestInstance(digestName);
+ this._digestOids.Add(digestOid);
+ }
+ }
+ catch (SecurityUtilityException)
+ {
+ // TODO Should do something other than ignore it
+ }
+ }
+
+ //
+ // If the message is simply a certificate chain message GetContent() may return null.
+ //
+ ContentInfoParser cont = _signedData.GetEncapContentInfo();
+ Asn1OctetStringParser octs = (Asn1OctetStringParser)
+ cont.GetContent(Asn1Tags.OctetString);
+
+ if (octs != null)
+ {
+ CmsTypedStream ctStr = new CmsTypedStream(
+ cont.ContentType.Id, octs.GetOctetStream());
+
+ if (_signedContent == null)
+ {
+ this._signedContent = ctStr;
+ }
+ else
+ {
+ //
+ // content passed in, need to read past empty encapsulated content info object if present
+ //
+ ctStr.Drain();
+ }
+ }
+
+ _signedContentType = _signedContent == null
+ ? cont.ContentType
+ : new DerObjectIdentifier(_signedContent.ContentType);
+ }
+ catch (IOException e)
+ {
+ throw new CmsException("io exception: " + e.Message, e);
+ }
+ }
+
+ /**
+ * Return the version number for the SignedData object
+ *
+ * @return the version number
+ */
+ public int Version
+ {
+ get { return _signedData.Version.Value.IntValue; }
+ }
+
+ public ISet DigestOids
+ {
+ get { return new HashSet(_digestOids); }
+ }
+
+ /**
+ * return the collection of signers that are associated with the
+ * signatures for the message.
+ * @throws CmsException
+ */
+ public SignerInformationStore GetSignerInfos()
+ {
+ if (_signerInfoStore == null)
+ {
+ PopulateCertCrlSets();
+
+ IList signerInfos = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ IDictionary hashes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+
+ foreach (object digestKey in _digests.Keys)
+ {
+ hashes[digestKey] = DigestUtilities.DoFinal(
+ (IDigest)_digests[digestKey]);
+ }
+
+ try
+ {
+ Asn1SetParser s = _signedData.GetSignerInfos();
+ IAsn1Convertible o;
+
+ while ((o = s.ReadObject()) != null)
+ {
+ SignerInfo info = SignerInfo.GetInstance(o.ToAsn1Object());
+ string digestName = Helper.GetDigestAlgName(
+ info.DigestAlgorithm.Algorithm.Id);
+
+ byte[] hash = (byte[]) hashes[digestName];
+
+ signerInfos.Add(new SignerInformation(info, _signedContentType, null, new BaseDigestCalculator(hash)));
+ }
+ }
+ catch (IOException e)
+ {
+ throw new CmsException("io exception: " + e.Message, e);
+ }
+
+ _signerInfoStore = new SignerInformationStore(signerInfos);
+ }
+
+ return _signerInfoStore;
+ }
+
+ /**
+ * return a X509Store containing the attribute certificates, if any, contained
+ * in this message.
+ *
+ * @param type type of store to create
+ * @return a store of attribute certificates
+ * @exception org.bouncycastle.x509.NoSuchStoreException if the store type isn't available.
+ * @exception CmsException if a general exception prevents creation of the X509Store
+ */
+ public IX509Store GetAttributeCertificates(
+ string type)
+ {
+ if (_attributeStore == null)
+ {
+ PopulateCertCrlSets();
+
+ _attributeStore = Helper.CreateAttributeStore(type, _certSet);
+ }
+
+ return _attributeStore;
+ }
+
+ /**
+ * return a X509Store containing the public key certificates, if any, contained
+ * in this message.
+ *
+ * @param type type of store to create
+ * @return a store of public key certificates
+ * @exception NoSuchStoreException if the store type isn't available.
+ * @exception CmsException if a general exception prevents creation of the X509Store
+ */
+ public IX509Store GetCertificates(
+ string type)
+ {
+ if (_certificateStore == null)
+ {
+ PopulateCertCrlSets();
+
+ _certificateStore = Helper.CreateCertificateStore(type, _certSet);
+ }
+
+ return _certificateStore;
+ }
+
+ /**
+ * return a X509Store containing CRLs, if any, contained
+ * in this message.
+ *
+ * @param type type of store to create
+ * @return a store of CRLs
+ * @exception NoSuchStoreException if the store type isn't available.
+ * @exception CmsException if a general exception prevents creation of the X509Store
+ */
+ public IX509Store GetCrls(
+ string type)
+ {
+ if (_crlStore == null)
+ {
+ PopulateCertCrlSets();
+
+ _crlStore = Helper.CreateCrlStore(type, _crlSet);
+ }
+
+ return _crlStore;
+ }
+
+ private void PopulateCertCrlSets()
+ {
+ if (_isCertCrlParsed)
+ return;
+
+ _isCertCrlParsed = true;
+
+ try
+ {
+ // care! Streaming - Must process the GetCertificates() result before calling GetCrls()
+ _certSet = GetAsn1Set(_signedData.GetCertificates());
+ _crlSet = GetAsn1Set(_signedData.GetCrls());
+ }
+ catch (IOException e)
+ {
+ throw new CmsException("problem parsing cert/crl sets", e);
+ }
+ }
+
+ ///
+ /// Return the DerObjectIdentifier associated with the encapsulated
+ /// content info structure carried in the signed data.
+ ///
+ public DerObjectIdentifier SignedContentType
+ {
+ get { return _signedContentType; }
+ }
+
+ public CmsTypedStream GetSignedContent()
+ {
+ if (_signedContent == null)
+ {
+ return null;
+ }
+
+ Stream digStream = _signedContent.ContentStream;
+
+ foreach (IDigest digest in _digests.Values)
+ {
+ digStream = new DigestStream(digStream, digest, null);
+ }
+
+ return new CmsTypedStream(_signedContent.ContentType, digStream);
+ }
+
+ /**
+ * Replace the signerinformation store associated with the passed
+ * in message contained in the stream original with the new one passed in.
+ * You would probably only want to do this if you wanted to change the unsigned
+ * attributes associated with a signer, or perhaps delete one.
+ *
+ * The output stream is returned unclosed.
+ *
+ * @param original the signed data stream to be used as a base.
+ * @param signerInformationStore the new signer information store to use.
+ * @param out the stream to Write the new signed data object to.
+ * @return out.
+ */
+ public static Stream ReplaceSigners(
+ Stream original,
+ SignerInformationStore signerInformationStore,
+ Stream outStr)
+ {
+ // NB: SecureRandom would be ignored since using existing signatures only
+ CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();
+ CmsSignedDataParser parser = new CmsSignedDataParser(original);
+
+// gen.AddDigests(parser.DigestOids);
+ gen.AddSigners(signerInformationStore);
+
+ CmsTypedStream signedContent = parser.GetSignedContent();
+ bool encapsulate = (signedContent != null);
+ Stream contentOut = gen.Open(outStr, parser.SignedContentType.Id, encapsulate);
+ if (encapsulate)
+ {
+ Streams.PipeAll(signedContent.ContentStream, contentOut);
+ }
+
+ gen.AddAttributeCertificates(parser.GetAttributeCertificates("Collection"));
+ gen.AddCertificates(parser.GetCertificates("Collection"));
+ gen.AddCrls(parser.GetCrls("Collection"));
+
+// gen.AddSigners(parser.GetSignerInfos());
+
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(contentOut);
+
+ return outStr;
+ }
+
+ /**
+ * Replace the certificate and CRL information associated with this
+ * CMSSignedData object with the new one passed in.
+ *
+ * The output stream is returned unclosed.
+ *
+ * @param original the signed data stream to be used as a base.
+ * @param certsAndCrls the new certificates and CRLs to be used.
+ * @param out the stream to Write the new signed data object to.
+ * @return out.
+ * @exception CmsException if there is an error processing the CertStore
+ */
+ public static Stream ReplaceCertificatesAndCrls(
+ Stream original,
+ IX509Store x509Certs,
+ IX509Store x509Crls,
+ IX509Store x509AttrCerts,
+ Stream outStr)
+ {
+ // NB: SecureRandom would be ignored since using existing signatures only
+ CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();
+ CmsSignedDataParser parser = new CmsSignedDataParser(original);
+
+ gen.AddDigests(parser.DigestOids);
+
+ CmsTypedStream signedContent = parser.GetSignedContent();
+ bool encapsulate = (signedContent != null);
+ Stream contentOut = gen.Open(outStr, parser.SignedContentType.Id, encapsulate);
+ if (encapsulate)
+ {
+ Streams.PipeAll(signedContent.ContentStream, contentOut);
+ }
+
+// gen.AddAttributeCertificates(parser.GetAttributeCertificates("Collection"));
+// gen.AddCertificates(parser.GetCertificates("Collection"));
+// gen.AddCrls(parser.GetCrls("Collection"));
+ if (x509AttrCerts != null)
+ gen.AddAttributeCertificates(x509AttrCerts);
+ if (x509Certs != null)
+ gen.AddCertificates(x509Certs);
+ if (x509Crls != null)
+ gen.AddCrls(x509Crls);
+
+ gen.AddSigners(parser.GetSignerInfos());
+
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(contentOut);
+
+ return outStr;
+ }
+
+ private static Asn1Set GetAsn1Set(
+ Asn1SetParser asn1SetParser)
+ {
+ return asn1SetParser == null
+ ? null
+ : Asn1Set.GetInstance(asn1SetParser.ToAsn1Object());
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSSignedDataParser.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSSignedDataParser.cs.meta
new file mode 100644
index 00000000..e3f0287c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSSignedDataParser.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0ccc5588045627642964cdaa1b1fddcf
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSSignedDataStreamGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSSignedDataStreamGenerator.cs
new file mode 100644
index 00000000..e8c0cd12
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSSignedDataStreamGenerator.cs
@@ -0,0 +1,937 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.Diagnostics;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.IO;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ /**
+ * General class for generating a pkcs7-signature message stream.
+ *
+ */
+ public class CmsSignedDataStreamGenerator
+ : CmsSignedGenerator
+ {
+ private static readonly CmsSignedHelper Helper = CmsSignedHelper.Instance;
+
+ private readonly IList _signerInfs = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ private readonly ISet _messageDigestOids = new HashSet();
+ private readonly IDictionary _messageDigests = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ private readonly IDictionary _messageHashes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ private bool _messageDigestsLocked;
+ private int _bufferSize;
+
+ private class DigestAndSignerInfoGeneratorHolder
+ {
+ internal readonly ISignerInfoGenerator signerInf;
+ internal readonly string digestOID;
+
+ internal DigestAndSignerInfoGeneratorHolder(ISignerInfoGenerator signerInf, String digestOID)
+ {
+ this.signerInf = signerInf;
+ this.digestOID = digestOID;
+ }
+
+ internal AlgorithmIdentifier DigestAlgorithm
+ {
+ get { return new AlgorithmIdentifier(new DerObjectIdentifier(this.digestOID), DerNull.Instance); }
+ }
+ }
+
+ private class SignerInfoGeneratorImpl : ISignerInfoGenerator
+ {
+ private readonly CmsSignedDataStreamGenerator outer;
+
+ private readonly SignerIdentifier _signerIdentifier;
+ private readonly string _digestOID;
+ private readonly string _encOID;
+ private readonly CmsAttributeTableGenerator _sAttr;
+ private readonly CmsAttributeTableGenerator _unsAttr;
+ private readonly string _encName;
+ private readonly ISigner _sig;
+
+ internal SignerInfoGeneratorImpl(
+ CmsSignedDataStreamGenerator outer,
+ AsymmetricKeyParameter key,
+ SignerIdentifier signerIdentifier,
+ string digestOID,
+ string encOID,
+ CmsAttributeTableGenerator sAttr,
+ CmsAttributeTableGenerator unsAttr)
+ {
+ this.outer = outer;
+
+ _signerIdentifier = signerIdentifier;
+ _digestOID = digestOID;
+ _encOID = encOID;
+ _sAttr = sAttr;
+ _unsAttr = unsAttr;
+ _encName = Helper.GetEncryptionAlgName(_encOID);
+
+ string digestName = Helper.GetDigestAlgName(_digestOID);
+ string signatureName = digestName + "with" + _encName;
+
+ if (_sAttr != null)
+ {
+ _sig = Helper.GetSignatureInstance(signatureName);
+ }
+ else
+ {
+ // Note: Need to use raw signatures here since we have already calculated the digest
+ if (_encName.Equals("RSA"))
+ {
+ _sig = Helper.GetSignatureInstance("RSA");
+ }
+ else if (_encName.Equals("DSA"))
+ {
+ _sig = Helper.GetSignatureInstance("NONEwithDSA");
+ }
+ // TODO Add support for raw PSS
+// else if (_encName.equals("RSAandMGF1"))
+// {
+// _sig = CMSSignedHelper.INSTANCE.getSignatureInstance("NONEWITHRSAPSS", _sigProvider);
+// try
+// {
+// // Init the params this way to avoid having a 'raw' version of each PSS algorithm
+// Signature sig2 = CMSSignedHelper.INSTANCE.getSignatureInstance(signatureName, _sigProvider);
+// PSSParameterSpec spec = (PSSParameterSpec)sig2.getParameters().getParameterSpec(PSSParameterSpec.class);
+// _sig.setParameter(spec);
+// }
+// catch (Exception e)
+// {
+// throw new SignatureException("algorithm: " + _encName + " could not be configured.");
+// }
+// }
+ else
+ {
+ throw new SignatureException("algorithm: " + _encName + " not supported in base signatures.");
+ }
+ }
+
+ _sig.Init(true, new ParametersWithRandom(key, outer.rand));
+ }
+
+ public SignerInfo Generate(DerObjectIdentifier contentType, AlgorithmIdentifier digestAlgorithm,
+ byte[] calculatedDigest)
+ {
+ try
+ {
+ string digestName = Helper.GetDigestAlgName(_digestOID);
+ string signatureName = digestName + "with" + _encName;
+
+// AlgorithmIdentifier digAlgId = DigestAlgorithmID;
+//
+// byte[] hash = (byte[])outer._messageHashes[Helper.GetDigestAlgName(this._digestOID)];
+// outer._digests[_digestOID] = hash.Clone();
+
+ byte[] bytesToSign = calculatedDigest;
+
+ /* RFC 3852 5.4
+ * The result of the message digest calculation process depends on
+ * whether the signedAttrs field is present. When the field is absent,
+ * the result is just the message digest of the content as described
+ *
+ * above. When the field is present, however, the result is the message
+ * digest of the complete DER encoding of the SignedAttrs value
+ * contained in the signedAttrs field.
+ */
+ Asn1Set signedAttr = null;
+ if (_sAttr != null)
+ {
+ IDictionary parameters = outer.GetBaseParameters(contentType, digestAlgorithm, calculatedDigest);
+
+// Asn1.Cms.AttributeTable signed = _sAttr.GetAttributes(Collections.unmodifiableMap(parameters));
+ Asn1.Cms.AttributeTable signed = _sAttr.GetAttributes(parameters);
+
+ if (contentType == null) //counter signature
+ {
+ if (signed != null && signed[CmsAttributes.ContentType] != null)
+ {
+ IDictionary tmpSigned = signed.ToDictionary();
+ tmpSigned.Remove(CmsAttributes.ContentType);
+ signed = new Asn1.Cms.AttributeTable(tmpSigned);
+ }
+ }
+
+ signedAttr = outer.GetAttributeSet(signed);
+
+ // sig must be composed from the DER encoding.
+ bytesToSign = signedAttr.GetEncoded(Asn1Encodable.Der);
+ }
+ else
+ {
+ // Note: Need to use raw signatures here since we have already calculated the digest
+ if (_encName.Equals("RSA"))
+ {
+ DigestInfo dInfo = new DigestInfo(digestAlgorithm, calculatedDigest);
+ bytesToSign = dInfo.GetEncoded(Asn1Encodable.Der);
+ }
+ }
+
+ _sig.BlockUpdate(bytesToSign, 0, bytesToSign.Length);
+ byte[] sigBytes = _sig.GenerateSignature();
+
+ Asn1Set unsignedAttr = null;
+ if (_unsAttr != null)
+ {
+ IDictionary parameters = outer.GetBaseParameters(
+ contentType, digestAlgorithm, calculatedDigest);
+ parameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone();
+
+// Asn1.Cms.AttributeTable unsigned = _unsAttr.getAttributes(Collections.unmodifiableMap(parameters));
+ Asn1.Cms.AttributeTable unsigned = _unsAttr.GetAttributes(parameters);
+
+ unsignedAttr = outer.GetAttributeSet(unsigned);
+ }
+
+ // TODO[RSAPSS] Need the ability to specify non-default parameters
+ Asn1Encodable sigX509Parameters = SignerUtilities.GetDefaultX509Parameters(signatureName);
+ AlgorithmIdentifier digestEncryptionAlgorithm = Helper.GetEncAlgorithmIdentifier(
+ new DerObjectIdentifier(_encOID), sigX509Parameters);
+
+ return new SignerInfo(_signerIdentifier, digestAlgorithm,
+ signedAttr, digestEncryptionAlgorithm, new DerOctetString(sigBytes), unsignedAttr);
+ }
+ catch (IOException e)
+ {
+ throw new CmsStreamException("encoding error.", e);
+ }
+ catch (SignatureException e)
+ {
+ throw new CmsStreamException("error creating signature.", e);
+ }
+ }
+ }
+
+ public CmsSignedDataStreamGenerator()
+ {
+ }
+
+ /// Constructor allowing specific source of randomness
+ /// Instance of SecureRandom to use.
+ public CmsSignedDataStreamGenerator(
+ SecureRandom rand)
+ : base(rand)
+ {
+ }
+
+ /**
+ * Set the underlying string size for encapsulated data
+ *
+ * @param bufferSize length of octet strings to buffer the data.
+ */
+ public void SetBufferSize(
+ int bufferSize)
+ {
+ _bufferSize = bufferSize;
+ }
+
+ public void AddDigests(
+ params string[] digestOids)
+ {
+ AddDigests((IEnumerable) digestOids);
+ }
+
+ public void AddDigests(
+ IEnumerable digestOids)
+ {
+ foreach (string digestOid in digestOids)
+ {
+ ConfigureDigest(digestOid);
+ }
+ }
+
+ /**
+ * add a signer - no attributes other than the default ones will be
+ * provided here.
+ * @throws NoSuchAlgorithmException
+ * @throws InvalidKeyException
+ */
+ public void AddSigner(
+ AsymmetricKeyParameter privateKey,
+ X509Certificate cert,
+ string digestOid)
+ {
+ AddSigner(privateKey, cert, digestOid,
+ new DefaultSignedAttributeTableGenerator(), null);
+ }
+
+ /**
+ * add a signer, specifying the digest encryption algorithm - no attributes other than the default ones will be
+ * provided here.
+ * @throws NoSuchProviderException
+ * @throws NoSuchAlgorithmException
+ * @throws InvalidKeyException
+ */
+ public void AddSigner(
+ AsymmetricKeyParameter privateKey,
+ X509Certificate cert,
+ string encryptionOid,
+ string digestOid)
+ {
+ AddSigner(privateKey, cert, encryptionOid, digestOid,
+ new DefaultSignedAttributeTableGenerator(),
+ (CmsAttributeTableGenerator)null);
+ }
+
+ /**
+ * add a signer with extra signed/unsigned attributes.
+ * @throws NoSuchAlgorithmException
+ * @throws InvalidKeyException
+ */
+ public void AddSigner(
+ AsymmetricKeyParameter privateKey,
+ X509Certificate cert,
+ string digestOid,
+ Asn1.Cms.AttributeTable signedAttr,
+ Asn1.Cms.AttributeTable unsignedAttr)
+ {
+ AddSigner(privateKey, cert, digestOid,
+ new DefaultSignedAttributeTableGenerator(signedAttr),
+ new SimpleAttributeTableGenerator(unsignedAttr));
+ }
+
+ /**
+ * add a signer with extra signed/unsigned attributes - specifying digest
+ * encryption algorithm.
+ * @throws NoSuchProviderException
+ * @throws NoSuchAlgorithmException
+ * @throws InvalidKeyException
+ */
+ public void AddSigner(
+ AsymmetricKeyParameter privateKey,
+ X509Certificate cert,
+ string encryptionOid,
+ string digestOid,
+ Asn1.Cms.AttributeTable signedAttr,
+ Asn1.Cms.AttributeTable unsignedAttr)
+ {
+ AddSigner(privateKey, cert, encryptionOid, digestOid,
+ new DefaultSignedAttributeTableGenerator(signedAttr),
+ new SimpleAttributeTableGenerator(unsignedAttr));
+ }
+
+ public void AddSigner(
+ AsymmetricKeyParameter privateKey,
+ X509Certificate cert,
+ string digestOid,
+ CmsAttributeTableGenerator signedAttrGenerator,
+ CmsAttributeTableGenerator unsignedAttrGenerator)
+ {
+ AddSigner(privateKey, cert, Helper.GetEncOid(privateKey, digestOid), digestOid,
+ signedAttrGenerator, unsignedAttrGenerator);
+ }
+
+ public void AddSigner(
+ AsymmetricKeyParameter privateKey,
+ X509Certificate cert,
+ string encryptionOid,
+ string digestOid,
+ CmsAttributeTableGenerator signedAttrGenerator,
+ CmsAttributeTableGenerator unsignedAttrGenerator)
+ {
+ DoAddSigner(privateKey, GetSignerIdentifier(cert), encryptionOid, digestOid,
+ signedAttrGenerator, unsignedAttrGenerator);
+ }
+
+ /**
+ * add a signer - no attributes other than the default ones will be
+ * provided here.
+ * @throws NoSuchAlgorithmException
+ * @throws InvalidKeyException
+ */
+ public void AddSigner(
+ AsymmetricKeyParameter privateKey,
+ byte[] subjectKeyID,
+ string digestOid)
+ {
+ AddSigner(privateKey, subjectKeyID, digestOid, new DefaultSignedAttributeTableGenerator(),
+ (CmsAttributeTableGenerator)null);
+ }
+
+ /**
+ * add a signer - no attributes other than the default ones will be
+ * provided here.
+ * @throws NoSuchProviderException
+ * @throws NoSuchAlgorithmException
+ * @throws InvalidKeyException
+ */
+ public void AddSigner(
+ AsymmetricKeyParameter privateKey,
+ byte[] subjectKeyID,
+ string encryptionOid,
+ string digestOid)
+ {
+ AddSigner(privateKey, subjectKeyID, encryptionOid, digestOid,
+ new DefaultSignedAttributeTableGenerator(),
+ (CmsAttributeTableGenerator)null);
+ }
+
+ /**
+ * add a signer with extra signed/unsigned attributes.
+ * @throws NoSuchAlgorithmException
+ * @throws InvalidKeyException
+ */
+ public void AddSigner(
+ AsymmetricKeyParameter privateKey,
+ byte[] subjectKeyID,
+ string digestOid,
+ Asn1.Cms.AttributeTable signedAttr,
+ Asn1.Cms.AttributeTable unsignedAttr)
+ {
+ AddSigner(privateKey, subjectKeyID, digestOid,
+ new DefaultSignedAttributeTableGenerator(signedAttr),
+ new SimpleAttributeTableGenerator(unsignedAttr));
+ }
+
+ public void AddSigner(
+ AsymmetricKeyParameter privateKey,
+ byte[] subjectKeyID,
+ string digestOid,
+ CmsAttributeTableGenerator signedAttrGenerator,
+ CmsAttributeTableGenerator unsignedAttrGenerator)
+ {
+ AddSigner(privateKey, subjectKeyID, Helper.GetEncOid(privateKey, digestOid),
+ digestOid, signedAttrGenerator, unsignedAttrGenerator);
+ }
+
+ public void AddSigner(
+ AsymmetricKeyParameter privateKey,
+ byte[] subjectKeyID,
+ string encryptionOid,
+ string digestOid,
+ CmsAttributeTableGenerator signedAttrGenerator,
+ CmsAttributeTableGenerator unsignedAttrGenerator)
+ {
+ DoAddSigner(privateKey, GetSignerIdentifier(subjectKeyID), encryptionOid, digestOid,
+ signedAttrGenerator, unsignedAttrGenerator);
+ }
+
+ private void DoAddSigner(
+ AsymmetricKeyParameter privateKey,
+ SignerIdentifier signerIdentifier,
+ string encryptionOid,
+ string digestOid,
+ CmsAttributeTableGenerator signedAttrGenerator,
+ CmsAttributeTableGenerator unsignedAttrGenerator)
+ {
+ ConfigureDigest(digestOid);
+
+ SignerInfoGeneratorImpl signerInf = new SignerInfoGeneratorImpl(this, privateKey,
+ signerIdentifier, digestOid, encryptionOid, signedAttrGenerator, unsignedAttrGenerator);
+
+ _signerInfs.Add(new DigestAndSignerInfoGeneratorHolder(signerInf, digestOid));
+ }
+
+ internal override void AddSignerCallback(
+ SignerInformation si)
+ {
+ // FIXME If there were parameters in si.DigestAlgorithmID.Parameters, they are lost
+ // NB: Would need to call FixAlgID on the DigestAlgorithmID
+
+ // For precalculated signers, just need to register the algorithm, not configure a digest
+ RegisterDigestOid(si.DigestAlgorithmID.Algorithm.Id);
+ }
+
+ /**
+ * generate a signed object that for a CMS Signed Data object
+ */
+ public Stream Open(
+ Stream outStream)
+ {
+ return Open(outStream, false);
+ }
+
+ /**
+ * generate a signed object that for a CMS Signed Data
+ * object - if encapsulate is true a copy
+ * of the message will be included in the signature with the
+ * default content type "data".
+ */
+ public Stream Open(
+ Stream outStream,
+ bool encapsulate)
+ {
+ return Open(outStream, Data, encapsulate);
+ }
+
+ /**
+ * generate a signed object that for a CMS Signed Data
+ * object using the given provider - if encapsulate is true a copy
+ * of the message will be included in the signature with the
+ * default content type "data". If dataOutputStream is non null the data
+ * being signed will be written to the stream as it is processed.
+ * @param out stream the CMS object is to be written to.
+ * @param encapsulate true if data should be encapsulated.
+ * @param dataOutputStream output stream to copy the data being signed to.
+ */
+ public Stream Open(
+ Stream outStream,
+ bool encapsulate,
+ Stream dataOutputStream)
+ {
+ return Open(outStream, Data, encapsulate, dataOutputStream);
+ }
+
+ /**
+ * generate a signed object that for a CMS Signed Data
+ * object - if encapsulate is true a copy
+ * of the message will be included in the signature. The content type
+ * is set according to the OID represented by the string signedContentType.
+ */
+ public Stream Open(
+ Stream outStream,
+ string signedContentType,
+ bool encapsulate)
+ {
+ return Open(outStream, signedContentType, encapsulate, null);
+ }
+
+ /**
+ * generate a signed object that for a CMS Signed Data
+ * object using the given provider - if encapsulate is true a copy
+ * of the message will be included in the signature. The content type
+ * is set according to the OID represented by the string signedContentType.
+ * @param out stream the CMS object is to be written to.
+ * @param signedContentType OID for data to be signed.
+ * @param encapsulate true if data should be encapsulated.
+ * @param dataOutputStream output stream to copy the data being signed to.
+ */
+ public Stream Open(
+ Stream outStream,
+ string signedContentType,
+ bool encapsulate,
+ Stream dataOutputStream)
+ {
+ if (outStream == null)
+ throw new ArgumentNullException("outStream");
+ if (!outStream.CanWrite)
+ throw new ArgumentException("Expected writeable stream", "outStream");
+ if (dataOutputStream != null && !dataOutputStream.CanWrite)
+ throw new ArgumentException("Expected writeable stream", "dataOutputStream");
+
+ _messageDigestsLocked = true;
+
+ //
+ // ContentInfo
+ //
+ BerSequenceGenerator sGen = new BerSequenceGenerator(outStream);
+
+ sGen.AddObject(CmsObjectIdentifiers.SignedData);
+
+ //
+ // Signed Data
+ //
+ BerSequenceGenerator sigGen = new BerSequenceGenerator(
+ sGen.GetRawOutputStream(), 0, true);
+
+ bool isCounterSignature = (signedContentType == null);
+
+ DerObjectIdentifier contentTypeOid = isCounterSignature
+ ? null
+ : new DerObjectIdentifier(signedContentType);
+
+ sigGen.AddObject(CalculateVersion(contentTypeOid));
+
+ Asn1EncodableVector digestAlgs = new Asn1EncodableVector();
+
+ foreach (string digestOid in _messageDigestOids)
+ {
+ digestAlgs.Add(
+ new AlgorithmIdentifier(new DerObjectIdentifier(digestOid), DerNull.Instance));
+ }
+
+ {
+ byte[] tmp = new DerSet(digestAlgs).GetEncoded();
+ sigGen.GetRawOutputStream().Write(tmp, 0, tmp.Length);
+ }
+
+ BerSequenceGenerator eiGen = new BerSequenceGenerator(sigGen.GetRawOutputStream());
+ eiGen.AddObject(contentTypeOid);
+
+ // If encapsulating, add the data as an octet string in the sequence
+ Stream encapStream = encapsulate
+ ? CmsUtilities.CreateBerOctetOutputStream(eiGen.GetRawOutputStream(), 0, true, _bufferSize)
+ : null;
+
+ // Also send the data to 'dataOutputStream' if necessary
+ Stream teeStream = GetSafeTeeOutputStream(dataOutputStream, encapStream);
+
+ // Let all the digests see the data as it is written
+ Stream digStream = AttachDigestsToOutputStream(_messageDigests.Values, teeStream);
+
+ return new CmsSignedDataOutputStream(this, digStream, signedContentType, sGen, sigGen, eiGen);
+ }
+
+ private void RegisterDigestOid(
+ string digestOid)
+ {
+ if (_messageDigestsLocked)
+ {
+ if (!_messageDigestOids.Contains(digestOid))
+ throw new InvalidOperationException("Cannot register new digest OIDs after the data stream is opened");
+ }
+ else
+ {
+ _messageDigestOids.Add(digestOid);
+ }
+ }
+
+ private void ConfigureDigest(
+ string digestOid)
+ {
+ RegisterDigestOid(digestOid);
+
+ string digestName = Helper.GetDigestAlgName(digestOid);
+ IDigest dig = (IDigest)_messageDigests[digestName];
+ if (dig == null)
+ {
+ if (_messageDigestsLocked)
+ throw new InvalidOperationException("Cannot configure new digests after the data stream is opened");
+
+ dig = Helper.GetDigestInstance(digestName);
+ _messageDigests[digestName] = dig;
+ }
+ }
+
+ // TODO Make public?
+ internal void Generate(
+ Stream outStream,
+ string eContentType,
+ bool encapsulate,
+ Stream dataOutputStream,
+ CmsProcessable content)
+ {
+ Stream signedOut = Open(outStream, eContentType, encapsulate, dataOutputStream);
+ if (content != null)
+ {
+ content.Write(signedOut);
+ }
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(signedOut);
+ }
+
+ // RFC3852, section 5.1:
+ // IF ((certificates is present) AND
+ // (any certificates with a type of other are present)) OR
+ // ((crls is present) AND
+ // (any crls with a type of other are present))
+ // THEN version MUST be 5
+ // ELSE
+ // IF (certificates is present) AND
+ // (any version 2 attribute certificates are present)
+ // THEN version MUST be 4
+ // ELSE
+ // IF ((certificates is present) AND
+ // (any version 1 attribute certificates are present)) OR
+ // (any SignerInfo structures are version 3) OR
+ // (encapContentInfo eContentType is other than id-data)
+ // THEN version MUST be 3
+ // ELSE version MUST be 1
+ //
+ private DerInteger CalculateVersion(
+ DerObjectIdentifier contentOid)
+ {
+ bool otherCert = false;
+ bool otherCrl = false;
+ bool attrCertV1Found = false;
+ bool attrCertV2Found = false;
+
+ if (_certs != null)
+ {
+ foreach (object obj in _certs)
+ {
+ if (obj is Asn1TaggedObject)
+ {
+ Asn1TaggedObject tagged = (Asn1TaggedObject) obj;
+
+ if (tagged.TagNo == 1)
+ {
+ attrCertV1Found = true;
+ }
+ else if (tagged.TagNo == 2)
+ {
+ attrCertV2Found = true;
+ }
+ else if (tagged.TagNo == 3)
+ {
+ otherCert = true;
+ break;
+ }
+ }
+ }
+ }
+
+ if (otherCert)
+ {
+ return new DerInteger(5);
+ }
+
+ if (_crls != null)
+ {
+ foreach (object obj in _crls)
+ {
+ if (obj is Asn1TaggedObject)
+ {
+ otherCrl = true;
+ break;
+ }
+ }
+ }
+
+ if (otherCrl)
+ {
+ return new DerInteger(5);
+ }
+
+ if (attrCertV2Found)
+ {
+ return new DerInteger(4);
+ }
+
+ if (attrCertV1Found || !CmsObjectIdentifiers.Data.Equals(contentOid) || CheckForVersion3(_signers))
+ {
+ return new DerInteger(3);
+ }
+
+ return new DerInteger(1);
+ }
+
+ private bool CheckForVersion3(
+ IList signerInfos)
+ {
+ foreach (SignerInformation si in signerInfos)
+ {
+ SignerInfo s = SignerInfo.GetInstance(si.ToSignerInfo());
+
+ if (s.Version.Value.IntValue == 3)
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private static Stream AttachDigestsToOutputStream(ICollection digests, Stream s)
+ {
+ Stream result = s;
+ foreach (IDigest digest in digests)
+ {
+ result = GetSafeTeeOutputStream(result, new DigestSink(digest));
+ }
+ return result;
+ }
+
+ private static Stream GetSafeOutputStream(Stream s)
+ {
+ if (s == null)
+ return new NullOutputStream();
+ return s;
+ }
+
+ private static Stream GetSafeTeeOutputStream(Stream s1, Stream s2)
+ {
+ if (s1 == null)
+ return GetSafeOutputStream(s2);
+ if (s2 == null)
+ return GetSafeOutputStream(s1);
+ return new TeeOutputStream(s1, s2);
+ }
+
+ private class CmsSignedDataOutputStream
+ : BaseOutputStream
+ {
+ private readonly CmsSignedDataStreamGenerator outer;
+
+ private Stream _out;
+ private DerObjectIdentifier _contentOID;
+ private BerSequenceGenerator _sGen;
+ private BerSequenceGenerator _sigGen;
+ private BerSequenceGenerator _eiGen;
+
+ public CmsSignedDataOutputStream(
+ CmsSignedDataStreamGenerator outer,
+ Stream outStream,
+ string contentOID,
+ BerSequenceGenerator sGen,
+ BerSequenceGenerator sigGen,
+ BerSequenceGenerator eiGen)
+ {
+ this.outer = outer;
+
+ _out = outStream;
+ _contentOID = new DerObjectIdentifier(contentOID);
+ _sGen = sGen;
+ _sigGen = sigGen;
+ _eiGen = eiGen;
+ }
+
+ public override void WriteByte(
+ byte b)
+ {
+ _out.WriteByte(b);
+ }
+
+ public override void Write(
+ byte[] bytes,
+ int off,
+ int len)
+ {
+ _out.Write(bytes, off, len);
+ }
+
+#if PORTABLE || NETFX_CORE
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ DoClose();
+ }
+ base.Dispose(disposing);
+ }
+#else
+ public override void Close()
+ {
+ DoClose();
+ base.Close();
+ }
+#endif
+
+ private void DoClose()
+ {
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(_out);
+
+ // TODO Parent context(s) should really be be closed explicitly
+
+ _eiGen.Close();
+
+ outer._digests.Clear(); // clear the current preserved digest state
+
+ if (outer._certs.Count > 0)
+ {
+ Asn1Set certs = outer.UseDerForCerts
+ ? CmsUtilities.CreateDerSetFromList(outer._certs)
+ : CmsUtilities.CreateBerSetFromList(outer._certs);
+
+ WriteToGenerator(_sigGen, new BerTaggedObject(false, 0, certs));
+ }
+
+ if (outer._crls.Count > 0)
+ {
+ Asn1Set crls = outer.UseDerForCrls
+ ? CmsUtilities.CreateDerSetFromList(outer._crls)
+ : CmsUtilities.CreateBerSetFromList(outer._crls);
+
+ WriteToGenerator(_sigGen, new BerTaggedObject(false, 1, crls));
+ }
+
+ //
+ // Calculate the digest hashes
+ //
+ foreach (DictionaryEntry de in outer._messageDigests)
+ {
+ outer._messageHashes.Add(de.Key, DigestUtilities.DoFinal((IDigest)de.Value));
+ }
+
+ // TODO If the digest OIDs for precalculated signers weren't mixed in with
+ // the others, we could fill in outer._digests here, instead of SignerInfoGenerator.Generate
+
+ //
+ // collect all the SignerInfo objects
+ //
+ Asn1EncodableVector signerInfos = new Asn1EncodableVector();
+
+ //
+ // add the generated SignerInfo objects
+ //
+ {
+ foreach (DigestAndSignerInfoGeneratorHolder holder in outer._signerInfs)
+ {
+ AlgorithmIdentifier digestAlgorithm = holder.DigestAlgorithm;
+
+ byte[] calculatedDigest = (byte[])outer._messageHashes[
+ Helper.GetDigestAlgName(holder.digestOID)];
+ outer._digests[holder.digestOID] = calculatedDigest.Clone();
+
+ signerInfos.Add(holder.signerInf.Generate(_contentOID, digestAlgorithm, calculatedDigest));
+ }
+ }
+
+ //
+ // add the precalculated SignerInfo objects.
+ //
+ {
+ foreach (SignerInformation signer in outer._signers)
+ {
+ // TODO Verify the content type and calculated digest match the precalculated SignerInfo
+// if (!signer.ContentType.Equals(_contentOID))
+// {
+// // TODO The precalculated content type did not match - error?
+// }
+//
+// byte[] calculatedDigest = (byte[])outer._digests[signer.DigestAlgOid];
+// if (calculatedDigest == null)
+// {
+// // TODO We can't confirm this digest because we didn't calculate it - error?
+// }
+// else
+// {
+// if (!Arrays.AreEqual(signer.GetContentDigest(), calculatedDigest))
+// {
+// // TODO The precalculated digest did not match - error?
+// }
+// }
+
+ signerInfos.Add(signer.ToSignerInfo());
+ }
+ }
+
+ WriteToGenerator(_sigGen, new DerSet(signerInfos));
+
+ _sigGen.Close();
+ _sGen.Close();
+ }
+
+ private static void WriteToGenerator(
+ Asn1Generator ag,
+ Asn1Encodable ae)
+ {
+ byte[] encoded = ae.GetEncoded();
+ ag.GetRawOutputStream().Write(encoded, 0, encoded.Length);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSSignedDataStreamGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSSignedDataStreamGenerator.cs.meta
new file mode 100644
index 00000000..088a416a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSSignedDataStreamGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 7609ff86af1d8cc4599341b4d5d36229
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSSignedGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSSignedGenerator.cs
new file mode 100644
index 00000000..dce67f30
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSSignedGenerator.cs
@@ -0,0 +1,287 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Oiw;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.TeleTrust;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ public class DefaultDigestAlgorithmIdentifierFinder
+ {
+ private static readonly IDictionary digestOids = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ private static readonly IDictionary digestNameToOids = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+
+ static DefaultDigestAlgorithmIdentifierFinder()
+ {
+ //
+ // digests
+ //
+ digestOids.Add(OiwObjectIdentifiers.MD4WithRsaEncryption, PkcsObjectIdentifiers.MD4);
+ digestOids.Add(OiwObjectIdentifiers.MD4WithRsa, PkcsObjectIdentifiers.MD4);
+ digestOids.Add(OiwObjectIdentifiers.MD5WithRsa, PkcsObjectIdentifiers.MD5);
+ digestOids.Add(OiwObjectIdentifiers.Sha1WithRsa, OiwObjectIdentifiers.IdSha1);
+ digestOids.Add(OiwObjectIdentifiers.DsaWithSha1, OiwObjectIdentifiers.IdSha1);
+
+ digestOids.Add(PkcsObjectIdentifiers.Sha224WithRsaEncryption, NistObjectIdentifiers.IdSha224);
+ digestOids.Add(PkcsObjectIdentifiers.Sha256WithRsaEncryption, NistObjectIdentifiers.IdSha256);
+ digestOids.Add(PkcsObjectIdentifiers.Sha384WithRsaEncryption, NistObjectIdentifiers.IdSha384);
+ digestOids.Add(PkcsObjectIdentifiers.Sha512WithRsaEncryption, NistObjectIdentifiers.IdSha512);
+ digestOids.Add(PkcsObjectIdentifiers.MD2WithRsaEncryption, PkcsObjectIdentifiers.MD2);
+ digestOids.Add(PkcsObjectIdentifiers.MD4WithRsaEncryption, PkcsObjectIdentifiers.MD4);
+ digestOids.Add(PkcsObjectIdentifiers.MD5WithRsaEncryption, PkcsObjectIdentifiers.MD5);
+ digestOids.Add(PkcsObjectIdentifiers.Sha1WithRsaEncryption, OiwObjectIdentifiers.IdSha1);
+
+ digestOids.Add(X9ObjectIdentifiers.ECDsaWithSha1, OiwObjectIdentifiers.IdSha1);
+ digestOids.Add(X9ObjectIdentifiers.ECDsaWithSha224, NistObjectIdentifiers.IdSha224);
+ digestOids.Add(X9ObjectIdentifiers.ECDsaWithSha256, NistObjectIdentifiers.IdSha256);
+ digestOids.Add(X9ObjectIdentifiers.ECDsaWithSha384, NistObjectIdentifiers.IdSha384);
+ digestOids.Add(X9ObjectIdentifiers.ECDsaWithSha512, NistObjectIdentifiers.IdSha512);
+ digestOids.Add(X9ObjectIdentifiers.IdDsaWithSha1, OiwObjectIdentifiers.IdSha1);
+
+ digestOids.Add(NistObjectIdentifiers.DsaWithSha224, NistObjectIdentifiers.IdSha224);
+ digestOids.Add(NistObjectIdentifiers.DsaWithSha256, NistObjectIdentifiers.IdSha256);
+ digestOids.Add(NistObjectIdentifiers.DsaWithSha384, NistObjectIdentifiers.IdSha384);
+ digestOids.Add(NistObjectIdentifiers.DsaWithSha512, NistObjectIdentifiers.IdSha512);
+
+ digestOids.Add(TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128, TeleTrusTObjectIdentifiers.RipeMD128);
+ digestOids.Add(TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160, TeleTrusTObjectIdentifiers.RipeMD160);
+ digestOids.Add(TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256, TeleTrusTObjectIdentifiers.RipeMD256);
+
+ digestOids.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94, CryptoProObjectIdentifiers.GostR3411);
+ digestOids.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001, CryptoProObjectIdentifiers.GostR3411);
+
+ digestNameToOids.Add("SHA-1", OiwObjectIdentifiers.IdSha1);
+ digestNameToOids.Add("SHA-224", NistObjectIdentifiers.IdSha224);
+ digestNameToOids.Add("SHA-256", NistObjectIdentifiers.IdSha256);
+ digestNameToOids.Add("SHA-384", NistObjectIdentifiers.IdSha384);
+ digestNameToOids.Add("SHA-512", NistObjectIdentifiers.IdSha512);
+
+ digestNameToOids.Add("SHA1", OiwObjectIdentifiers.IdSha1);
+ digestNameToOids.Add("SHA224", NistObjectIdentifiers.IdSha224);
+ digestNameToOids.Add("SHA256", NistObjectIdentifiers.IdSha256);
+ digestNameToOids.Add("SHA384", NistObjectIdentifiers.IdSha384);
+ digestNameToOids.Add("SHA512", NistObjectIdentifiers.IdSha512);
+
+ digestNameToOids.Add("SHA3-224", NistObjectIdentifiers.IdSha3_224);
+ digestNameToOids.Add("SHA3-256", NistObjectIdentifiers.IdSha3_256);
+ digestNameToOids.Add("SHA3-384", NistObjectIdentifiers.IdSha3_384);
+ digestNameToOids.Add("SHA3-512", NistObjectIdentifiers.IdSha3_512);
+
+ digestNameToOids.Add("SHAKE-128", NistObjectIdentifiers.IdShake128);
+ digestNameToOids.Add("SHAKE-256", NistObjectIdentifiers.IdShake256);
+
+ digestNameToOids.Add("GOST3411", CryptoProObjectIdentifiers.GostR3411);
+
+ digestNameToOids.Add("MD2", PkcsObjectIdentifiers.MD2);
+ digestNameToOids.Add("MD4", PkcsObjectIdentifiers.MD4);
+ digestNameToOids.Add("MD5", PkcsObjectIdentifiers.MD5);
+
+ digestNameToOids.Add("RIPEMD128", TeleTrusTObjectIdentifiers.RipeMD128);
+ digestNameToOids.Add("RIPEMD160", TeleTrusTObjectIdentifiers.RipeMD160);
+ digestNameToOids.Add("RIPEMD256", TeleTrusTObjectIdentifiers.RipeMD256);
+ }
+
+ public AlgorithmIdentifier find(AlgorithmIdentifier sigAlgId)
+ {
+ AlgorithmIdentifier digAlgId;
+
+ if (sigAlgId.Algorithm.Equals(PkcsObjectIdentifiers.IdRsassaPss))
+ {
+ digAlgId = RsassaPssParameters.GetInstance(sigAlgId.Parameters).HashAlgorithm;
+ }
+ else
+ {
+ digAlgId = new AlgorithmIdentifier((DerObjectIdentifier)digestOids[sigAlgId.Algorithm], DerNull.Instance);
+ }
+
+ return digAlgId;
+ }
+
+ public AlgorithmIdentifier find(String digAlgName)
+ {
+ return new AlgorithmIdentifier((DerObjectIdentifier)digestNameToOids[digAlgName], DerNull.Instance);
+ }
+ }
+
+ public class CmsSignedGenerator
+ {
+ /**
+ * Default type for the signed data.
+ */
+ public static readonly string Data = CmsObjectIdentifiers.Data.Id;
+
+ public static readonly string DigestSha1 = OiwObjectIdentifiers.IdSha1.Id;
+ public static readonly string DigestSha224 = NistObjectIdentifiers.IdSha224.Id;
+ public static readonly string DigestSha256 = NistObjectIdentifiers.IdSha256.Id;
+ public static readonly string DigestSha384 = NistObjectIdentifiers.IdSha384.Id;
+ public static readonly string DigestSha512 = NistObjectIdentifiers.IdSha512.Id;
+ public static readonly string DigestMD5 = PkcsObjectIdentifiers.MD5.Id;
+ public static readonly string DigestGost3411 = CryptoProObjectIdentifiers.GostR3411.Id;
+ public static readonly string DigestRipeMD128 = TeleTrusTObjectIdentifiers.RipeMD128.Id;
+ public static readonly string DigestRipeMD160 = TeleTrusTObjectIdentifiers.RipeMD160.Id;
+ public static readonly string DigestRipeMD256 = TeleTrusTObjectIdentifiers.RipeMD256.Id;
+
+ public static readonly string EncryptionRsa = PkcsObjectIdentifiers.RsaEncryption.Id;
+ public static readonly string EncryptionDsa = X9ObjectIdentifiers.IdDsaWithSha1.Id;
+ public static readonly string EncryptionECDsa = X9ObjectIdentifiers.ECDsaWithSha1.Id;
+ public static readonly string EncryptionRsaPss = PkcsObjectIdentifiers.IdRsassaPss.Id;
+ public static readonly string EncryptionGost3410 = CryptoProObjectIdentifiers.GostR3410x94.Id;
+ public static readonly string EncryptionECGost3410 = CryptoProObjectIdentifiers.GostR3410x2001.Id;
+
+ internal IList _certs = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ internal IList _crls = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ internal IList _signers = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ internal IDictionary _digests = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ internal bool _useDerForCerts = false;
+ internal bool _useDerForCrls = false;
+
+ protected readonly SecureRandom rand;
+
+ protected CmsSignedGenerator()
+ : this(new SecureRandom())
+ {
+ }
+
+ /// Constructor allowing specific source of randomness
+ /// Instance of SecureRandom to use.
+ protected CmsSignedGenerator(
+ SecureRandom rand)
+ {
+ this.rand = rand;
+ }
+
+ internal protected virtual IDictionary GetBaseParameters(
+ DerObjectIdentifier contentType,
+ AlgorithmIdentifier digAlgId,
+ byte[] hash)
+ {
+ IDictionary param = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+
+ if (contentType != null)
+ {
+ param[CmsAttributeTableParameter.ContentType] = contentType;
+ }
+
+ param[CmsAttributeTableParameter.DigestAlgorithmIdentifier] = digAlgId;
+ param[CmsAttributeTableParameter.Digest] = hash.Clone();
+
+ return param;
+ }
+
+ internal protected virtual Asn1Set GetAttributeSet(
+ Asn1.Cms.AttributeTable attr)
+ {
+ return attr == null
+ ? null
+ : new DerSet(attr.ToAsn1EncodableVector());
+ }
+
+ public void AddCertificates(
+ IX509Store certStore)
+ {
+ CollectionUtilities.AddRange(_certs, CmsUtilities.GetCertificatesFromStore(certStore));
+ }
+
+ public void AddCrls(
+ IX509Store crlStore)
+ {
+ CollectionUtilities.AddRange(_crls, CmsUtilities.GetCrlsFromStore(crlStore));
+ }
+
+ /**
+ * Add the attribute certificates contained in the passed in store to the
+ * generator.
+ *
+ * @param store a store of Version 2 attribute certificates
+ * @throws CmsException if an error occurse processing the store.
+ */
+ public void AddAttributeCertificates(
+ IX509Store store)
+ {
+ try
+ {
+ foreach (IX509AttributeCertificate attrCert in store.GetMatches(null))
+ {
+ _certs.Add(new DerTaggedObject(false, 2,
+ AttributeCertificate.GetInstance(Asn1Object.FromByteArray(attrCert.GetEncoded()))));
+ }
+ }
+ catch (Exception e)
+ {
+ throw new CmsException("error processing attribute certs", e);
+ }
+ }
+
+ /**
+ * Add a store of precalculated signers to the generator.
+ *
+ * @param signerStore store of signers
+ */
+ public void AddSigners(
+ SignerInformationStore signerStore)
+ {
+ foreach (SignerInformation o in signerStore.GetSigners())
+ {
+ _signers.Add(o);
+ AddSignerCallback(o);
+ }
+ }
+
+ /**
+ * Return a map of oids and byte arrays representing the digests calculated on the content during
+ * the last generate.
+ *
+ * @return a map of oids (as String objects) and byte[] representing digests.
+ */
+ public IDictionary GetGeneratedDigests()
+ {
+ return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(_digests);
+ }
+
+ public bool UseDerForCerts
+ {
+ get { return _useDerForCerts; }
+ set { this._useDerForCerts = value; }
+ }
+
+ public bool UseDerForCrls
+ {
+ get { return _useDerForCrls; }
+ set { this._useDerForCrls = value; }
+ }
+
+ internal virtual void AddSignerCallback(
+ SignerInformation si)
+ {
+ }
+
+ internal static SignerIdentifier GetSignerIdentifier(X509Certificate cert)
+ {
+ return new SignerIdentifier(CmsUtilities.GetIssuerAndSerialNumber(cert));
+ }
+
+ internal static SignerIdentifier GetSignerIdentifier(byte[] subjectKeyIdentifier)
+ {
+ return new SignerIdentifier(new DerOctetString(subjectKeyIdentifier));
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSSignedGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSSignedGenerator.cs.meta
new file mode 100644
index 00000000..50cecdfc
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSSignedGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 005c41845e2bb2c44b19515d790e39e7
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSSignedHelper.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSSignedHelper.cs
new file mode 100644
index 00000000..a48edd4d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSSignedHelper.cs
@@ -0,0 +1,430 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Eac;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Iana;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Misc;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Oiw;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.TeleTrust;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ internal class CmsSignedHelper
+ {
+ internal static readonly CmsSignedHelper Instance = new CmsSignedHelper();
+
+ private static readonly string EncryptionECDsaWithSha1 = X9ObjectIdentifiers.ECDsaWithSha1.Id;
+ private static readonly string EncryptionECDsaWithSha224 = X9ObjectIdentifiers.ECDsaWithSha224.Id;
+ private static readonly string EncryptionECDsaWithSha256 = X9ObjectIdentifiers.ECDsaWithSha256.Id;
+ private static readonly string EncryptionECDsaWithSha384 = X9ObjectIdentifiers.ECDsaWithSha384.Id;
+ private static readonly string EncryptionECDsaWithSha512 = X9ObjectIdentifiers.ECDsaWithSha512.Id;
+
+ private static readonly IDictionary encryptionAlgs = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ private static readonly IDictionary digestAlgs = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ private static readonly IDictionary digestAliases = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+
+ private static readonly ISet noParams = new HashSet();
+ private static readonly IDictionary ecAlgorithms = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+
+ private static void AddEntries(DerObjectIdentifier oid, string digest, string encryption)
+ {
+ string alias = oid.Id;
+ digestAlgs.Add(alias, digest);
+ encryptionAlgs.Add(alias, encryption);
+ }
+
+ static CmsSignedHelper()
+ {
+ AddEntries(NistObjectIdentifiers.DsaWithSha224, "SHA224", "DSA");
+ AddEntries(NistObjectIdentifiers.DsaWithSha256, "SHA256", "DSA");
+ AddEntries(NistObjectIdentifiers.DsaWithSha384, "SHA384", "DSA");
+ AddEntries(NistObjectIdentifiers.DsaWithSha512, "SHA512", "DSA");
+ AddEntries(OiwObjectIdentifiers.DsaWithSha1, "SHA1", "DSA");
+ AddEntries(OiwObjectIdentifiers.MD4WithRsa, "MD4", "RSA");
+ AddEntries(OiwObjectIdentifiers.MD4WithRsaEncryption, "MD4", "RSA");
+ AddEntries(OiwObjectIdentifiers.MD5WithRsa, "MD5", "RSA");
+ AddEntries(OiwObjectIdentifiers.Sha1WithRsa, "SHA1", "RSA");
+ AddEntries(PkcsObjectIdentifiers.MD2WithRsaEncryption, "MD2", "RSA");
+ AddEntries(PkcsObjectIdentifiers.MD4WithRsaEncryption, "MD4", "RSA");
+ AddEntries(PkcsObjectIdentifiers.MD5WithRsaEncryption, "MD5", "RSA");
+ AddEntries(PkcsObjectIdentifiers.Sha1WithRsaEncryption, "SHA1", "RSA");
+ AddEntries(PkcsObjectIdentifiers.Sha224WithRsaEncryption, "SHA224", "RSA");
+ AddEntries(PkcsObjectIdentifiers.Sha256WithRsaEncryption, "SHA256", "RSA");
+ AddEntries(PkcsObjectIdentifiers.Sha384WithRsaEncryption, "SHA384", "RSA");
+ AddEntries(PkcsObjectIdentifiers.Sha512WithRsaEncryption, "SHA512", "RSA");
+ AddEntries(X9ObjectIdentifiers.ECDsaWithSha1, "SHA1", "ECDSA");
+ AddEntries(X9ObjectIdentifiers.ECDsaWithSha224, "SHA224", "ECDSA");
+ AddEntries(X9ObjectIdentifiers.ECDsaWithSha256, "SHA256", "ECDSA");
+ AddEntries(X9ObjectIdentifiers.ECDsaWithSha384, "SHA384", "ECDSA");
+ AddEntries(X9ObjectIdentifiers.ECDsaWithSha512, "SHA512", "ECDSA");
+ AddEntries(X9ObjectIdentifiers.IdDsaWithSha1, "SHA1", "DSA");
+ AddEntries(EacObjectIdentifiers.id_TA_ECDSA_SHA_1, "SHA1", "ECDSA");
+ AddEntries(EacObjectIdentifiers.id_TA_ECDSA_SHA_224, "SHA224", "ECDSA");
+ AddEntries(EacObjectIdentifiers.id_TA_ECDSA_SHA_256, "SHA256", "ECDSA");
+ AddEntries(EacObjectIdentifiers.id_TA_ECDSA_SHA_384, "SHA384", "ECDSA");
+ AddEntries(EacObjectIdentifiers.id_TA_ECDSA_SHA_512, "SHA512", "ECDSA");
+ AddEntries(EacObjectIdentifiers.id_TA_RSA_v1_5_SHA_1, "SHA1", "RSA");
+ AddEntries(EacObjectIdentifiers.id_TA_RSA_v1_5_SHA_256, "SHA256", "RSA");
+ AddEntries(EacObjectIdentifiers.id_TA_RSA_PSS_SHA_1, "SHA1", "RSAandMGF1");
+ AddEntries(EacObjectIdentifiers.id_TA_RSA_PSS_SHA_256, "SHA256", "RSAandMGF1");
+
+ encryptionAlgs.Add(X9ObjectIdentifiers.IdDsa.Id, "DSA");
+ encryptionAlgs.Add(PkcsObjectIdentifiers.RsaEncryption.Id, "RSA");
+ encryptionAlgs.Add(TeleTrusTObjectIdentifiers.TeleTrusTRsaSignatureAlgorithm, "RSA");
+ encryptionAlgs.Add(X509ObjectIdentifiers.IdEARsa.Id, "RSA");
+ encryptionAlgs.Add(CmsSignedGenerator.EncryptionRsaPss, "RSAandMGF1");
+ encryptionAlgs.Add(CryptoProObjectIdentifiers.GostR3410x94.Id, "GOST3410");
+ encryptionAlgs.Add(CryptoProObjectIdentifiers.GostR3410x2001.Id, "ECGOST3410");
+ encryptionAlgs.Add("1.3.6.1.4.1.5849.1.6.2", "ECGOST3410");
+ encryptionAlgs.Add("1.3.6.1.4.1.5849.1.1.5", "GOST3410");
+
+ digestAlgs.Add(PkcsObjectIdentifiers.MD2.Id, "MD2");
+ digestAlgs.Add(PkcsObjectIdentifiers.MD4.Id, "MD4");
+ digestAlgs.Add(PkcsObjectIdentifiers.MD5.Id, "MD5");
+ digestAlgs.Add(OiwObjectIdentifiers.IdSha1.Id, "SHA1");
+ digestAlgs.Add(NistObjectIdentifiers.IdSha224.Id, "SHA224");
+ digestAlgs.Add(NistObjectIdentifiers.IdSha256.Id, "SHA256");
+ digestAlgs.Add(NistObjectIdentifiers.IdSha384.Id, "SHA384");
+ digestAlgs.Add(NistObjectIdentifiers.IdSha512.Id, "SHA512");
+ digestAlgs.Add(TeleTrusTObjectIdentifiers.RipeMD128.Id, "RIPEMD128");
+ digestAlgs.Add(TeleTrusTObjectIdentifiers.RipeMD160.Id, "RIPEMD160");
+ digestAlgs.Add(TeleTrusTObjectIdentifiers.RipeMD256.Id, "RIPEMD256");
+ digestAlgs.Add(CryptoProObjectIdentifiers.GostR3411.Id, "GOST3411");
+ digestAlgs.Add("1.3.6.1.4.1.5849.1.2.1", "GOST3411");
+
+ digestAliases.Add("SHA1", new string[] { "SHA-1" });
+ digestAliases.Add("SHA224", new string[] { "SHA-224" });
+ digestAliases.Add("SHA256", new string[] { "SHA-256" });
+ digestAliases.Add("SHA384", new string[] { "SHA-384" });
+ digestAliases.Add("SHA512", new string[] { "SHA-512" });
+
+ noParams.Add(CmsSignedGenerator.EncryptionDsa);
+ // noParams.Add(EncryptionECDsa);
+ noParams.Add(EncryptionECDsaWithSha1);
+ noParams.Add(EncryptionECDsaWithSha224);
+ noParams.Add(EncryptionECDsaWithSha256);
+ noParams.Add(EncryptionECDsaWithSha384);
+ noParams.Add(EncryptionECDsaWithSha512);
+
+ ecAlgorithms.Add(CmsSignedGenerator.DigestSha1, EncryptionECDsaWithSha1);
+ ecAlgorithms.Add(CmsSignedGenerator.DigestSha224, EncryptionECDsaWithSha224);
+ ecAlgorithms.Add(CmsSignedGenerator.DigestSha256, EncryptionECDsaWithSha256);
+ ecAlgorithms.Add(CmsSignedGenerator.DigestSha384, EncryptionECDsaWithSha384);
+ ecAlgorithms.Add(CmsSignedGenerator.DigestSha512, EncryptionECDsaWithSha512);
+ }
+
+ /**
+ * Return the digest algorithm using one of the standard JCA string
+ * representations rather than the algorithm identifier (if possible).
+ */
+ internal string GetDigestAlgName(
+ string digestAlgOid)
+ {
+ string algName = (string)digestAlgs[digestAlgOid];
+
+ if (algName != null)
+ {
+ return algName;
+ }
+
+ return digestAlgOid;
+ }
+
+ internal AlgorithmIdentifier GetEncAlgorithmIdentifier(
+ DerObjectIdentifier encOid,
+ Asn1Encodable sigX509Parameters)
+ {
+ if (noParams.Contains(encOid.Id))
+ {
+ return new AlgorithmIdentifier(encOid);
+ }
+
+ return new AlgorithmIdentifier(encOid, sigX509Parameters);
+ }
+
+ internal string[] GetDigestAliases(
+ string algName)
+ {
+ string[] aliases = (string[]) digestAliases[algName];
+
+ return aliases == null ? new String[0] : (string[]) aliases.Clone();
+ }
+
+ /**
+ * Return the digest encryption algorithm using one of the standard
+ * JCA string representations rather than the algorithm identifier (if
+ * possible).
+ */
+ internal string GetEncryptionAlgName(
+ string encryptionAlgOid)
+ {
+ string algName = (string) encryptionAlgs[encryptionAlgOid];
+
+ if (algName != null)
+ {
+ return algName;
+ }
+
+ return encryptionAlgOid;
+ }
+
+ internal IDigest GetDigestInstance(
+ string algorithm)
+ {
+ try
+ {
+ return DigestUtilities.GetDigest(algorithm);
+ }
+ catch (SecurityUtilityException e)
+ {
+ // This is probably superfluous on C#, since no provider infrastructure,
+ // assuming DigestUtilities already knows all the aliases
+ foreach (string alias in GetDigestAliases(algorithm))
+ {
+ try { return DigestUtilities.GetDigest(alias); }
+ catch (SecurityUtilityException) {}
+ }
+ throw e;
+ }
+ }
+
+ internal ISigner GetSignatureInstance(
+ string algorithm)
+ {
+ return SignerUtilities.GetSigner(algorithm);
+ }
+
+ internal IX509Store CreateAttributeStore(
+ string type,
+ Asn1Set certSet)
+ {
+ IList certs = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+
+ if (certSet != null)
+ {
+ foreach (Asn1Encodable ae in certSet)
+ {
+ try
+ {
+ Asn1Object obj = ae.ToAsn1Object();
+
+ if (obj is Asn1TaggedObject)
+ {
+ Asn1TaggedObject tagged = (Asn1TaggedObject)obj;
+
+ if (tagged.TagNo == 2)
+ {
+ certs.Add(
+ new X509V2AttributeCertificate(
+ Asn1Sequence.GetInstance(tagged, false).GetEncoded()));
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ throw new CmsException("can't re-encode attribute certificate!", ex);
+ }
+ }
+ }
+
+ try
+ {
+ return X509StoreFactory.Create(
+ "AttributeCertificate/" + type,
+ new X509CollectionStoreParameters(certs));
+ }
+ catch (ArgumentException e)
+ {
+ throw new CmsException("can't setup the X509Store", e);
+ }
+ }
+
+ internal IX509Store CreateCertificateStore(
+ string type,
+ Asn1Set certSet)
+ {
+ IList certs = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+
+ if (certSet != null)
+ {
+ AddCertsFromSet(certs, certSet);
+ }
+
+ try
+ {
+ return X509StoreFactory.Create(
+ "Certificate/" + type,
+ new X509CollectionStoreParameters(certs));
+ }
+ catch (ArgumentException e)
+ {
+ throw new CmsException("can't setup the X509Store", e);
+ }
+ }
+
+ internal IX509Store CreateCrlStore(
+ string type,
+ Asn1Set crlSet)
+ {
+ IList crls = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+
+ if (crlSet != null)
+ {
+ AddCrlsFromSet(crls, crlSet);
+ }
+
+ try
+ {
+ return X509StoreFactory.Create(
+ "CRL/" + type,
+ new X509CollectionStoreParameters(crls));
+ }
+ catch (ArgumentException e)
+ {
+ throw new CmsException("can't setup the X509Store", e);
+ }
+ }
+
+ private void AddCertsFromSet(
+ IList certs,
+ Asn1Set certSet)
+ {
+ X509CertificateParser cf = new X509CertificateParser();
+
+ foreach (Asn1Encodable ae in certSet)
+ {
+ try
+ {
+ Asn1Object obj = ae.ToAsn1Object();
+
+ if (obj is Asn1Sequence)
+ {
+ // TODO Build certificate directly from sequence?
+ certs.Add(cf.ReadCertificate(obj.GetEncoded()));
+ }
+ }
+ catch (Exception ex)
+ {
+ throw new CmsException("can't re-encode certificate!", ex);
+ }
+ }
+ }
+
+ private void AddCrlsFromSet(
+ IList crls,
+ Asn1Set crlSet)
+ {
+ X509CrlParser cf = new X509CrlParser();
+
+ foreach (Asn1Encodable ae in crlSet)
+ {
+ try
+ {
+ // TODO Build CRL directly from ae.ToAsn1Object()?
+ crls.Add(cf.ReadCrl(ae.GetEncoded()));
+ }
+ catch (Exception ex)
+ {
+ throw new CmsException("can't re-encode CRL!", ex);
+ }
+ }
+ }
+
+ internal AlgorithmIdentifier FixAlgID(
+ AlgorithmIdentifier algId)
+ {
+ if (algId.Parameters == null)
+ return new AlgorithmIdentifier(algId.Algorithm, DerNull.Instance);
+
+ return algId;
+ }
+
+ internal string GetEncOid(
+ AsymmetricKeyParameter key,
+ string digestOID)
+ {
+ string encOID = null;
+
+ if (key is RsaKeyParameters)
+ {
+ if (!((RsaKeyParameters)key).IsPrivate)
+ throw new ArgumentException("Expected RSA private key");
+
+ encOID = CmsSignedGenerator.EncryptionRsa;
+ }
+ else if (key is DsaPrivateKeyParameters)
+ {
+ if (digestOID.Equals(CmsSignedGenerator.DigestSha1))
+ {
+ encOID = CmsSignedGenerator.EncryptionDsa;
+ }
+ else if (digestOID.Equals(CmsSignedGenerator.DigestSha224))
+ {
+ encOID = NistObjectIdentifiers.DsaWithSha224.Id;
+ }
+ else if (digestOID.Equals(CmsSignedGenerator.DigestSha256))
+ {
+ encOID = NistObjectIdentifiers.DsaWithSha256.Id;
+ }
+ else if (digestOID.Equals(CmsSignedGenerator.DigestSha384))
+ {
+ encOID = NistObjectIdentifiers.DsaWithSha384.Id;
+ }
+ else if (digestOID.Equals(CmsSignedGenerator.DigestSha512))
+ {
+ encOID = NistObjectIdentifiers.DsaWithSha512.Id;
+ }
+ else
+ {
+ throw new ArgumentException("can't mix DSA with anything but SHA1/SHA2");
+ }
+ }
+ else if (key is ECPrivateKeyParameters)
+ {
+ ECPrivateKeyParameters ecPrivKey = (ECPrivateKeyParameters)key;
+ string algName = ecPrivKey.AlgorithmName;
+
+ if (algName == "ECGOST3410")
+ {
+ encOID = CmsSignedGenerator.EncryptionECGost3410;
+ }
+ else
+ {
+ // TODO Should we insist on algName being one of "EC" or "ECDSA", as Java does?
+ encOID = (string)ecAlgorithms[digestOID];
+
+ if (encOID == null)
+ throw new ArgumentException("can't mix ECDSA with anything but SHA family digests");
+ }
+ }
+ else if (key is Gost3410PrivateKeyParameters)
+ {
+ encOID = CmsSignedGenerator.EncryptionGost3410;
+ }
+ else
+ {
+ throw new ArgumentException("Unknown algorithm in CmsSignedGenerator.GetEncOid");
+ }
+
+ return encOID;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSSignedHelper.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSSignedHelper.cs.meta
new file mode 100644
index 00000000..0f4d986b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSSignedHelper.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: f0f0baf6a26286f41b9a981fa79313a2
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSStreamException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSStreamException.cs
new file mode 100644
index 00000000..ef719d3a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSStreamException.cs
@@ -0,0 +1,33 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class CmsStreamException
+ : IOException
+ {
+ public CmsStreamException()
+ {
+ }
+
+ public CmsStreamException(
+ string name)
+ : base(name)
+ {
+ }
+
+ public CmsStreamException(
+ string name,
+ Exception e)
+ : base(name, e)
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSStreamException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSStreamException.cs.meta
new file mode 100644
index 00000000..811e76dd
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSStreamException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 65c03251f868f0c4eacde295bcfa8a55
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSTypedStream.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSTypedStream.cs
new file mode 100644
index 00000000..c8b0529c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSTypedStream.cs
@@ -0,0 +1,76 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ public class CmsTypedStream
+ {
+ private const int BufferSize = 32 * 1024;
+
+ private readonly string _oid;
+ private readonly Stream _in;
+
+ public CmsTypedStream(
+ Stream inStream)
+ : this(PkcsObjectIdentifiers.Data.Id, inStream, BufferSize)
+ {
+ }
+
+ public CmsTypedStream(
+ string oid,
+ Stream inStream)
+ : this(oid, inStream, BufferSize)
+ {
+ }
+
+ public CmsTypedStream(
+ string oid,
+ Stream inStream,
+ int bufSize)
+ {
+ _oid = oid;
+#if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE
+ _in = new FullReaderStream(inStream);
+#else
+ _in = new FullReaderStream(new BufferedStream(inStream, bufSize));
+#endif
+ }
+
+ public string ContentType
+ {
+ get { return _oid; }
+ }
+
+ public Stream ContentStream
+ {
+ get { return _in; }
+ }
+
+ public void Drain()
+ {
+ Streams.Drain(_in);
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(_in);
+ }
+
+ private class FullReaderStream : FilterStream
+ {
+ internal FullReaderStream(Stream input)
+ : base(input)
+ {
+ }
+
+ public override int Read(byte[] buf, int off, int len)
+ {
+ return Streams.ReadFully(base.s, buf, off, len);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSTypedStream.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSTypedStream.cs.meta
new file mode 100644
index 00000000..0c621f89
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSTypedStream.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 7cb2eb2d53bfddc48ada720945f16136
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSUtils.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSUtils.cs
new file mode 100644
index 00000000..b1a2b937
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSUtils.cs
@@ -0,0 +1,190 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ internal class CmsUtilities
+ {
+ // TODO Is there a .NET equivalent to this?
+// private static readonly Runtime RUNTIME = Runtime.getRuntime();
+
+ internal static int MaximumMemory
+ {
+ get
+ {
+ // TODO Is there a .NET equivalent to this?
+ long maxMem = int.MaxValue;//RUNTIME.maxMemory();
+
+ if (maxMem > int.MaxValue)
+ {
+ return int.MaxValue;
+ }
+
+ return (int)maxMem;
+ }
+ }
+
+ internal static ContentInfo ReadContentInfo(
+ byte[] input)
+ {
+ // enforce limit checking as from a byte array
+ return ReadContentInfo(new Asn1InputStream(input));
+ }
+
+ internal static ContentInfo ReadContentInfo(
+ Stream input)
+ {
+ // enforce some limit checking
+ return ReadContentInfo(new Asn1InputStream(input, MaximumMemory));
+ }
+
+ private static ContentInfo ReadContentInfo(
+ Asn1InputStream aIn)
+ {
+ try
+ {
+ return ContentInfo.GetInstance(aIn.ReadObject());
+ }
+ catch (IOException e)
+ {
+ throw new CmsException("IOException reading content.", e);
+ }
+ catch (InvalidCastException e)
+ {
+ throw new CmsException("Malformed content.", e);
+ }
+ catch (ArgumentException e)
+ {
+ throw new CmsException("Malformed content.", e);
+ }
+ }
+
+ public static byte[] StreamToByteArray(
+ Stream inStream)
+ {
+ return Streams.ReadAll(inStream);
+ }
+
+ public static byte[] StreamToByteArray(
+ Stream inStream,
+ int limit)
+ {
+ return Streams.ReadAllLimited(inStream, limit);
+ }
+
+ public static IList GetCertificatesFromStore(
+ IX509Store certStore)
+ {
+ try
+ {
+ IList certs = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+
+ if (certStore != null)
+ {
+ foreach (X509Certificate c in certStore.GetMatches(null))
+ {
+ certs.Add(
+ X509CertificateStructure.GetInstance(
+ Asn1Object.FromByteArray(c.GetEncoded())));
+ }
+ }
+
+ return certs;
+ }
+ catch (CertificateEncodingException e)
+ {
+ throw new CmsException("error encoding certs", e);
+ }
+ catch (Exception e)
+ {
+ throw new CmsException("error processing certs", e);
+ }
+ }
+
+ public static IList GetCrlsFromStore(
+ IX509Store crlStore)
+ {
+ try
+ {
+ IList crls = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+
+ if (crlStore != null)
+ {
+ foreach (X509Crl c in crlStore.GetMatches(null))
+ {
+ crls.Add(
+ CertificateList.GetInstance(
+ Asn1Object.FromByteArray(c.GetEncoded())));
+ }
+ }
+
+ return crls;
+ }
+ catch (CrlException e)
+ {
+ throw new CmsException("error encoding crls", e);
+ }
+ catch (Exception e)
+ {
+ throw new CmsException("error processing crls", e);
+ }
+ }
+
+ public static Asn1Set CreateBerSetFromList(
+ IList berObjects)
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector();
+
+ foreach (Asn1Encodable ae in berObjects)
+ {
+ v.Add(ae);
+ }
+
+ return new BerSet(v);
+ }
+
+ public static Asn1Set CreateDerSetFromList(
+ IList derObjects)
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector();
+
+ foreach (Asn1Encodable ae in derObjects)
+ {
+ v.Add(ae);
+ }
+
+ return new DerSet(v);
+ }
+
+ internal static Stream CreateBerOctetOutputStream(Stream s, int tagNo, bool isExplicit, int bufferSize)
+ {
+ BerOctetStringGenerator octGen = new BerOctetStringGenerator(s, tagNo, isExplicit);
+ return octGen.GetOctetOutputStream(bufferSize);
+ }
+
+ internal static TbsCertificateStructure GetTbsCertificateStructure(X509Certificate cert)
+ {
+ return TbsCertificateStructure.GetInstance(Asn1Object.FromByteArray(cert.GetTbsCertificate()));
+ }
+
+ internal static IssuerAndSerialNumber GetIssuerAndSerialNumber(X509Certificate cert)
+ {
+ TbsCertificateStructure tbsCert = GetTbsCertificateStructure(cert);
+ return new IssuerAndSerialNumber(tbsCert.Issuer, tbsCert.SerialNumber.Value);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSUtils.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSUtils.cs.meta
new file mode 100644
index 00000000..10f2e314
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CMSUtils.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 67354a24f57564445b672cc8ecb0d55a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CounterSignatureDigestCalculator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CounterSignatureDigestCalculator.cs
new file mode 100644
index 00000000..4f8611ee
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CounterSignatureDigestCalculator.cs
@@ -0,0 +1,32 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ internal class CounterSignatureDigestCalculator
+ : IDigestCalculator
+ {
+ private readonly string alg;
+ private readonly byte[] data;
+
+ internal CounterSignatureDigestCalculator(
+ string alg,
+ byte[] data)
+ {
+ this.alg = alg;
+ this.data = data;
+ }
+
+ public byte[] GetDigest()
+ {
+ IDigest digest = CmsSignedHelper.Instance.GetDigestInstance(alg);
+ return DigestUtilities.DoFinal(digest, data);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CounterSignatureDigestCalculator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CounterSignatureDigestCalculator.cs.meta
new file mode 100644
index 00000000..b2cde11b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/CounterSignatureDigestCalculator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0dc404fbdaec35e45ba416368a1f3d44
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/DefaultAuthenticatedAttributeTableGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/DefaultAuthenticatedAttributeTableGenerator.cs
new file mode 100644
index 00000000..b588bdee
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/DefaultAuthenticatedAttributeTableGenerator.cs
@@ -0,0 +1,94 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ /**
+ * Default authenticated attributes generator.
+ */
+ public class DefaultAuthenticatedAttributeTableGenerator
+ : CmsAttributeTableGenerator
+ {
+ private readonly IDictionary table;
+
+ /**
+ * Initialise to use all defaults
+ */
+ public DefaultAuthenticatedAttributeTableGenerator()
+ {
+ table = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ }
+
+ /**
+ * Initialise with some extra attributes or overrides.
+ *
+ * @param attributeTable initial attribute table to use.
+ */
+ public DefaultAuthenticatedAttributeTableGenerator(
+ AttributeTable attributeTable)
+ {
+ if (attributeTable != null)
+ {
+ table = attributeTable.ToDictionary();
+ }
+ else
+ {
+ table = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ }
+ }
+
+ /**
+ * Create a standard attribute table from the passed in parameters - this will
+ * normally include contentType and messageDigest. If the constructor
+ * using an AttributeTable was used, entries in it for contentType and
+ * messageDigest will override the generated ones.
+ *
+ * @param parameters source parameters for table generation.
+ *
+ * @return a filled in IDictionary of attributes.
+ */
+ protected virtual IDictionary CreateStandardAttributeTable(
+ IDictionary parameters)
+ {
+ IDictionary std = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(table);
+
+ if (!std.Contains(CmsAttributes.ContentType))
+ {
+ DerObjectIdentifier contentType = (DerObjectIdentifier)
+ parameters[CmsAttributeTableParameter.ContentType];
+ Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(CmsAttributes.ContentType,
+ new DerSet(contentType));
+ std[attr.AttrType] = attr;
+ }
+
+ if (!std.Contains(CmsAttributes.MessageDigest))
+ {
+ byte[] messageDigest = (byte[])parameters[CmsAttributeTableParameter.Digest];
+ Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(CmsAttributes.MessageDigest,
+ new DerSet(new DerOctetString(messageDigest)));
+ std[attr.AttrType] = attr;
+ }
+
+ return std;
+ }
+
+ /**
+ * @param parameters source parameters
+ * @return the populated attribute table
+ */
+ public virtual AttributeTable GetAttributes(
+ IDictionary parameters)
+ {
+ IDictionary table = CreateStandardAttributeTable(parameters);
+ return new AttributeTable(table);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/DefaultAuthenticatedAttributeTableGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/DefaultAuthenticatedAttributeTableGenerator.cs.meta
new file mode 100644
index 00000000..330e0fdd
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/DefaultAuthenticatedAttributeTableGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0ff46025627cc3f4db1238e4c51595a1
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/DefaultSignedAttributeTableGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/DefaultSignedAttributeTableGenerator.cs
new file mode 100644
index 00000000..44a4f04f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/DefaultSignedAttributeTableGenerator.cs
@@ -0,0 +1,128 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ /**
+ * Default signed attributes generator.
+ */
+ public class DefaultSignedAttributeTableGenerator
+ : CmsAttributeTableGenerator
+ {
+ private readonly IDictionary table;
+
+ /**
+ * Initialise to use all defaults
+ */
+ public DefaultSignedAttributeTableGenerator()
+ {
+ table = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ }
+
+ /**
+ * Initialise with some extra attributes or overrides.
+ *
+ * @param attributeTable initial attribute table to use.
+ */
+ public DefaultSignedAttributeTableGenerator(
+ AttributeTable attributeTable)
+ {
+ if (attributeTable != null)
+ {
+ table = attributeTable.ToDictionary();
+ }
+ else
+ {
+ table = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ }
+ }
+
+#if SILVERLIGHT || PORTABLE || NETFX_CORE
+ /**
+ * Create a standard attribute table from the passed in parameters - this will
+ * normally include contentType, signingTime, and messageDigest. If the constructor
+ * using an AttributeTable was used, entries in it for contentType, signingTime, and
+ * messageDigest will override the generated ones.
+ *
+ * @param parameters source parameters for table generation.
+ *
+ * @return a filled in Hashtable of attributes.
+ */
+ protected virtual IDictionary createStandardAttributeTable(
+ IDictionary parameters)
+ {
+ IDictionary std = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(table);
+ DoCreateStandardAttributeTable(parameters, std);
+ return std;
+ }
+#else
+ /**
+ * Create a standard attribute table from the passed in parameters - this will
+ * normally include contentType, signingTime, and messageDigest. If the constructor
+ * using an AttributeTable was used, entries in it for contentType, signingTime, and
+ * messageDigest will override the generated ones.
+ *
+ * @param parameters source parameters for table generation.
+ *
+ * @return a filled in Hashtable of attributes.
+ */
+ protected virtual Hashtable createStandardAttributeTable(
+ IDictionary parameters)
+ {
+ Hashtable std = new Hashtable(table);
+ DoCreateStandardAttributeTable(parameters, std);
+ return std;
+ }
+#endif
+
+ private void DoCreateStandardAttributeTable(IDictionary parameters, IDictionary std)
+ {
+ // contentType will be absent if we're trying to generate a counter signature.
+ if (parameters.Contains(CmsAttributeTableParameter.ContentType))
+ {
+ if (!std.Contains(CmsAttributes.ContentType))
+ {
+ DerObjectIdentifier contentType = (DerObjectIdentifier)
+ parameters[CmsAttributeTableParameter.ContentType];
+ Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(CmsAttributes.ContentType,
+ new DerSet(contentType));
+ std[attr.AttrType] = attr;
+ }
+ }
+
+ if (!std.Contains(CmsAttributes.SigningTime))
+ {
+ Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(CmsAttributes.SigningTime,
+ new DerSet(new Time(DateTime.UtcNow)));
+ std[attr.AttrType] = attr;
+ }
+
+ if (!std.Contains(CmsAttributes.MessageDigest))
+ {
+ byte[] messageDigest = (byte[])parameters[CmsAttributeTableParameter.Digest];
+ Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(CmsAttributes.MessageDigest,
+ new DerSet(new DerOctetString(messageDigest)));
+ std[attr.AttrType] = attr;
+ }
+ }
+
+ /**
+ * @param parameters source parameters
+ * @return the populated attribute table
+ */
+ public virtual AttributeTable GetAttributes(
+ IDictionary parameters)
+ {
+ IDictionary table = createStandardAttributeTable(parameters);
+ return new AttributeTable(table);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/DefaultSignedAttributeTableGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/DefaultSignedAttributeTableGenerator.cs.meta
new file mode 100644
index 00000000..a5f366d1
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/DefaultSignedAttributeTableGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0436e2d77a8dae845a14d9535027953c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/IDigestCalculator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/IDigestCalculator.cs
new file mode 100644
index 00000000..e88c7e41
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/IDigestCalculator.cs
@@ -0,0 +1,13 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ internal interface IDigestCalculator
+ {
+ byte[] GetDigest();
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/IDigestCalculator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/IDigestCalculator.cs.meta
new file mode 100644
index 00000000..7c94d2a5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/IDigestCalculator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 5d9dc3e4ade64ee40b172d9d67f0830c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KEKRecipientInfoGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KEKRecipientInfoGenerator.cs
new file mode 100644
index 00000000..703f62f6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KEKRecipientInfoGenerator.cs
@@ -0,0 +1,142 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Kisa;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Ntt;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ internal class KekRecipientInfoGenerator : RecipientInfoGenerator
+ {
+ private static readonly CmsEnvelopedHelper Helper = CmsEnvelopedHelper.Instance;
+
+ private KeyParameter keyEncryptionKey;
+ // TODO Can get this from keyEncryptionKey?
+ private string keyEncryptionKeyOID;
+ private KekIdentifier kekIdentifier;
+
+ // Derived
+ private AlgorithmIdentifier keyEncryptionAlgorithm;
+
+ internal KekRecipientInfoGenerator()
+ {
+ }
+
+ internal KekIdentifier KekIdentifier
+ {
+ set { this.kekIdentifier = value; }
+ }
+
+ internal KeyParameter KeyEncryptionKey
+ {
+ set
+ {
+ this.keyEncryptionKey = value;
+ this.keyEncryptionAlgorithm = DetermineKeyEncAlg(keyEncryptionKeyOID, keyEncryptionKey);
+ }
+ }
+
+ internal string KeyEncryptionKeyOID
+ {
+ set { this.keyEncryptionKeyOID = value; }
+ }
+
+ public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
+ {
+ byte[] keyBytes = contentEncryptionKey.GetKey();
+
+ IWrapper keyWrapper = Helper.CreateWrapper(keyEncryptionAlgorithm.Algorithm.Id);
+ keyWrapper.Init(true, new ParametersWithRandom(keyEncryptionKey, random));
+ Asn1OctetString encryptedKey = new DerOctetString(
+ keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));
+
+ return new RecipientInfo(new KekRecipientInfo(kekIdentifier, keyEncryptionAlgorithm, encryptedKey));
+ }
+
+ private static AlgorithmIdentifier DetermineKeyEncAlg(
+ string algorithm, KeyParameter key)
+ {
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(algorithm, "DES"))
+ {
+ return new AlgorithmIdentifier(
+ PkcsObjectIdentifiers.IdAlgCms3DesWrap,
+ DerNull.Instance);
+ }
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(algorithm, "RC2"))
+ {
+ return new AlgorithmIdentifier(
+ PkcsObjectIdentifiers.IdAlgCmsRC2Wrap,
+ new DerInteger(58));
+ }
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(algorithm, "AES"))
+ {
+ int length = key.GetKey().Length * 8;
+ DerObjectIdentifier wrapOid;
+
+ if (length == 128)
+ {
+ wrapOid = NistObjectIdentifiers.IdAes128Wrap;
+ }
+ else if (length == 192)
+ {
+ wrapOid = NistObjectIdentifiers.IdAes192Wrap;
+ }
+ else if (length == 256)
+ {
+ wrapOid = NistObjectIdentifiers.IdAes256Wrap;
+ }
+ else
+ {
+ throw new ArgumentException("illegal keysize in AES");
+ }
+
+ return new AlgorithmIdentifier(wrapOid); // parameters absent
+ }
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(algorithm, "SEED"))
+ {
+ // parameters absent
+ return new AlgorithmIdentifier(KisaObjectIdentifiers.IdNpkiAppCmsSeedWrap);
+ }
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(algorithm, "CAMELLIA"))
+ {
+ int length = key.GetKey().Length * 8;
+ DerObjectIdentifier wrapOid;
+
+ if (length == 128)
+ {
+ wrapOid = NttObjectIdentifiers.IdCamellia128Wrap;
+ }
+ else if (length == 192)
+ {
+ wrapOid = NttObjectIdentifiers.IdCamellia192Wrap;
+ }
+ else if (length == 256)
+ {
+ wrapOid = NttObjectIdentifiers.IdCamellia256Wrap;
+ }
+ else
+ {
+ throw new ArgumentException("illegal keysize in Camellia");
+ }
+
+ return new AlgorithmIdentifier(wrapOid); // parameters must be absent
+ }
+ else
+ {
+ throw new ArgumentException("unknown algorithm");
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KEKRecipientInfoGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KEKRecipientInfoGenerator.cs.meta
new file mode 100644
index 00000000..e0fa9ab1
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KEKRecipientInfoGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 764accd23d3d15147a4cf8f10a88f687
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KEKRecipientInformation.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KEKRecipientInformation.cs
new file mode 100644
index 00000000..efe706a5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KEKRecipientInformation.cs
@@ -0,0 +1,66 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ /**
+ * the RecipientInfo class for a recipient who has been sent a message
+ * encrypted using a secret key known to the other side.
+ */
+ public class KekRecipientInformation
+ : RecipientInformation
+ {
+ private KekRecipientInfo info;
+
+ internal KekRecipientInformation(
+ KekRecipientInfo info,
+ CmsSecureReadable secureReadable)
+ : base(info.KeyEncryptionAlgorithm, secureReadable)
+ {
+ this.info = info;
+ this.rid = new RecipientID();
+
+ KekIdentifier kekId = info.KekID;
+
+ rid.KeyIdentifier = kekId.KeyIdentifier.GetOctets();
+ }
+
+ /**
+ * decrypt the content and return an input stream.
+ */
+ public override CmsTypedStream GetContentStream(
+ ICipherParameters key)
+ {
+ try
+ {
+ byte[] encryptedKey = info.EncryptedKey.GetOctets();
+ IWrapper keyWrapper = WrapperUtilities.GetWrapper(keyEncAlg.Algorithm.Id);
+
+ keyWrapper.Init(false, key);
+
+ KeyParameter sKey = ParameterUtilities.CreateKeyParameter(
+ GetContentAlgorithmName(), keyWrapper.Unwrap(encryptedKey, 0, encryptedKey.Length));
+
+ return GetContentFromSessionKey(sKey);
+ }
+ catch (SecurityUtilityException e)
+ {
+ throw new CmsException("couldn't create cipher.", e);
+ }
+ catch (InvalidKeyException e)
+ {
+ throw new CmsException("key invalid in message.", e);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KEKRecipientInformation.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KEKRecipientInformation.cs.meta
new file mode 100644
index 00000000..93dfbc92
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KEKRecipientInformation.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a668dd24874b8c047b20f583f86df772
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KeyAgreeRecipientInfoGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KeyAgreeRecipientInfoGenerator.cs
new file mode 100644
index 00000000..614ca5ba
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KeyAgreeRecipientInfoGenerator.cs
@@ -0,0 +1,175 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms.Ecc;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ internal class KeyAgreeRecipientInfoGenerator : RecipientInfoGenerator
+ {
+ private static readonly CmsEnvelopedHelper Helper = CmsEnvelopedHelper.Instance;
+
+ private DerObjectIdentifier keyAgreementOID;
+ private DerObjectIdentifier keyEncryptionOID;
+ private IList recipientCerts;
+ private AsymmetricCipherKeyPair senderKeyPair;
+
+ internal KeyAgreeRecipientInfoGenerator()
+ {
+ }
+
+ internal DerObjectIdentifier KeyAgreementOID
+ {
+ set { this.keyAgreementOID = value; }
+ }
+
+ internal DerObjectIdentifier KeyEncryptionOID
+ {
+ set { this.keyEncryptionOID = value; }
+ }
+
+ internal ICollection RecipientCerts
+ {
+ set { this.recipientCerts = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(value); }
+ }
+
+ internal AsymmetricCipherKeyPair SenderKeyPair
+ {
+ set { this.senderKeyPair = value; }
+ }
+
+ public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
+ {
+ byte[] keyBytes = contentEncryptionKey.GetKey();
+
+ AsymmetricKeyParameter senderPublicKey = senderKeyPair.Public;
+ ICipherParameters senderPrivateParams = senderKeyPair.Private;
+
+
+ OriginatorIdentifierOrKey originator;
+ try
+ {
+ originator = new OriginatorIdentifierOrKey(
+ CreateOriginatorPublicKey(senderPublicKey));
+ }
+ catch (IOException e)
+ {
+ throw new InvalidKeyException("cannot extract originator public key: " + e);
+ }
+
+
+ Asn1OctetString ukm = null;
+ if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
+ {
+ try
+ {
+ IAsymmetricCipherKeyPairGenerator ephemKPG =
+ GeneratorUtilities.GetKeyPairGenerator(keyAgreementOID);
+ ephemKPG.Init(
+ ((ECPublicKeyParameters)senderPublicKey).CreateKeyGenerationParameters(random));
+
+ AsymmetricCipherKeyPair ephemKP = ephemKPG.GenerateKeyPair();
+
+ ukm = new DerOctetString(
+ new MQVuserKeyingMaterial(
+ CreateOriginatorPublicKey(ephemKP.Public), null));
+
+ senderPrivateParams = new MqvPrivateParameters(
+ (ECPrivateKeyParameters)senderPrivateParams,
+ (ECPrivateKeyParameters)ephemKP.Private,
+ (ECPublicKeyParameters)ephemKP.Public);
+ }
+ catch (IOException e)
+ {
+ throw new InvalidKeyException("cannot extract MQV ephemeral public key: " + e);
+ }
+ catch (SecurityUtilityException e)
+ {
+ throw new InvalidKeyException("cannot determine MQV ephemeral key pair parameters from public key: " + e);
+ }
+ }
+
+
+ DerSequence paramSeq = new DerSequence(
+ keyEncryptionOID,
+ DerNull.Instance);
+ AlgorithmIdentifier keyEncAlg = new AlgorithmIdentifier(keyAgreementOID, paramSeq);
+
+
+ Asn1EncodableVector recipientEncryptedKeys = new Asn1EncodableVector();
+ foreach (X509Certificate recipientCert in recipientCerts)
+ {
+ TbsCertificateStructure tbsCert;
+ try
+ {
+ tbsCert = TbsCertificateStructure.GetInstance(
+ Asn1Object.FromByteArray(recipientCert.GetTbsCertificate()));
+ }
+ catch (Exception)
+ {
+ throw new ArgumentException("can't extract TBS structure from certificate");
+ }
+
+ // TODO Should there be a SubjectKeyIdentifier-based alternative?
+ IssuerAndSerialNumber issuerSerial = new IssuerAndSerialNumber(
+ tbsCert.Issuer, tbsCert.SerialNumber.Value);
+ KeyAgreeRecipientIdentifier karid = new KeyAgreeRecipientIdentifier(issuerSerial);
+
+ ICipherParameters recipientPublicParams = recipientCert.GetPublicKey();
+ if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
+ {
+ recipientPublicParams = new MqvPublicParameters(
+ (ECPublicKeyParameters)recipientPublicParams,
+ (ECPublicKeyParameters)recipientPublicParams);
+ }
+
+ // Use key agreement to choose a wrap key for this recipient
+ IBasicAgreement keyAgreement = AgreementUtilities.GetBasicAgreementWithKdf(
+ keyAgreementOID, keyEncryptionOID.Id);
+ keyAgreement.Init(new ParametersWithRandom(senderPrivateParams, random));
+ BigInteger agreedValue = keyAgreement.CalculateAgreement(recipientPublicParams);
+
+ int keyEncryptionKeySize = GeneratorUtilities.GetDefaultKeySize(keyEncryptionOID) / 8;
+ byte[] keyEncryptionKeyBytes = X9IntegerConverter.IntegerToBytes(agreedValue, keyEncryptionKeySize);
+ KeyParameter keyEncryptionKey = ParameterUtilities.CreateKeyParameter(
+ keyEncryptionOID, keyEncryptionKeyBytes);
+
+ // Wrap the content encryption key with the agreement key
+ IWrapper keyWrapper = Helper.CreateWrapper(keyEncryptionOID.Id);
+ keyWrapper.Init(true, new ParametersWithRandom(keyEncryptionKey, random));
+ byte[] encryptedKeyBytes = keyWrapper.Wrap(keyBytes, 0, keyBytes.Length);
+
+ Asn1OctetString encryptedKey = new DerOctetString(encryptedKeyBytes);
+
+ recipientEncryptedKeys.Add(new RecipientEncryptedKey(karid, encryptedKey));
+ }
+
+ return new RecipientInfo(new KeyAgreeRecipientInfo(originator, ukm, keyEncAlg,
+ new DerSequence(recipientEncryptedKeys)));
+ }
+
+ private static OriginatorPublicKey CreateOriginatorPublicKey(
+ AsymmetricKeyParameter publicKey)
+ {
+ SubjectPublicKeyInfo spki = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
+ return new OriginatorPublicKey(
+ new AlgorithmIdentifier(spki.AlgorithmID.Algorithm, DerNull.Instance),
+ spki.PublicKeyData.GetBytes());
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KeyAgreeRecipientInfoGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KeyAgreeRecipientInfoGenerator.cs.meta
new file mode 100644
index 00000000..ced2b2fe
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KeyAgreeRecipientInfoGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 123a2fced714ba64db37e4e782038e10
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KeyAgreeRecipientInformation.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KeyAgreeRecipientInformation.cs
new file mode 100644
index 00000000..b6106e48
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KeyAgreeRecipientInformation.cs
@@ -0,0 +1,230 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms.Ecc;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ /**
+ * the RecipientInfo class for a recipient who has been sent a message
+ * encrypted using key agreement.
+ */
+ public class KeyAgreeRecipientInformation
+ : RecipientInformation
+ {
+ private KeyAgreeRecipientInfo info;
+ private Asn1OctetString encryptedKey;
+
+ internal static void ReadRecipientInfo(IList infos, KeyAgreeRecipientInfo info,
+ CmsSecureReadable secureReadable)
+ {
+ try
+ {
+ foreach (Asn1Encodable rek in info.RecipientEncryptedKeys)
+ {
+ RecipientEncryptedKey id = RecipientEncryptedKey.GetInstance(rek.ToAsn1Object());
+
+ RecipientID rid = new RecipientID();
+
+ Asn1.Cms.KeyAgreeRecipientIdentifier karid = id.Identifier;
+
+ Asn1.Cms.IssuerAndSerialNumber iAndSN = karid.IssuerAndSerialNumber;
+ if (iAndSN != null)
+ {
+ rid.Issuer = iAndSN.Name;
+ rid.SerialNumber = iAndSN.SerialNumber.Value;
+ }
+ else
+ {
+ Asn1.Cms.RecipientKeyIdentifier rKeyID = karid.RKeyID;
+
+ // Note: 'date' and 'other' fields of RecipientKeyIdentifier appear to be only informational
+
+ rid.SubjectKeyIdentifier = rKeyID.SubjectKeyIdentifier.GetOctets();
+ }
+
+ infos.Add(new KeyAgreeRecipientInformation(info, rid, id.EncryptedKey,
+ secureReadable));
+ }
+ }
+ catch (IOException e)
+ {
+ throw new ArgumentException("invalid rid in KeyAgreeRecipientInformation", e);
+ }
+ }
+
+ internal KeyAgreeRecipientInformation(
+ KeyAgreeRecipientInfo info,
+ RecipientID rid,
+ Asn1OctetString encryptedKey,
+ CmsSecureReadable secureReadable)
+ : base(info.KeyEncryptionAlgorithm, secureReadable)
+ {
+ this.info = info;
+ this.rid = rid;
+ this.encryptedKey = encryptedKey;
+ }
+
+ private AsymmetricKeyParameter GetSenderPublicKey(
+ AsymmetricKeyParameter receiverPrivateKey,
+ OriginatorIdentifierOrKey originator)
+ {
+ OriginatorPublicKey opk = originator.OriginatorPublicKey;
+ if (opk != null)
+ {
+ return GetPublicKeyFromOriginatorPublicKey(receiverPrivateKey, opk);
+ }
+
+ OriginatorID origID = new OriginatorID();
+
+ Asn1.Cms.IssuerAndSerialNumber iAndSN = originator.IssuerAndSerialNumber;
+ if (iAndSN != null)
+ {
+ origID.Issuer = iAndSN.Name;
+ origID.SerialNumber = iAndSN.SerialNumber.Value;
+ }
+ else
+ {
+ SubjectKeyIdentifier ski = originator.SubjectKeyIdentifier;
+
+ origID.SubjectKeyIdentifier = ski.GetKeyIdentifier();
+ }
+
+ return GetPublicKeyFromOriginatorID(origID);
+ }
+
+ private AsymmetricKeyParameter GetPublicKeyFromOriginatorPublicKey(
+ AsymmetricKeyParameter receiverPrivateKey,
+ OriginatorPublicKey originatorPublicKey)
+ {
+ PrivateKeyInfo privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(receiverPrivateKey);
+ SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo(
+ privInfo.PrivateKeyAlgorithm,
+ originatorPublicKey.PublicKey.GetBytes());
+ return PublicKeyFactory.CreateKey(pubInfo);
+ }
+
+ private AsymmetricKeyParameter GetPublicKeyFromOriginatorID(
+ OriginatorID origID)
+ {
+ // TODO Support all alternatives for OriginatorIdentifierOrKey
+ // see RFC 3852 6.2.2
+ throw new CmsException("No support for 'originator' as IssuerAndSerialNumber or SubjectKeyIdentifier");
+ }
+
+ private KeyParameter CalculateAgreedWrapKey(
+ string wrapAlg,
+ AsymmetricKeyParameter senderPublicKey,
+ AsymmetricKeyParameter receiverPrivateKey)
+ {
+ DerObjectIdentifier agreeAlgID = keyEncAlg.Algorithm;
+
+ ICipherParameters senderPublicParams = senderPublicKey;
+ ICipherParameters receiverPrivateParams = receiverPrivateKey;
+
+ if (agreeAlgID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
+ {
+ byte[] ukmEncoding = info.UserKeyingMaterial.GetOctets();
+ MQVuserKeyingMaterial ukm = MQVuserKeyingMaterial.GetInstance(
+ Asn1Object.FromByteArray(ukmEncoding));
+
+ AsymmetricKeyParameter ephemeralKey = GetPublicKeyFromOriginatorPublicKey(
+ receiverPrivateKey, ukm.EphemeralPublicKey);
+
+ senderPublicParams = new MqvPublicParameters(
+ (ECPublicKeyParameters)senderPublicParams,
+ (ECPublicKeyParameters)ephemeralKey);
+ receiverPrivateParams = new MqvPrivateParameters(
+ (ECPrivateKeyParameters)receiverPrivateParams,
+ (ECPrivateKeyParameters)receiverPrivateParams);
+ }
+
+ IBasicAgreement agreement = AgreementUtilities.GetBasicAgreementWithKdf(
+ agreeAlgID, wrapAlg);
+ agreement.Init(receiverPrivateParams);
+ BigInteger agreedValue = agreement.CalculateAgreement(senderPublicParams);
+
+ int wrapKeySize = GeneratorUtilities.GetDefaultKeySize(wrapAlg) / 8;
+ byte[] wrapKeyBytes = X9IntegerConverter.IntegerToBytes(agreedValue, wrapKeySize);
+ return ParameterUtilities.CreateKeyParameter(wrapAlg, wrapKeyBytes);
+ }
+
+ private KeyParameter UnwrapSessionKey(
+ string wrapAlg,
+ KeyParameter agreedKey)
+ {
+ byte[] encKeyOctets = encryptedKey.GetOctets();
+
+ IWrapper keyCipher = WrapperUtilities.GetWrapper(wrapAlg);
+ keyCipher.Init(false, agreedKey);
+ byte[] sKeyBytes = keyCipher.Unwrap(encKeyOctets, 0, encKeyOctets.Length);
+ return ParameterUtilities.CreateKeyParameter(GetContentAlgorithmName(), sKeyBytes);
+ }
+
+ internal KeyParameter GetSessionKey(
+ AsymmetricKeyParameter receiverPrivateKey)
+ {
+ try
+ {
+ string wrapAlg = DerObjectIdentifier.GetInstance(
+ Asn1Sequence.GetInstance(keyEncAlg.Parameters)[0]).Id;
+
+ AsymmetricKeyParameter senderPublicKey = GetSenderPublicKey(
+ receiverPrivateKey, info.Originator);
+
+ KeyParameter agreedWrapKey = CalculateAgreedWrapKey(wrapAlg,
+ senderPublicKey, receiverPrivateKey);
+
+ return UnwrapSessionKey(wrapAlg, agreedWrapKey);
+ }
+ catch (SecurityUtilityException e)
+ {
+ throw new CmsException("couldn't create cipher.", e);
+ }
+ catch (InvalidKeyException e)
+ {
+ throw new CmsException("key invalid in message.", e);
+ }
+ catch (Exception e)
+ {
+ throw new CmsException("originator key invalid.", e);
+ }
+ }
+
+ /**
+ * decrypt the content and return an input stream.
+ */
+ public override CmsTypedStream GetContentStream(
+ ICipherParameters key)
+ {
+ if (!(key is AsymmetricKeyParameter))
+ throw new ArgumentException("KeyAgreement requires asymmetric key", "key");
+
+ AsymmetricKeyParameter receiverPrivateKey = (AsymmetricKeyParameter) key;
+
+ if (!receiverPrivateKey.IsPrivate)
+ throw new ArgumentException("Expected private key", "key");
+
+ KeyParameter sKey = GetSessionKey(receiverPrivateKey);
+
+ return GetContentFromSessionKey(sKey);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KeyAgreeRecipientInformation.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KeyAgreeRecipientInformation.cs.meta
new file mode 100644
index 00000000..2afa8460
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KeyAgreeRecipientInformation.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 16d9a42147799fc408b9bb9ff87d2d6d
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KeyTransRecipientInfoGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KeyTransRecipientInfoGenerator.cs
new file mode 100644
index 00000000..2a52ae38
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KeyTransRecipientInfoGenerator.cs
@@ -0,0 +1,91 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ internal class KeyTransRecipientInfoGenerator : RecipientInfoGenerator
+ {
+ private static readonly CmsEnvelopedHelper Helper = CmsEnvelopedHelper.Instance;
+
+ private TbsCertificateStructure recipientTbsCert;
+ private AsymmetricKeyParameter recipientPublicKey;
+ private Asn1OctetString subjectKeyIdentifier;
+
+ // Derived fields
+ private SubjectPublicKeyInfo info;
+
+ internal KeyTransRecipientInfoGenerator()
+ {
+ }
+
+ internal X509Certificate RecipientCert
+ {
+ set
+ {
+ this.recipientTbsCert = CmsUtilities.GetTbsCertificateStructure(value);
+ this.recipientPublicKey = value.GetPublicKey();
+ this.info = recipientTbsCert.SubjectPublicKeyInfo;
+ }
+ }
+
+ internal AsymmetricKeyParameter RecipientPublicKey
+ {
+ set
+ {
+ this.recipientPublicKey = value;
+
+ try
+ {
+ info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(
+ recipientPublicKey);
+ }
+ catch (IOException)
+ {
+ throw new ArgumentException("can't extract key algorithm from this key");
+ }
+ }
+ }
+
+ internal Asn1OctetString SubjectKeyIdentifier
+ {
+ set { this.subjectKeyIdentifier = value; }
+ }
+
+ public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
+ {
+ byte[] keyBytes = contentEncryptionKey.GetKey();
+ AlgorithmIdentifier keyEncryptionAlgorithm = info.AlgorithmID;
+
+ IWrapper keyWrapper = Helper.CreateWrapper(keyEncryptionAlgorithm.Algorithm.Id);
+ keyWrapper.Init(true, new ParametersWithRandom(recipientPublicKey, random));
+ byte[] encryptedKeyBytes = keyWrapper.Wrap(keyBytes, 0, keyBytes.Length);
+
+ RecipientIdentifier recipId;
+ if (recipientTbsCert != null)
+ {
+ IssuerAndSerialNumber issuerAndSerial = new IssuerAndSerialNumber(
+ recipientTbsCert.Issuer, recipientTbsCert.SerialNumber.Value);
+ recipId = new RecipientIdentifier(issuerAndSerial);
+ }
+ else
+ {
+ recipId = new RecipientIdentifier(subjectKeyIdentifier);
+ }
+
+ return new RecipientInfo(new KeyTransRecipientInfo(recipId, keyEncryptionAlgorithm,
+ new DerOctetString(encryptedKeyBytes)));
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KeyTransRecipientInfoGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KeyTransRecipientInfoGenerator.cs.meta
new file mode 100644
index 00000000..eed2c815
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KeyTransRecipientInfoGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 62cf515f439ab014faae9f84218999b4
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KeyTransRecipientInformation.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KeyTransRecipientInformation.cs
new file mode 100644
index 00000000..9c0b4231
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KeyTransRecipientInformation.cs
@@ -0,0 +1,117 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
+using Asn1Pkcs = BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ /**
+ * the KeyTransRecipientInformation class for a recipient who has been sent a secret
+ * key encrypted using their public key that needs to be used to
+ * extract the message.
+ */
+ public class KeyTransRecipientInformation
+ : RecipientInformation
+ {
+ private KeyTransRecipientInfo info;
+
+ internal KeyTransRecipientInformation(
+ KeyTransRecipientInfo info,
+ CmsSecureReadable secureReadable)
+ : base(info.KeyEncryptionAlgorithm, secureReadable)
+ {
+ this.info = info;
+ this.rid = new RecipientID();
+
+ RecipientIdentifier r = info.RecipientIdentifier;
+
+ try
+ {
+ if (r.IsTagged)
+ {
+ Asn1OctetString octs = Asn1OctetString.GetInstance(r.ID);
+
+ rid.SubjectKeyIdentifier = octs.GetOctets();
+ }
+ else
+ {
+ IssuerAndSerialNumber iAnds = IssuerAndSerialNumber.GetInstance(r.ID);
+
+ rid.Issuer = iAnds.Name;
+ rid.SerialNumber = iAnds.SerialNumber.Value;
+ }
+ }
+ catch (IOException)
+ {
+ throw new ArgumentException("invalid rid in KeyTransRecipientInformation");
+ }
+ }
+
+ private string GetExchangeEncryptionAlgorithmName(
+ DerObjectIdentifier oid)
+ {
+ if (Asn1Pkcs.PkcsObjectIdentifiers.RsaEncryption.Equals(oid))
+ {
+ return "RSA//PKCS1Padding";
+ }
+
+ return oid.Id;
+ }
+
+ internal KeyParameter UnwrapKey(ICipherParameters key)
+ {
+ byte[] encryptedKey = info.EncryptedKey.GetOctets();
+ string keyExchangeAlgorithm = GetExchangeEncryptionAlgorithmName(keyEncAlg.Algorithm);
+
+ try
+ {
+ IWrapper keyWrapper = WrapperUtilities.GetWrapper(keyExchangeAlgorithm);
+ keyWrapper.Init(false, key);
+
+ // FIXME Support for MAC algorithm parameters similar to cipher parameters
+ return ParameterUtilities.CreateKeyParameter(
+ GetContentAlgorithmName(), keyWrapper.Unwrap(encryptedKey, 0, encryptedKey.Length));
+ }
+ catch (SecurityUtilityException e)
+ {
+ throw new CmsException("couldn't create cipher.", e);
+ }
+ catch (InvalidKeyException e)
+ {
+ throw new CmsException("key invalid in message.", e);
+ }
+// catch (IllegalBlockSizeException e)
+ catch (DataLengthException e)
+ {
+ throw new CmsException("illegal blocksize in message.", e);
+ }
+// catch (BadPaddingException e)
+ catch (InvalidCipherTextException e)
+ {
+ throw new CmsException("bad padding in message.", e);
+ }
+ }
+
+ /**
+ * decrypt the content and return it as a byte array.
+ */
+ public override CmsTypedStream GetContentStream(
+ ICipherParameters key)
+ {
+ KeyParameter sKey = UnwrapKey(key);
+
+ return GetContentFromSessionKey(sKey);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KeyTransRecipientInformation.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KeyTransRecipientInformation.cs.meta
new file mode 100644
index 00000000..216db4ba
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/KeyTransRecipientInformation.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: e0e4c1fe9df46304aad8da6377a731b3
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/OriginatorId.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/OriginatorId.cs
new file mode 100644
index 00000000..ff3f0b01
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/OriginatorId.cs
@@ -0,0 +1,55 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ /**
+ * a basic index for an originator.
+ */
+ public class OriginatorID
+ : X509CertStoreSelector
+ {
+ public override int GetHashCode()
+ {
+ int code = Arrays.GetHashCode(this.SubjectKeyIdentifier);
+
+ BigInteger serialNumber = this.SerialNumber;
+ if (serialNumber != null)
+ {
+ code ^= serialNumber.GetHashCode();
+ }
+
+ X509Name issuer = this.Issuer;
+ if (issuer != null)
+ {
+ code ^= issuer.GetHashCode();
+ }
+
+ return code;
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return false;
+
+ OriginatorID id = obj as OriginatorID;
+
+ if (id == null)
+ return false;
+
+ return Arrays.AreEqual(SubjectKeyIdentifier, id.SubjectKeyIdentifier)
+ && BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(SerialNumber, id.SerialNumber)
+ && IssuersMatch(Issuer, id.Issuer);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/OriginatorId.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/OriginatorId.cs.meta
new file mode 100644
index 00000000..c46a4e76
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/OriginatorId.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 88730f33bf66f0a448ad35da8082b31d
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/OriginatorInfoGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/OriginatorInfoGenerator.cs
new file mode 100644
index 00000000..6fcd7150
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/OriginatorInfoGenerator.cs
@@ -0,0 +1,46 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ public class OriginatorInfoGenerator
+ {
+ private readonly IList origCerts;
+ private readonly IList origCrls;
+
+ public OriginatorInfoGenerator(X509Certificate origCert)
+ {
+ this.origCerts = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(1);
+ this.origCrls = null;
+ origCerts.Add(origCert.CertificateStructure);
+ }
+
+ public OriginatorInfoGenerator(IX509Store origCerts)
+ : this(origCerts, null)
+ {
+ }
+
+ public OriginatorInfoGenerator(IX509Store origCerts, IX509Store origCrls)
+ {
+ this.origCerts = CmsUtilities.GetCertificatesFromStore(origCerts);
+ this.origCrls = origCrls == null ? null : CmsUtilities.GetCrlsFromStore(origCrls);
+ }
+
+ public virtual OriginatorInfo Generate()
+ {
+ Asn1Set certSet = CmsUtilities.CreateDerSetFromList(origCerts);
+ Asn1Set crlSet = origCrls == null ? null : CmsUtilities.CreateDerSetFromList(origCrls);
+ return new OriginatorInfo(certSet, crlSet);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/OriginatorInfoGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/OriginatorInfoGenerator.cs.meta
new file mode 100644
index 00000000..e55cac03
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/OriginatorInfoGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: e2dbdf7ea09dde0419cae93bf8aecc19
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/OriginatorInformation.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/OriginatorInformation.cs
new file mode 100644
index 00000000..d122b6ec
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/OriginatorInformation.cs
@@ -0,0 +1,100 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ public class OriginatorInformation
+ {
+ private readonly OriginatorInfo originatorInfo;
+
+ internal OriginatorInformation(OriginatorInfo originatorInfo)
+ {
+ this.originatorInfo = originatorInfo;
+ }
+
+ /**
+ * Return the certificates stored in the underlying OriginatorInfo object.
+ *
+ * @return a Store of X509CertificateHolder objects.
+ */
+ public virtual IX509Store GetCertificates()
+ {
+ Asn1Set certSet = originatorInfo.Certificates;
+
+ if (certSet != null)
+ {
+ IList certList = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(certSet.Count);
+
+ foreach (Asn1Encodable enc in certSet)
+ {
+ Asn1Object obj = enc.ToAsn1Object();
+ if (obj is Asn1Sequence)
+ {
+ certList.Add(new X509Certificate(X509CertificateStructure.GetInstance(obj)));
+ }
+ }
+
+ return X509StoreFactory.Create(
+ "Certificate/Collection",
+ new X509CollectionStoreParameters(certList));
+ }
+
+ return X509StoreFactory.Create(
+ "Certificate/Collection",
+ new X509CollectionStoreParameters(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList()));
+ }
+
+ /**
+ * Return the CRLs stored in the underlying OriginatorInfo object.
+ *
+ * @return a Store of X509CRLHolder objects.
+ */
+ public virtual IX509Store GetCrls()
+ {
+ Asn1Set crlSet = originatorInfo.Certificates;
+
+ if (crlSet != null)
+ {
+ IList crlList = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(crlSet.Count);
+
+ foreach (Asn1Encodable enc in crlSet)
+ {
+ Asn1Object obj = enc.ToAsn1Object();
+ if (obj is Asn1Sequence)
+ {
+ crlList.Add(new X509Crl(CertificateList.GetInstance(obj)));
+ }
+ }
+
+ return X509StoreFactory.Create(
+ "CRL/Collection",
+ new X509CollectionStoreParameters(crlList));
+ }
+
+ return X509StoreFactory.Create(
+ "CRL/Collection",
+ new X509CollectionStoreParameters(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList()));
+ }
+
+ /**
+ * Return the underlying ASN.1 object defining this SignerInformation object.
+ *
+ * @return a OriginatorInfo.
+ */
+ public virtual OriginatorInfo ToAsn1Structure()
+ {
+ return originatorInfo;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/OriginatorInformation.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/OriginatorInformation.cs.meta
new file mode 100644
index 00000000..57ecb390
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/OriginatorInformation.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c0274e45e4aa4c948bc4607426c487bd
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/PKCS5Scheme2PBEKey.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/PKCS5Scheme2PBEKey.cs
new file mode 100644
index 00000000..12986779
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/PKCS5Scheme2PBEKey.cs
@@ -0,0 +1,68 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ ///
+ /// PKCS5 scheme-2 - password converted to bytes assuming ASCII.
+ ///
+ public class Pkcs5Scheme2PbeKey
+ : CmsPbeKey
+ {
+ [Obsolete("Use version taking 'char[]' instead")]
+ public Pkcs5Scheme2PbeKey(
+ string password,
+ byte[] salt,
+ int iterationCount)
+ : this(password.ToCharArray(), salt, iterationCount)
+ {
+ }
+
+ [Obsolete("Use version taking 'char[]' instead")]
+ public Pkcs5Scheme2PbeKey(
+ string password,
+ AlgorithmIdentifier keyDerivationAlgorithm)
+ : this(password.ToCharArray(), keyDerivationAlgorithm)
+ {
+ }
+
+ public Pkcs5Scheme2PbeKey(
+ char[] password,
+ byte[] salt,
+ int iterationCount)
+ : base(password, salt, iterationCount)
+ {
+ }
+
+ public Pkcs5Scheme2PbeKey(
+ char[] password,
+ AlgorithmIdentifier keyDerivationAlgorithm)
+ : base(password, keyDerivationAlgorithm)
+ {
+ }
+
+ internal override KeyParameter GetEncoded(
+ string algorithmOid)
+ {
+ Pkcs5S2ParametersGenerator gen = new Pkcs5S2ParametersGenerator();
+
+ gen.Init(
+ PbeParametersGenerator.Pkcs5PasswordToBytes(password),
+ salt,
+ iterationCount);
+
+ return (KeyParameter) gen.GenerateDerivedParameters(
+ algorithmOid,
+ CmsEnvelopedHelper.Instance.GetKeySize(algorithmOid));
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/PKCS5Scheme2PBEKey.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/PKCS5Scheme2PBEKey.cs.meta
new file mode 100644
index 00000000..12b7fb47
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/PKCS5Scheme2PBEKey.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ff95842945d4c9b43a55fdf3135fe940
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/PKCS5Scheme2UTF8PBEKey.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/PKCS5Scheme2UTF8PBEKey.cs
new file mode 100644
index 00000000..ecbeb8b2
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/PKCS5Scheme2UTF8PBEKey.cs
@@ -0,0 +1,68 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ /**
+ * PKCS5 scheme-2 - password converted to bytes using UTF-8.
+ */
+ public class Pkcs5Scheme2Utf8PbeKey
+ : CmsPbeKey
+ {
+ [Obsolete("Use version taking 'char[]' instead")]
+ public Pkcs5Scheme2Utf8PbeKey(
+ string password,
+ byte[] salt,
+ int iterationCount)
+ : this(password.ToCharArray(), salt, iterationCount)
+ {
+ }
+
+ [Obsolete("Use version taking 'char[]' instead")]
+ public Pkcs5Scheme2Utf8PbeKey(
+ string password,
+ AlgorithmIdentifier keyDerivationAlgorithm)
+ : this(password.ToCharArray(), keyDerivationAlgorithm)
+ {
+ }
+
+ public Pkcs5Scheme2Utf8PbeKey(
+ char[] password,
+ byte[] salt,
+ int iterationCount)
+ : base(password, salt, iterationCount)
+ {
+ }
+
+ public Pkcs5Scheme2Utf8PbeKey(
+ char[] password,
+ AlgorithmIdentifier keyDerivationAlgorithm)
+ : base(password, keyDerivationAlgorithm)
+ {
+ }
+
+ internal override KeyParameter GetEncoded(
+ string algorithmOid)
+ {
+ Pkcs5S2ParametersGenerator gen = new Pkcs5S2ParametersGenerator();
+
+ gen.Init(
+ PbeParametersGenerator.Pkcs5PasswordToUtf8Bytes(password),
+ salt,
+ iterationCount);
+
+ return (KeyParameter) gen.GenerateDerivedParameters(
+ algorithmOid,
+ CmsEnvelopedHelper.Instance.GetKeySize(algorithmOid));
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/PKCS5Scheme2UTF8PBEKey.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/PKCS5Scheme2UTF8PBEKey.cs.meta
new file mode 100644
index 00000000..a69f6ec5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/PKCS5Scheme2UTF8PBEKey.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 9efe8084cdcc5b94abb2f637c28bbbb4
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/PasswordRecipientInfoGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/PasswordRecipientInfoGenerator.cs
new file mode 100644
index 00000000..5f5dcb7a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/PasswordRecipientInfoGenerator.cs
@@ -0,0 +1,74 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ internal class PasswordRecipientInfoGenerator : RecipientInfoGenerator
+ {
+ private static readonly CmsEnvelopedHelper Helper = CmsEnvelopedHelper.Instance;
+
+ private AlgorithmIdentifier keyDerivationAlgorithm;
+ private KeyParameter keyEncryptionKey;
+ // TODO Can get this from keyEncryptionKey?
+ private string keyEncryptionKeyOID;
+
+ internal PasswordRecipientInfoGenerator()
+ {
+ }
+
+ internal AlgorithmIdentifier KeyDerivationAlgorithm
+ {
+ set { this.keyDerivationAlgorithm = value; }
+ }
+
+ internal KeyParameter KeyEncryptionKey
+ {
+ set { this.keyEncryptionKey = value; }
+ }
+
+ internal string KeyEncryptionKeyOID
+ {
+ set { this.keyEncryptionKeyOID = value; }
+ }
+
+ public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
+ {
+ byte[] keyBytes = contentEncryptionKey.GetKey();
+
+ string rfc3211WrapperName = Helper.GetRfc3211WrapperName(keyEncryptionKeyOID);
+ IWrapper keyWrapper = Helper.CreateWrapper(rfc3211WrapperName);
+
+ // Note: In Java build, the IV is automatically generated in JCE layer
+ int ivLength = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(rfc3211WrapperName, "DESEDE") ? 8 : 16;
+ byte[] iv = new byte[ivLength];
+ random.NextBytes(iv);
+
+ ICipherParameters parameters = new ParametersWithIV(keyEncryptionKey, iv);
+ keyWrapper.Init(true, new ParametersWithRandom(parameters, random));
+ Asn1OctetString encryptedKey = new DerOctetString(
+ keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));
+
+ DerSequence seq = new DerSequence(
+ new DerObjectIdentifier(keyEncryptionKeyOID),
+ new DerOctetString(iv));
+
+ AlgorithmIdentifier keyEncryptionAlgorithm = new AlgorithmIdentifier(
+ PkcsObjectIdentifiers.IdAlgPwriKek, seq);
+
+ return new RecipientInfo(new PasswordRecipientInfo(
+ keyDerivationAlgorithm, keyEncryptionAlgorithm, encryptedKey));
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/PasswordRecipientInfoGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/PasswordRecipientInfoGenerator.cs.meta
new file mode 100644
index 00000000..204ad244
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/PasswordRecipientInfoGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0797ef17dd9a6674e99ef08509e4fae2
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/PasswordRecipientInformation.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/PasswordRecipientInformation.cs
new file mode 100644
index 00000000..4aa58f08
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/PasswordRecipientInformation.cs
@@ -0,0 +1,83 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ /**
+ * the RecipientInfo class for a recipient who has been sent a message
+ * encrypted using a password.
+ */
+ public class PasswordRecipientInformation
+ : RecipientInformation
+ {
+ private readonly PasswordRecipientInfo info;
+
+ internal PasswordRecipientInformation(
+ PasswordRecipientInfo info,
+ CmsSecureReadable secureReadable)
+ : base(info.KeyEncryptionAlgorithm, secureReadable)
+ {
+ this.info = info;
+ this.rid = new RecipientID();
+ }
+
+ /**
+ * return the object identifier for the key derivation algorithm, or null
+ * if there is none present.
+ *
+ * @return OID for key derivation algorithm, if present.
+ */
+ public virtual AlgorithmIdentifier KeyDerivationAlgorithm
+ {
+ get { return info.KeyDerivationAlgorithm; }
+ }
+
+ /**
+ * decrypt the content and return an input stream.
+ */
+ public override CmsTypedStream GetContentStream(
+ ICipherParameters key)
+ {
+ try
+ {
+ AlgorithmIdentifier kekAlg = AlgorithmIdentifier.GetInstance(info.KeyEncryptionAlgorithm);
+ Asn1Sequence kekAlgParams = (Asn1Sequence)kekAlg.Parameters;
+ byte[] encryptedKey = info.EncryptedKey.GetOctets();
+ string kekAlgName = DerObjectIdentifier.GetInstance(kekAlgParams[0]).Id;
+ string cName = CmsEnvelopedHelper.Instance.GetRfc3211WrapperName(kekAlgName);
+ IWrapper keyWrapper = WrapperUtilities.GetWrapper(cName);
+
+ byte[] iv = Asn1OctetString.GetInstance(kekAlgParams[1]).GetOctets();
+
+ ICipherParameters parameters = ((CmsPbeKey)key).GetEncoded(kekAlgName);
+ parameters = new ParametersWithIV(parameters, iv);
+
+ keyWrapper.Init(false, parameters);
+
+ KeyParameter sKey = ParameterUtilities.CreateKeyParameter(
+ GetContentAlgorithmName(), keyWrapper.Unwrap(encryptedKey, 0, encryptedKey.Length));
+
+ return GetContentFromSessionKey(sKey);
+ }
+ catch (SecurityUtilityException e)
+ {
+ throw new CmsException("couldn't create cipher.", e);
+ }
+ catch (InvalidKeyException e)
+ {
+ throw new CmsException("key invalid in message.", e);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/PasswordRecipientInformation.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/PasswordRecipientInformation.cs.meta
new file mode 100644
index 00000000..7f74e026
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/PasswordRecipientInformation.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 59db2f4f7992797448e438347160b5d1
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/RecipientId.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/RecipientId.cs
new file mode 100644
index 00000000..7a1a9505
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/RecipientId.cs
@@ -0,0 +1,62 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ public class RecipientID
+ : X509CertStoreSelector
+ {
+ private byte[] keyIdentifier;
+
+ public byte[] KeyIdentifier
+ {
+ get { return Arrays.Clone(keyIdentifier); }
+ set { keyIdentifier = Arrays.Clone(value); }
+ }
+
+ public override int GetHashCode()
+ {
+ int code = Arrays.GetHashCode(keyIdentifier)
+ ^ Arrays.GetHashCode(this.SubjectKeyIdentifier);
+
+ BigInteger serialNumber = this.SerialNumber;
+ if (serialNumber != null)
+ {
+ code ^= serialNumber.GetHashCode();
+ }
+
+ X509Name issuer = this.Issuer;
+ if (issuer != null)
+ {
+ code ^= issuer.GetHashCode();
+ }
+
+ return code;
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return true;
+
+ RecipientID id = obj as RecipientID;
+
+ if (id == null)
+ return false;
+
+ return Arrays.AreEqual(keyIdentifier, id.keyIdentifier)
+ && Arrays.AreEqual(SubjectKeyIdentifier, id.SubjectKeyIdentifier)
+ && BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(SerialNumber, id.SerialNumber)
+ && IssuersMatch(Issuer, id.Issuer);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/RecipientId.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/RecipientId.cs.meta
new file mode 100644
index 00000000..a3e5b777
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/RecipientId.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 8d8f726b35dc2ff4a82eedd642b0f48a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/RecipientInfoGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/RecipientInfoGenerator.cs
new file mode 100644
index 00000000..b5ce25e7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/RecipientInfoGenerator.cs
@@ -0,0 +1,30 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ interface RecipientInfoGenerator
+ {
+ ///
+ /// Generate a RecipientInfo object for the given key.
+ ///
+ ///
+ /// A
+ ///
+ ///
+ /// A
+ ///
+ ///
+ /// A
+ ///
+ ///
+ RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/RecipientInfoGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/RecipientInfoGenerator.cs.meta
new file mode 100644
index 00000000..5266110e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/RecipientInfoGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 98552255b0d43084da588633f2b167e2
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/RecipientInformation.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/RecipientInformation.cs
new file mode 100644
index 00000000..af116d45
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/RecipientInformation.cs
@@ -0,0 +1,130 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.IO;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ public abstract class RecipientInformation
+ {
+ internal RecipientID rid = new RecipientID();
+ internal AlgorithmIdentifier keyEncAlg;
+ internal CmsSecureReadable secureReadable;
+
+ private byte[] resultMac;
+
+ internal RecipientInformation(
+ AlgorithmIdentifier keyEncAlg,
+ CmsSecureReadable secureReadable)
+ {
+ this.keyEncAlg = keyEncAlg;
+ this.secureReadable = secureReadable;
+ }
+
+ internal string GetContentAlgorithmName()
+ {
+ AlgorithmIdentifier algorithm = secureReadable.Algorithm;
+// return CmsEnvelopedHelper.Instance.GetSymmetricCipherName(algorithm.Algorithm.Id);
+ return algorithm.Algorithm.Id;
+ }
+
+ public RecipientID RecipientID
+ {
+ get { return rid; }
+ }
+
+ public AlgorithmIdentifier KeyEncryptionAlgorithmID
+ {
+ get { return keyEncAlg; }
+ }
+
+ /**
+ * return the object identifier for the key encryption algorithm.
+ *
+ * @return OID for key encryption algorithm.
+ */
+ public string KeyEncryptionAlgOid
+ {
+ get { return keyEncAlg.Algorithm.Id; }
+ }
+
+ /**
+ * return the ASN.1 encoded key encryption algorithm parameters, or null if
+ * there aren't any.
+ *
+ * @return ASN.1 encoding of key encryption algorithm parameters.
+ */
+ public Asn1Object KeyEncryptionAlgParams
+ {
+ get
+ {
+ Asn1Encodable ae = keyEncAlg.Parameters;
+
+ return ae == null ? null : ae.ToAsn1Object();
+ }
+ }
+
+ internal CmsTypedStream GetContentFromSessionKey(
+ KeyParameter sKey)
+ {
+ CmsReadable readable = secureReadable.GetReadable(sKey);
+
+ try
+ {
+ return new CmsTypedStream(readable.GetInputStream());
+ }
+ catch (IOException e)
+ {
+ throw new CmsException("error getting .", e);
+ }
+ }
+
+ public byte[] GetContent(
+ ICipherParameters key)
+ {
+ try
+ {
+ return CmsUtilities.StreamToByteArray(GetContentStream(key).ContentStream);
+ }
+ catch (IOException e)
+ {
+ throw new Exception("unable to parse internal stream: " + e);
+ }
+ }
+
+ /**
+ * Return the MAC calculated for the content stream. Note: this call is only meaningful once all
+ * the content has been read.
+ *
+ * @return byte array containing the mac.
+ */
+ public byte[] GetMac()
+ {
+ if (resultMac == null)
+ {
+ object cryptoObject = secureReadable.CryptoObject;
+ if (cryptoObject is IMac)
+ {
+ resultMac = MacUtilities.DoFinal((IMac)cryptoObject);
+ }
+ }
+
+ return Arrays.Clone(resultMac);
+ }
+
+ public abstract CmsTypedStream GetContentStream(ICipherParameters key);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/RecipientInformation.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/RecipientInformation.cs.meta
new file mode 100644
index 00000000..2cb5fd11
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/RecipientInformation.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: b09bd29817789f64585d8d5fd9c5bc31
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/RecipientInformationStore.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/RecipientInformationStore.cs
new file mode 100644
index 00000000..e067b7c9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/RecipientInformationStore.cs
@@ -0,0 +1,90 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ public class RecipientInformationStore
+ {
+ private readonly IList all; //ArrayList[RecipientInformation]
+ private readonly IDictionary table = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); // Hashtable[RecipientID, ArrayList[RecipientInformation]]
+
+ public RecipientInformationStore(
+ ICollection recipientInfos)
+ {
+ foreach (RecipientInformation recipientInformation in recipientInfos)
+ {
+ RecipientID rid = recipientInformation.RecipientID;
+ IList list = (IList)table[rid];
+
+ if (list == null)
+ {
+ table[rid] = list = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(1);
+ }
+
+ list.Add(recipientInformation);
+ }
+
+ this.all = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(recipientInfos);
+ }
+
+ public RecipientInformation this[RecipientID selector]
+ {
+ get { return GetFirstRecipient(selector); }
+ }
+
+ /**
+ * Return the first RecipientInformation object that matches the
+ * passed in selector. Null if there are no matches.
+ *
+ * @param selector to identify a recipient
+ * @return a single RecipientInformation object. Null if none matches.
+ */
+ public RecipientInformation GetFirstRecipient(
+ RecipientID selector)
+ {
+ IList list = (IList) table[selector];
+
+ return list == null ? null : (RecipientInformation) list[0];
+ }
+
+ /**
+ * Return the number of recipients in the collection.
+ *
+ * @return number of recipients identified.
+ */
+ public int Count
+ {
+ get { return all.Count; }
+ }
+
+ /**
+ * Return all recipients in the collection
+ *
+ * @return a collection of recipients.
+ */
+ public ICollection GetRecipients()
+ {
+ return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(all);
+ }
+
+ /**
+ * Return possible empty collection with recipients matching the passed in RecipientID
+ *
+ * @param selector a recipient id to select against.
+ * @return a collection of RecipientInformation objects.
+ */
+ public ICollection GetRecipients(
+ RecipientID selector)
+ {
+ IList list = (IList)table[selector];
+
+ return list == null ? BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList() : BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(list);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/RecipientInformationStore.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/RecipientInformationStore.cs.meta
new file mode 100644
index 00000000..4010dbe7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/RecipientInformationStore.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: b264e8d3e47b2984cbe5e32516b48789
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SignerId.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SignerId.cs
new file mode 100644
index 00000000..f707a240
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SignerId.cs
@@ -0,0 +1,55 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ /**
+ * a basic index for a signer.
+ */
+ public class SignerID
+ : X509CertStoreSelector
+ {
+ public override int GetHashCode()
+ {
+ int code = Arrays.GetHashCode(this.SubjectKeyIdentifier);
+
+ BigInteger serialNumber = this.SerialNumber;
+ if (serialNumber != null)
+ {
+ code ^= serialNumber.GetHashCode();
+ }
+
+ X509Name issuer = this.Issuer;
+ if (issuer != null)
+ {
+ code ^= issuer.GetHashCode();
+ }
+
+ return code;
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return false;
+
+ SignerID id = obj as SignerID;
+
+ if (id == null)
+ return false;
+
+ return Arrays.AreEqual(SubjectKeyIdentifier, id.SubjectKeyIdentifier)
+ && BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(SerialNumber, id.SerialNumber)
+ && IssuersMatch(Issuer, id.Issuer);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SignerId.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SignerId.cs.meta
new file mode 100644
index 00000000..2f99c90f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SignerId.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 301fe279a448eb44e9877141e50d0d51
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SignerInfoGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SignerInfoGenerator.cs
new file mode 100644
index 00000000..9e6a34de
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SignerInfoGenerator.cs
@@ -0,0 +1,170 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ internal interface ISignerInfoGenerator
+ {
+ SignerInfo Generate(DerObjectIdentifier contentType, AlgorithmIdentifier digestAlgorithm,
+ byte[] calculatedDigest);
+ }
+
+ public class SignerInfoGenerator
+ {
+ internal X509Certificate certificate;
+ internal ISignatureFactory contentSigner;
+ internal SignerIdentifier sigId;
+ internal CmsAttributeTableGenerator signedGen;
+ internal CmsAttributeTableGenerator unsignedGen;
+ private bool isDirectSignature;
+
+ internal SignerInfoGenerator(SignerIdentifier sigId, ISignatureFactory signerFactory): this(sigId, signerFactory, false)
+ {
+
+ }
+
+ internal SignerInfoGenerator(SignerIdentifier sigId, ISignatureFactory signerFactory, bool isDirectSignature)
+ {
+ this.sigId = sigId;
+ this.contentSigner = signerFactory;
+ this.isDirectSignature = isDirectSignature;
+ if (this.isDirectSignature)
+ {
+ this.signedGen = null;
+ this.unsignedGen = null;
+ }
+ else
+ {
+ this.signedGen = new DefaultSignedAttributeTableGenerator();
+ this.unsignedGen = null;
+ }
+ }
+
+ internal SignerInfoGenerator(SignerIdentifier sigId, ISignatureFactory contentSigner, CmsAttributeTableGenerator signedGen, CmsAttributeTableGenerator unsignedGen)
+ {
+ this.sigId = sigId;
+ this.contentSigner = contentSigner;
+ this.signedGen = signedGen;
+ this.unsignedGen = unsignedGen;
+ this.isDirectSignature = false;
+ }
+
+ internal void setAssociatedCertificate(X509Certificate certificate)
+ {
+ this.certificate = certificate;
+ }
+ }
+
+ public class SignerInfoGeneratorBuilder
+ {
+ private bool directSignature;
+ private CmsAttributeTableGenerator signedGen;
+ private CmsAttributeTableGenerator unsignedGen;
+
+ public SignerInfoGeneratorBuilder()
+ {
+ }
+
+ /**
+ * If the passed in flag is true, the signer signature will be based on the data, not
+ * a collection of signed attributes, and no signed attributes will be included.
+ *
+ * @return the builder object
+ */
+ public SignerInfoGeneratorBuilder SetDirectSignature(bool hasNoSignedAttributes)
+ {
+ this.directSignature = hasNoSignedAttributes;
+
+ return this;
+ }
+
+ /**
+ * Provide a custom signed attribute generator.
+ *
+ * @param signedGen a generator of signed attributes.
+ * @return the builder object
+ */
+ public SignerInfoGeneratorBuilder WithSignedAttributeGenerator(CmsAttributeTableGenerator signedGen)
+ {
+ this.signedGen = signedGen;
+
+ return this;
+ }
+
+ /**
+ * Provide a generator of unsigned attributes.
+ *
+ * @param unsignedGen a generator for signed attributes.
+ * @return the builder object
+ */
+ public SignerInfoGeneratorBuilder WithUnsignedAttributeGenerator(CmsAttributeTableGenerator unsignedGen)
+ {
+ this.unsignedGen = unsignedGen;
+
+ return this;
+ }
+
+ /**
+ * Build a generator with the passed in X.509 certificate issuer and serial number as the signerIdentifier.
+ *
+ * @param contentSigner operator for generating the final signature in the SignerInfo with.
+ * @param certificate X.509 certificate related to the contentSigner.
+ * @return a SignerInfoGenerator
+ * @throws OperatorCreationException if the generator cannot be built.
+ */
+ public SignerInfoGenerator Build(ISignatureFactory contentSigner, X509Certificate certificate)
+ {
+ SignerIdentifier sigId = new SignerIdentifier(new IssuerAndSerialNumber(certificate.IssuerDN, new DerInteger(certificate.SerialNumber)));
+
+ SignerInfoGenerator sigInfoGen = CreateGenerator(contentSigner, sigId);
+
+ sigInfoGen.setAssociatedCertificate(certificate);
+
+ return sigInfoGen;
+ }
+
+ /**
+ * Build a generator with the passed in subjectKeyIdentifier as the signerIdentifier. If used you should
+ * try to follow the calculation described in RFC 5280 section 4.2.1.2.
+ *
+ * @param signerFactory operator factory for generating the final signature in the SignerInfo with.
+ * @param subjectKeyIdentifier key identifier to identify the public key for verifying the signature.
+ * @return a SignerInfoGenerator
+ */
+ public SignerInfoGenerator Build(ISignatureFactory signerFactory, byte[] subjectKeyIdentifier)
+ {
+ SignerIdentifier sigId = new SignerIdentifier(new DerOctetString(subjectKeyIdentifier));
+
+ return CreateGenerator(signerFactory, sigId);
+ }
+
+ private SignerInfoGenerator CreateGenerator(ISignatureFactory contentSigner, SignerIdentifier sigId)
+ {
+ if (directSignature)
+ {
+ return new SignerInfoGenerator(sigId, contentSigner, true);
+ }
+
+ if (signedGen != null || unsignedGen != null)
+ {
+ if (signedGen == null)
+ {
+ signedGen = new DefaultSignedAttributeTableGenerator();
+ }
+
+ return new SignerInfoGenerator(sigId, contentSigner, signedGen, unsignedGen);
+ }
+
+ return new SignerInfoGenerator(sigId, contentSigner);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SignerInfoGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SignerInfoGenerator.cs.meta
new file mode 100644
index 00000000..c63cc452
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SignerInfoGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 432e7e0fd04f285448faeb0b827ea82e
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SignerInformation.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SignerInformation.cs
new file mode 100644
index 00000000..fef7dd68
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SignerInformation.cs
@@ -0,0 +1,797 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.Diagnostics;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.IO;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ /**
+ * an expanded SignerInfo block from a CMS Signed message
+ */
+ public class SignerInformation
+ {
+ private static readonly CmsSignedHelper Helper = CmsSignedHelper.Instance;
+
+ private SignerID sid;
+ private SignerInfo info;
+ private AlgorithmIdentifier digestAlgorithm;
+ private AlgorithmIdentifier encryptionAlgorithm;
+ private readonly Asn1Set signedAttributeSet;
+ private readonly Asn1Set unsignedAttributeSet;
+ private CmsProcessable content;
+ private byte[] signature;
+ private DerObjectIdentifier contentType;
+ private IDigestCalculator digestCalculator;
+ private byte[] resultDigest;
+
+ // Derived
+ private Asn1.Cms.AttributeTable signedAttributeTable;
+ private Asn1.Cms.AttributeTable unsignedAttributeTable;
+ private readonly bool isCounterSignature;
+
+ internal SignerInformation(
+ SignerInfo info,
+ DerObjectIdentifier contentType,
+ CmsProcessable content,
+ IDigestCalculator digestCalculator)
+ {
+ this.info = info;
+ this.sid = new SignerID();
+ this.contentType = contentType;
+ this.isCounterSignature = contentType == null;
+
+ try
+ {
+ SignerIdentifier s = info.SignerID;
+
+ if (s.IsTagged)
+ {
+ Asn1OctetString octs = Asn1OctetString.GetInstance(s.ID);
+
+ sid.SubjectKeyIdentifier = octs.GetEncoded();
+ }
+ else
+ {
+ Asn1.Cms.IssuerAndSerialNumber iAnds =
+ Asn1.Cms.IssuerAndSerialNumber.GetInstance(s.ID);
+
+ sid.Issuer = iAnds.Name;
+ sid.SerialNumber = iAnds.SerialNumber.Value;
+ }
+ }
+ catch (IOException)
+ {
+ throw new ArgumentException("invalid sid in SignerInfo");
+ }
+
+ this.digestAlgorithm = info.DigestAlgorithm;
+ this.signedAttributeSet = info.AuthenticatedAttributes;
+ this.unsignedAttributeSet = info.UnauthenticatedAttributes;
+ this.encryptionAlgorithm = info.DigestEncryptionAlgorithm;
+ this.signature = info.EncryptedDigest.GetOctets();
+
+ this.content = content;
+ this.digestCalculator = digestCalculator;
+ }
+
+ /**
+ * Protected constructor. In some cases clients have their own idea about how to encode
+ * the signed attributes and calculate the signature. This constructor is to allow developers
+ * to deal with that by extending off the class and overridng methods like getSignedAttributes().
+ *
+ * @param baseInfo the SignerInformation to base this one on.
+ */
+ protected SignerInformation(SignerInformation baseInfo)
+ {
+ this.info = baseInfo.info;
+ this.contentType = baseInfo.contentType;
+ this.isCounterSignature = baseInfo.IsCounterSignature;
+ this.sid = baseInfo.SignerID;
+ this.digestAlgorithm = info.DigestAlgorithm;
+ this.signedAttributeSet = info.AuthenticatedAttributes;
+ this.unsignedAttributeSet = info.UnauthenticatedAttributes;
+ this.encryptionAlgorithm = info.DigestEncryptionAlgorithm;
+ this.signature = info.EncryptedDigest.GetOctets();
+ this.content = baseInfo.content;
+ this.resultDigest = baseInfo.resultDigest;
+ this.signedAttributeTable = baseInfo.signedAttributeTable;
+ this.unsignedAttributeTable = baseInfo.unsignedAttributeTable;
+ }
+
+ public bool IsCounterSignature
+ {
+ get { return isCounterSignature; }
+ }
+
+ public DerObjectIdentifier ContentType
+ {
+ get { return contentType; }
+ }
+
+ public SignerID SignerID
+ {
+ get { return sid; }
+ }
+
+ /**
+ * return the version number for this objects underlying SignerInfo structure.
+ */
+ public int Version
+ {
+ get { return info.Version.Value.IntValue; }
+ }
+
+ public AlgorithmIdentifier DigestAlgorithmID
+ {
+ get { return digestAlgorithm; }
+ }
+
+ /**
+ * return the object identifier for the signature.
+ */
+ public string DigestAlgOid
+ {
+ get { return digestAlgorithm.Algorithm.Id; }
+ }
+
+ /**
+ * return the signature parameters, or null if there aren't any.
+ */
+ public Asn1Object DigestAlgParams
+ {
+ get
+ {
+ Asn1Encodable ae = digestAlgorithm.Parameters;
+
+ return ae == null ? null : ae.ToAsn1Object();
+ }
+ }
+
+ /**
+ * return the content digest that was calculated during verification.
+ */
+ public byte[] GetContentDigest()
+ {
+ if (resultDigest == null)
+ {
+ throw new InvalidOperationException("method can only be called after verify.");
+ }
+
+ return (byte[])resultDigest.Clone();
+ }
+
+ public AlgorithmIdentifier EncryptionAlgorithmID
+ {
+ get { return encryptionAlgorithm; }
+ }
+
+ /**
+ * return the object identifier for the signature.
+ */
+ public string EncryptionAlgOid
+ {
+ get { return encryptionAlgorithm.Algorithm.Id; }
+ }
+
+ /**
+ * return the signature/encryption algorithm parameters, or null if
+ * there aren't any.
+ */
+ public Asn1Object EncryptionAlgParams
+ {
+ get
+ {
+ Asn1Encodable ae = encryptionAlgorithm.Parameters;
+
+ return ae == null ? null : ae.ToAsn1Object();
+ }
+ }
+
+ /**
+ * return a table of the signed attributes - indexed by
+ * the OID of the attribute.
+ */
+ public Asn1.Cms.AttributeTable SignedAttributes
+ {
+ get
+ {
+ if (signedAttributeSet != null && signedAttributeTable == null)
+ {
+ signedAttributeTable = new Asn1.Cms.AttributeTable(signedAttributeSet);
+ }
+ return signedAttributeTable;
+ }
+ }
+
+ /**
+ * return a table of the unsigned attributes indexed by
+ * the OID of the attribute.
+ */
+ public Asn1.Cms.AttributeTable UnsignedAttributes
+ {
+ get
+ {
+ if (unsignedAttributeSet != null && unsignedAttributeTable == null)
+ {
+ unsignedAttributeTable = new Asn1.Cms.AttributeTable(unsignedAttributeSet);
+ }
+ return unsignedAttributeTable;
+ }
+ }
+
+ /**
+ * return the encoded signature
+ */
+ public byte[] GetSignature()
+ {
+ return (byte[]) signature.Clone();
+ }
+
+ /**
+ * Return a SignerInformationStore containing the counter signatures attached to this
+ * signer. If no counter signatures are present an empty store is returned.
+ */
+ public SignerInformationStore GetCounterSignatures()
+ {
+ // TODO There are several checks implied by the RFC3852 comments that are missing
+
+ /*
+ The countersignature attribute MUST be an unsigned attribute; it MUST
+ NOT be a signed attribute, an authenticated attribute, an
+ unauthenticated attribute, or an unprotected attribute.
+ */
+ Asn1.Cms.AttributeTable unsignedAttributeTable = UnsignedAttributes;
+ if (unsignedAttributeTable == null)
+ {
+ return new SignerInformationStore(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(0));
+ }
+
+ IList counterSignatures = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+
+ /*
+ The UnsignedAttributes syntax is defined as a SET OF Attributes. The
+ UnsignedAttributes in a signerInfo may include multiple instances of
+ the countersignature attribute.
+ */
+ Asn1EncodableVector allCSAttrs = unsignedAttributeTable.GetAll(CmsAttributes.CounterSignature);
+
+ foreach (Asn1.Cms.Attribute counterSignatureAttribute in allCSAttrs)
+ {
+ /*
+ A countersignature attribute can have multiple attribute values. The
+ syntax is defined as a SET OF AttributeValue, and there MUST be one
+ or more instances of AttributeValue present.
+ */
+ Asn1Set values = counterSignatureAttribute.AttrValues;
+ if (values.Count < 1)
+ {
+ // TODO Throw an appropriate exception?
+ }
+
+ foreach (Asn1Encodable asn1Obj in values)
+ {
+ /*
+ Countersignature values have the same meaning as SignerInfo values
+ for ordinary signatures, except that:
+
+ 1. The signedAttributes field MUST NOT contain a content-type
+ attribute; there is no content type for countersignatures.
+
+ 2. The signedAttributes field MUST contain a message-digest
+ attribute if it contains any other attributes.
+
+ 3. The input to the message-digesting process is the contents
+ octets of the DER encoding of the signatureValue field of the
+ SignerInfo value with which the attribute is associated.
+ */
+ SignerInfo si = SignerInfo.GetInstance(asn1Obj.ToAsn1Object());
+
+ string digestName = CmsSignedHelper.Instance.GetDigestAlgName(si.DigestAlgorithm.Algorithm.Id);
+
+ counterSignatures.Add(new SignerInformation(si, null, null, new CounterSignatureDigestCalculator(digestName, GetSignature())));
+ }
+ }
+
+ return new SignerInformationStore(counterSignatures);
+ }
+
+ /**
+ * return the DER encoding of the signed attributes.
+ * @throws IOException if an encoding error occurs.
+ */
+ public byte[] GetEncodedSignedAttributes()
+ {
+ return signedAttributeSet == null
+ ? null
+ : signedAttributeSet.GetEncoded(Asn1Encodable.Der);
+ }
+
+ private bool DoVerify(
+ AsymmetricKeyParameter key)
+ {
+ string digestName = Helper.GetDigestAlgName(this.DigestAlgOid);
+ IDigest digest = Helper.GetDigestInstance(digestName);
+
+ DerObjectIdentifier sigAlgOid = this.encryptionAlgorithm.Algorithm;
+ Asn1Encodable sigParams = this.encryptionAlgorithm.Parameters;
+ ISigner sig;
+
+ if (sigAlgOid.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdRsassaPss))
+ {
+ // RFC 4056 2.2
+ // When the id-RSASSA-PSS algorithm identifier is used for a signature,
+ // the AlgorithmIdentifier parameters field MUST contain RSASSA-PSS-params.
+ if (sigParams == null)
+ throw new CmsException("RSASSA-PSS signature must specify algorithm parameters");
+
+ try
+ {
+ // TODO Provide abstract configuration mechanism
+ // (via alternate SignerUtilities.GetSigner method taking ASN.1 params)
+
+ Asn1.Pkcs.RsassaPssParameters pss = Asn1.Pkcs.RsassaPssParameters.GetInstance(
+ sigParams.ToAsn1Object());
+
+ if (!pss.HashAlgorithm.Algorithm.Equals(this.digestAlgorithm.Algorithm))
+ throw new CmsException("RSASSA-PSS signature parameters specified incorrect hash algorithm");
+ if (!pss.MaskGenAlgorithm.Algorithm.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdMgf1))
+ throw new CmsException("RSASSA-PSS signature parameters specified unknown MGF");
+
+ IDigest pssDigest = DigestUtilities.GetDigest(pss.HashAlgorithm.Algorithm);
+ int saltLength = pss.SaltLength.Value.IntValue;
+ byte trailerField = (byte) pss.TrailerField.Value.IntValue;
+
+ // RFC 4055 3.1
+ // The value MUST be 1, which represents the trailer field with hexadecimal value 0xBC
+ if (trailerField != 1)
+ throw new CmsException("RSASSA-PSS signature parameters must have trailerField of 1");
+
+ sig = new PssSigner(new RsaBlindedEngine(), pssDigest, saltLength);
+ }
+ catch (Exception e)
+ {
+ throw new CmsException("failed to set RSASSA-PSS signature parameters", e);
+ }
+ }
+ else
+ {
+ // TODO Probably too strong a check at the moment
+// if (sigParams != null)
+// throw new CmsException("unrecognised signature parameters provided");
+
+ string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(this.EncryptionAlgOid);
+
+ sig = Helper.GetSignatureInstance(signatureName);
+
+ //sig = Helper.GetSignatureInstance(this.EncryptionAlgOid);
+ //sig = SignerUtilities.GetSigner(sigAlgOid);
+ }
+
+ try
+ {
+ if (digestCalculator != null)
+ {
+ resultDigest = digestCalculator.GetDigest();
+ }
+ else
+ {
+ if (content != null)
+ {
+ content.Write(new DigestSink(digest));
+ }
+ else if (signedAttributeSet == null)
+ {
+ // TODO Get rid of this exception and just treat content==null as empty not missing?
+ throw new CmsException("data not encapsulated in signature - use detached constructor.");
+ }
+
+ resultDigest = DigestUtilities.DoFinal(digest);
+ }
+ }
+ catch (IOException e)
+ {
+ throw new CmsException("can't process mime object to create signature.", e);
+ }
+
+ // RFC 3852 11.1 Check the content-type attribute is correct
+ {
+ Asn1Object validContentType = GetSingleValuedSignedAttribute(
+ CmsAttributes.ContentType, "content-type");
+ if (validContentType == null)
+ {
+ if (!isCounterSignature && signedAttributeSet != null)
+ throw new CmsException("The content-type attribute type MUST be present whenever signed attributes are present in signed-data");
+ }
+ else
+ {
+ if (isCounterSignature)
+ throw new CmsException("[For counter signatures,] the signedAttributes field MUST NOT contain a content-type attribute");
+
+ if (!(validContentType is DerObjectIdentifier))
+ throw new CmsException("content-type attribute value not of ASN.1 type 'OBJECT IDENTIFIER'");
+
+ DerObjectIdentifier signedContentType = (DerObjectIdentifier)validContentType;
+
+ if (!signedContentType.Equals(contentType))
+ throw new CmsException("content-type attribute value does not match eContentType");
+ }
+ }
+
+ // RFC 3852 11.2 Check the message-digest attribute is correct
+ {
+ Asn1Object validMessageDigest = GetSingleValuedSignedAttribute(
+ CmsAttributes.MessageDigest, "message-digest");
+ if (validMessageDigest == null)
+ {
+ if (signedAttributeSet != null)
+ throw new CmsException("the message-digest signed attribute type MUST be present when there are any signed attributes present");
+ }
+ else
+ {
+ if (!(validMessageDigest is Asn1OctetString))
+ {
+ throw new CmsException("message-digest attribute value not of ASN.1 type 'OCTET STRING'");
+ }
+
+ Asn1OctetString signedMessageDigest = (Asn1OctetString)validMessageDigest;
+
+ if (!Arrays.AreEqual(resultDigest, signedMessageDigest.GetOctets()))
+ throw new CmsException("message-digest attribute value does not match calculated value");
+ }
+ }
+
+ // RFC 3852 11.4 Validate countersignature attribute(s)
+ {
+ Asn1.Cms.AttributeTable signedAttrTable = this.SignedAttributes;
+ if (signedAttrTable != null
+ && signedAttrTable.GetAll(CmsAttributes.CounterSignature).Count > 0)
+ {
+ throw new CmsException("A countersignature attribute MUST NOT be a signed attribute");
+ }
+
+ Asn1.Cms.AttributeTable unsignedAttrTable = this.UnsignedAttributes;
+ if (unsignedAttrTable != null)
+ {
+ foreach (Asn1.Cms.Attribute csAttr in unsignedAttrTable.GetAll(CmsAttributes.CounterSignature))
+ {
+ if (csAttr.AttrValues.Count < 1)
+ throw new CmsException("A countersignature attribute MUST contain at least one AttributeValue");
+
+ // Note: We don't recursively validate the countersignature value
+ }
+ }
+ }
+
+ try
+ {
+ sig.Init(false, key);
+
+ if (signedAttributeSet == null)
+ {
+ if (digestCalculator != null)
+ {
+ // need to decrypt signature and check message bytes
+ return VerifyDigest(resultDigest, key, this.GetSignature());
+ }
+ else if (content != null)
+ {
+ try
+ {
+ // TODO Use raw signature of the hash value instead
+ content.Write(new SignerSink(sig));
+ }
+ catch (SignatureException e)
+ {
+ throw new CmsStreamException("signature problem: " + e);
+ }
+ }
+ }
+ else
+ {
+ byte[] tmp = this.GetEncodedSignedAttributes();
+ sig.BlockUpdate(tmp, 0, tmp.Length);
+ }
+
+ return sig.VerifySignature(this.GetSignature());
+ }
+ catch (InvalidKeyException e)
+ {
+ throw new CmsException("key not appropriate to signature in message.", e);
+ }
+ catch (IOException e)
+ {
+ throw new CmsException("can't process mime object to create signature.", e);
+ }
+ catch (SignatureException e)
+ {
+ throw new CmsException("invalid signature format in message: " + e.Message, e);
+ }
+ }
+
+ private bool IsNull(
+ Asn1Encodable o)
+ {
+ return (o is Asn1Null) || (o == null);
+ }
+
+ private DigestInfo DerDecode(
+ byte[] encoding)
+ {
+ if (encoding[0] != (int)(Asn1Tags.Constructed | Asn1Tags.Sequence))
+ {
+ throw new IOException("not a digest info object");
+ }
+
+ DigestInfo digInfo = DigestInfo.GetInstance(Asn1Object.FromByteArray(encoding));
+
+ // length check to avoid Bleichenbacher vulnerability
+
+ if (digInfo.GetEncoded().Length != encoding.Length)
+ {
+ throw new CmsException("malformed RSA signature");
+ }
+
+ return digInfo;
+ }
+
+ private bool VerifyDigest(
+ byte[] digest,
+ AsymmetricKeyParameter key,
+ byte[] signature)
+ {
+ string algorithm = Helper.GetEncryptionAlgName(this.EncryptionAlgOid);
+
+ try
+ {
+ if (algorithm.Equals("RSA"))
+ {
+ IBufferedCipher c = CmsEnvelopedHelper.Instance.CreateAsymmetricCipher("RSA/ECB/PKCS1Padding");
+
+ c.Init(false, key);
+
+ byte[] decrypt = c.DoFinal(signature);
+
+ DigestInfo digInfo = DerDecode(decrypt);
+
+ if (!digInfo.AlgorithmID.Algorithm.Equals(digestAlgorithm.Algorithm))
+ {
+ return false;
+ }
+
+ if (!IsNull(digInfo.AlgorithmID.Parameters))
+ {
+ return false;
+ }
+
+ byte[] sigHash = digInfo.GetDigest();
+
+ return Arrays.ConstantTimeAreEqual(digest, sigHash);
+ }
+ else if (algorithm.Equals("DSA"))
+ {
+ ISigner sig = SignerUtilities.GetSigner("NONEwithDSA");
+
+ sig.Init(false, key);
+
+ sig.BlockUpdate(digest, 0, digest.Length);
+
+ return sig.VerifySignature(signature);
+ }
+ else
+ {
+ throw new CmsException("algorithm: " + algorithm + " not supported in base signatures.");
+ }
+ }
+ catch (SecurityUtilityException e)
+ {
+ throw e;
+ }
+ catch (GeneralSecurityException e)
+ {
+ throw new CmsException("Exception processing signature: " + e, e);
+ }
+ catch (IOException e)
+ {
+ throw new CmsException("Exception decoding signature: " + e, e);
+ }
+ }
+
+ /**
+ * verify that the given public key successfully handles and confirms the
+ * signature associated with this signer.
+ */
+ public bool Verify(
+ AsymmetricKeyParameter pubKey)
+ {
+ if (pubKey.IsPrivate)
+ throw new ArgumentException("Expected public key", "pubKey");
+
+ // Optional, but still need to validate if present
+ GetSigningTime();
+
+ return DoVerify(pubKey);
+ }
+
+ /**
+ * verify that the given certificate successfully handles and confirms
+ * the signature associated with this signer and, if a signingTime
+ * attribute is available, that the certificate was valid at the time the
+ * signature was generated.
+ */
+ public bool Verify(
+ X509Certificate cert)
+ {
+ Asn1.Cms.Time signingTime = GetSigningTime();
+ if (signingTime != null)
+ {
+ cert.CheckValidity(signingTime.Date);
+ }
+
+ return DoVerify(cert.GetPublicKey());
+ }
+
+ /**
+ * Return the base ASN.1 CMS structure that this object contains.
+ *
+ * @return an object containing a CMS SignerInfo structure.
+ */
+ public SignerInfo ToSignerInfo()
+ {
+ return info;
+ }
+
+ private Asn1Object GetSingleValuedSignedAttribute(
+ DerObjectIdentifier attrOID, string printableName)
+ {
+
+ Asn1.Cms.AttributeTable unsignedAttrTable = this.UnsignedAttributes;
+ if (unsignedAttrTable != null
+ && unsignedAttrTable.GetAll(attrOID).Count > 0)
+ {
+ throw new CmsException("The " + printableName
+ + " attribute MUST NOT be an unsigned attribute");
+ }
+
+ Asn1.Cms.AttributeTable signedAttrTable = this.SignedAttributes;
+ if (signedAttrTable == null)
+ {
+ return null;
+ }
+
+ Asn1EncodableVector v = signedAttrTable.GetAll(attrOID);
+ switch (v.Count)
+ {
+ case 0:
+ return null;
+ case 1:
+ Asn1.Cms.Attribute t = (Asn1.Cms.Attribute) v[0];
+ Asn1Set attrValues = t.AttrValues;
+
+ if (attrValues.Count != 1)
+ throw new CmsException("A " + printableName
+ + " attribute MUST have a single attribute value");
+
+ return attrValues[0].ToAsn1Object();
+ default:
+ throw new CmsException("The SignedAttributes in a signerInfo MUST NOT include multiple instances of the "
+ + printableName + " attribute");
+ }
+ }
+
+ private Asn1.Cms.Time GetSigningTime()
+ {
+ Asn1Object validSigningTime = GetSingleValuedSignedAttribute(
+ CmsAttributes.SigningTime, "signing-time");
+
+ if (validSigningTime == null)
+ return null;
+
+ try
+ {
+ return Asn1.Cms.Time.GetInstance(validSigningTime);
+ }
+ catch (ArgumentException)
+ {
+ throw new CmsException("signing-time attribute value not a valid 'Time' structure");
+ }
+ }
+
+ /**
+ * Return a signer information object with the passed in unsigned
+ * attributes replacing the ones that are current associated with
+ * the object passed in.
+ *
+ * @param signerInformation the signerInfo to be used as the basis.
+ * @param unsignedAttributes the unsigned attributes to add.
+ * @return a copy of the original SignerInformationObject with the changed attributes.
+ */
+ public static SignerInformation ReplaceUnsignedAttributes(
+ SignerInformation signerInformation,
+ Asn1.Cms.AttributeTable unsignedAttributes)
+ {
+ SignerInfo sInfo = signerInformation.info;
+ Asn1Set unsignedAttr = null;
+
+ if (unsignedAttributes != null)
+ {
+ unsignedAttr = new DerSet(unsignedAttributes.ToAsn1EncodableVector());
+ }
+
+ return new SignerInformation(
+ new SignerInfo(
+ sInfo.SignerID,
+ sInfo.DigestAlgorithm,
+ sInfo.AuthenticatedAttributes,
+ sInfo.DigestEncryptionAlgorithm,
+ sInfo.EncryptedDigest,
+ unsignedAttr),
+ signerInformation.contentType,
+ signerInformation.content,
+ null);
+ }
+
+ /**
+ * Return a signer information object with passed in SignerInformationStore representing counter
+ * signatures attached as an unsigned attribute.
+ *
+ * @param signerInformation the signerInfo to be used as the basis.
+ * @param counterSigners signer info objects carrying counter signature.
+ * @return a copy of the original SignerInformationObject with the changed attributes.
+ */
+ public static SignerInformation AddCounterSigners(
+ SignerInformation signerInformation,
+ SignerInformationStore counterSigners)
+ {
+ // TODO Perform checks from RFC 3852 11.4
+
+ SignerInfo sInfo = signerInformation.info;
+ Asn1.Cms.AttributeTable unsignedAttr = signerInformation.UnsignedAttributes;
+ Asn1EncodableVector v;
+
+ if (unsignedAttr != null)
+ {
+ v = unsignedAttr.ToAsn1EncodableVector();
+ }
+ else
+ {
+ v = new Asn1EncodableVector();
+ }
+
+ Asn1EncodableVector sigs = new Asn1EncodableVector();
+
+ foreach (SignerInformation sigInf in counterSigners.GetSigners())
+ {
+ sigs.Add(sigInf.ToSignerInfo());
+ }
+
+ v.Add(new Asn1.Cms.Attribute(CmsAttributes.CounterSignature, new DerSet(sigs)));
+
+ return new SignerInformation(
+ new SignerInfo(
+ sInfo.SignerID,
+ sInfo.DigestAlgorithm,
+ sInfo.AuthenticatedAttributes,
+ sInfo.DigestEncryptionAlgorithm,
+ sInfo.EncryptedDigest,
+ new DerSet(v)),
+ signerInformation.contentType,
+ signerInformation.content,
+ null);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SignerInformation.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SignerInformation.cs.meta
new file mode 100644
index 00000000..c3002560
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SignerInformation.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: dfd117ab49ca573488f189430fec731e
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SignerInformationStore.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SignerInformationStore.cs
new file mode 100644
index 00000000..6e45fb67
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SignerInformationStore.cs
@@ -0,0 +1,99 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ public class SignerInformationStore
+ {
+ private readonly IList all; //ArrayList[SignerInformation]
+ private readonly IDictionary table = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); // Hashtable[SignerID, ArrayList[SignerInformation]]
+
+ /**
+ * Create a store containing a single SignerInformation object.
+ *
+ * @param signerInfo the signer information to contain.
+ */
+ public SignerInformationStore(
+ SignerInformation signerInfo)
+ {
+ this.all = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(1);
+ this.all.Add(signerInfo);
+
+ SignerID sid = signerInfo.SignerID;
+
+ table[sid] = all;
+ }
+
+ /**
+ * Create a store containing a collection of SignerInformation objects.
+ *
+ * @param signerInfos a collection signer information objects to contain.
+ */
+ public SignerInformationStore(
+ ICollection signerInfos)
+ {
+ foreach (SignerInformation signer in signerInfos)
+ {
+ SignerID sid = signer.SignerID;
+ IList list = (IList)table[sid];
+
+ if (list == null)
+ {
+ table[sid] = list = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(1);
+ }
+
+ list.Add(signer);
+ }
+
+ this.all = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(signerInfos);
+ }
+
+ /**
+ * Return the first SignerInformation object that matches the
+ * passed in selector. Null if there are no matches.
+ *
+ * @param selector to identify a signer
+ * @return a single SignerInformation object. Null if none matches.
+ */
+ public SignerInformation GetFirstSigner(
+ SignerID selector)
+ {
+ IList list = (IList) table[selector];
+
+ return list == null ? null : (SignerInformation) list[0];
+ }
+
+ /// The number of signers in the collection.
+ public int Count
+ {
+ get { return all.Count; }
+ }
+
+ /// An ICollection of all signers in the collection
+ public ICollection GetSigners()
+ {
+ return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(all);
+ }
+
+ /**
+ * Return possible empty collection with signers matching the passed in SignerID
+ *
+ * @param selector a signer id to select against.
+ * @return a collection of SignerInformation objects.
+ */
+ public ICollection GetSigners(
+ SignerID selector)
+ {
+ IList list = (IList) table[selector];
+
+ return list == null ? BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList() : BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(list);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SignerInformationStore.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SignerInformationStore.cs.meta
new file mode 100644
index 00000000..5f2fd7a0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SignerInformationStore.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: d7833ac1bdca67e48b219183aab7cebe
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SimpleAttributeTableGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SimpleAttributeTableGenerator.cs
new file mode 100644
index 00000000..8d846ac6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SimpleAttributeTableGenerator.cs
@@ -0,0 +1,32 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms
+{
+ /**
+ * Basic generator that just returns a preconstructed attribute table
+ */
+ public class SimpleAttributeTableGenerator
+ : CmsAttributeTableGenerator
+ {
+ private readonly AttributeTable attributes;
+
+ public SimpleAttributeTableGenerator(
+ AttributeTable attributes)
+ {
+ this.attributes = attributes;
+ }
+
+ public virtual AttributeTable GetAttributes(
+ IDictionary parameters)
+ {
+ return attributes;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SimpleAttributeTableGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SimpleAttributeTableGenerator.cs.meta
new file mode 100644
index 00000000..1501fae4
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/cms/SimpleAttributeTableGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 373dc7b36a67c43448524ed163119b9e
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto.meta
new file mode 100644
index 00000000..beffab3b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 65f5702f015c2304e9152f0d0a52eb2f
+folderAsset: yes
+DefaultImporter:
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/AsymmetricCipherKeyPair.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/AsymmetricCipherKeyPair.cs
new file mode 100644
index 00000000..6c2b79d3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/AsymmetricCipherKeyPair.cs
@@ -0,0 +1,56 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ /**
+ * a holding class for public/private parameter pairs.
+ */
+ public class AsymmetricCipherKeyPair
+ {
+ private readonly AsymmetricKeyParameter publicParameter;
+ private readonly AsymmetricKeyParameter privateParameter;
+
+ /**
+ * basic constructor.
+ *
+ * @param publicParam a public key parameters object.
+ * @param privateParam the corresponding private key parameters.
+ */
+ public AsymmetricCipherKeyPair(
+ AsymmetricKeyParameter publicParameter,
+ AsymmetricKeyParameter privateParameter)
+ {
+ if (publicParameter.IsPrivate)
+ throw new ArgumentException("Expected a public key", "publicParameter");
+ if (!privateParameter.IsPrivate)
+ throw new ArgumentException("Expected a private key", "privateParameter");
+
+ this.publicParameter = publicParameter;
+ this.privateParameter = privateParameter;
+ }
+
+ /**
+ * return the public key parameters.
+ *
+ * @return the public key parameters.
+ */
+ public AsymmetricKeyParameter Public
+ {
+ get { return publicParameter; }
+ }
+
+ /**
+ * return the private key parameters.
+ *
+ * @return the private key parameters.
+ */
+ public AsymmetricKeyParameter Private
+ {
+ get { return privateParameter; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/AsymmetricCipherKeyPair.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/AsymmetricCipherKeyPair.cs.meta
new file mode 100644
index 00000000..6028e8c0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/AsymmetricCipherKeyPair.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: eef9b100979b64f49a4f37506e85cbea
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/AsymmetricKeyParameter.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/AsymmetricKeyParameter.cs
new file mode 100644
index 00000000..b5313dd3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/AsymmetricKeyParameter.cs
@@ -0,0 +1,51 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ public abstract class AsymmetricKeyParameter
+ : ICipherParameters
+ {
+ private readonly bool privateKey;
+
+ protected AsymmetricKeyParameter(
+ bool privateKey)
+ {
+ this.privateKey = privateKey;
+ }
+
+ public bool IsPrivate
+ {
+ get { return privateKey; }
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ AsymmetricKeyParameter other = obj as AsymmetricKeyParameter;
+
+ if (other == null)
+ {
+ return false;
+ }
+
+ return Equals(other);
+ }
+
+ protected bool Equals(
+ AsymmetricKeyParameter other)
+ {
+ return privateKey == other.privateKey;
+ }
+
+ public override int GetHashCode()
+ {
+ return privateKey.GetHashCode();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/AsymmetricKeyParameter.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/AsymmetricKeyParameter.cs.meta
new file mode 100644
index 00000000..f05ee328
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/AsymmetricKeyParameter.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a345564cb9c4fb64eb3b18227bc3bc11
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedAeadBlockCipher.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedAeadBlockCipher.cs
new file mode 100644
index 00000000..8488bae5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedAeadBlockCipher.cs
@@ -0,0 +1,251 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ /**
+ * The AEAD block ciphers already handle buffering internally, so this class
+ * just takes care of implementing IBufferedCipher methods.
+ */
+ public class BufferedAeadBlockCipher
+ : BufferedCipherBase
+ {
+ private readonly IAeadBlockCipher cipher;
+
+ public BufferedAeadBlockCipher(
+ IAeadBlockCipher cipher)
+ {
+ if (cipher == null)
+ throw new ArgumentNullException("cipher");
+
+ this.cipher = cipher;
+ }
+
+ public override string AlgorithmName
+ {
+ get { return cipher.AlgorithmName; }
+ }
+
+ /**
+ * initialise the cipher.
+ *
+ * @param forEncryption if true the cipher is initialised for
+ * encryption, if false for decryption.
+ * @param param the key and other data required by the cipher.
+ * @exception ArgumentException if the parameters argument is
+ * inappropriate.
+ */
+ public override void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ if (parameters is ParametersWithRandom)
+ {
+ parameters = ((ParametersWithRandom) parameters).Parameters;
+ }
+
+ cipher.Init(forEncryption, parameters);
+ }
+
+ /**
+ * return the blocksize for the underlying cipher.
+ *
+ * @return the blocksize for the underlying cipher.
+ */
+ public override int GetBlockSize()
+ {
+ return cipher.GetBlockSize();
+ }
+
+ /**
+ * return the size of the output buffer required for an update
+ * an input of len bytes.
+ *
+ * @param len the length of the input.
+ * @return the space required to accommodate a call to update
+ * with len bytes of input.
+ */
+ public override int GetUpdateOutputSize(
+ int length)
+ {
+ return cipher.GetUpdateOutputSize(length);
+ }
+
+ /**
+ * return the size of the output buffer required for an update plus a
+ * doFinal with an input of len bytes.
+ *
+ * @param len the length of the input.
+ * @return the space required to accommodate a call to update and doFinal
+ * with len bytes of input.
+ */
+ public override int GetOutputSize(
+ int length)
+ {
+ return cipher.GetOutputSize(length);
+ }
+
+ /**
+ * process a single byte, producing an output block if necessary.
+ *
+ * @param in the input byte.
+ * @param out the space for any output that might be produced.
+ * @param outOff the offset from which the output will be copied.
+ * @return the number of output bytes copied to out.
+ * @exception DataLengthException if there isn't enough space in out.
+ * @exception InvalidOperationException if the cipher isn't initialised.
+ */
+ public override int ProcessByte(
+ byte input,
+ byte[] output,
+ int outOff)
+ {
+ return cipher.ProcessByte(input, output, outOff);
+ }
+
+ public override byte[] ProcessByte(
+ byte input)
+ {
+ int outLength = GetUpdateOutputSize(1);
+
+ byte[] outBytes = outLength > 0 ? new byte[outLength] : null;
+
+ int pos = ProcessByte(input, outBytes, 0);
+
+ if (outLength > 0 && pos < outLength)
+ {
+ byte[] tmp = new byte[pos];
+ Array.Copy(outBytes, 0, tmp, 0, pos);
+ outBytes = tmp;
+ }
+
+ return outBytes;
+ }
+
+ public override byte[] ProcessBytes(
+ byte[] input,
+ int inOff,
+ int length)
+ {
+ if (input == null)
+ throw new ArgumentNullException("input");
+ if (length < 1)
+ return null;
+
+ int outLength = GetUpdateOutputSize(length);
+
+ byte[] outBytes = outLength > 0 ? new byte[outLength] : null;
+
+ int pos = ProcessBytes(input, inOff, length, outBytes, 0);
+
+ if (outLength > 0 && pos < outLength)
+ {
+ byte[] tmp = new byte[pos];
+ Array.Copy(outBytes, 0, tmp, 0, pos);
+ outBytes = tmp;
+ }
+
+ return outBytes;
+ }
+
+ /**
+ * process an array of bytes, producing output if necessary.
+ *
+ * @param in the input byte array.
+ * @param inOff the offset at which the input data starts.
+ * @param len the number of bytes to be copied out of the input array.
+ * @param out the space for any output that might be produced.
+ * @param outOff the offset from which the output will be copied.
+ * @return the number of output bytes copied to out.
+ * @exception DataLengthException if there isn't enough space in out.
+ * @exception InvalidOperationException if the cipher isn't initialised.
+ */
+ public override int ProcessBytes(
+ byte[] input,
+ int inOff,
+ int length,
+ byte[] output,
+ int outOff)
+ {
+ return cipher.ProcessBytes(input, inOff, length, output, outOff);
+ }
+
+ public override byte[] DoFinal()
+ {
+ byte[] outBytes = new byte[GetOutputSize(0)];
+
+ int pos = DoFinal(outBytes, 0);
+
+ if (pos < outBytes.Length)
+ {
+ byte[] tmp = new byte[pos];
+ Array.Copy(outBytes, 0, tmp, 0, pos);
+ outBytes = tmp;
+ }
+
+ return outBytes;
+ }
+
+ public override byte[] DoFinal(
+ byte[] input,
+ int inOff,
+ int inLen)
+ {
+ if (input == null)
+ throw new ArgumentNullException("input");
+
+ byte[] outBytes = new byte[GetOutputSize(inLen)];
+
+ int pos = (inLen > 0)
+ ? ProcessBytes(input, inOff, inLen, outBytes, 0)
+ : 0;
+
+ pos += DoFinal(outBytes, pos);
+
+ if (pos < outBytes.Length)
+ {
+ byte[] tmp = new byte[pos];
+ Array.Copy(outBytes, 0, tmp, 0, pos);
+ outBytes = tmp;
+ }
+
+ return outBytes;
+ }
+
+ /**
+ * Process the last block in the buffer.
+ *
+ * @param out the array the block currently being held is copied into.
+ * @param outOff the offset at which the copying starts.
+ * @return the number of output bytes copied to out.
+ * @exception DataLengthException if there is insufficient space in out for
+ * the output, or the input is not block size aligned and should be.
+ * @exception InvalidOperationException if the underlying cipher is not
+ * initialised.
+ * @exception InvalidCipherTextException if padding is expected and not found.
+ * @exception DataLengthException if the input is not block size
+ * aligned.
+ */
+ public override int DoFinal(
+ byte[] output,
+ int outOff)
+ {
+ return cipher.DoFinal(output, outOff);
+ }
+
+ /**
+ * Reset the buffer and cipher. After resetting the object is in the same
+ * state as it was after the last init (if there was one).
+ */
+ public override void Reset()
+ {
+ cipher.Reset();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedAeadBlockCipher.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedAeadBlockCipher.cs.meta
new file mode 100644
index 00000000..faf3ebcb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedAeadBlockCipher.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 7341cef11d2e8f24e844590b6747bf16
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedAsymmetricBlockCipher.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedAsymmetricBlockCipher.cs
new file mode 100644
index 00000000..1ea38863
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedAsymmetricBlockCipher.cs
@@ -0,0 +1,156 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Diagnostics;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ /**
+ * a buffer wrapper for an asymmetric block cipher, allowing input
+ * to be accumulated in a piecemeal fashion until final processing.
+ */
+ public class BufferedAsymmetricBlockCipher
+ : BufferedCipherBase
+ {
+ private readonly IAsymmetricBlockCipher cipher;
+
+ private byte[] buffer;
+ private int bufOff;
+
+ /**
+ * base constructor.
+ *
+ * @param cipher the cipher this buffering object wraps.
+ */
+ public BufferedAsymmetricBlockCipher(
+ IAsymmetricBlockCipher cipher)
+ {
+ this.cipher = cipher;
+ }
+
+ /**
+ * return the amount of data sitting in the buffer.
+ *
+ * @return the amount of data sitting in the buffer.
+ */
+ internal int GetBufferPosition()
+ {
+ return bufOff;
+ }
+
+ public override string AlgorithmName
+ {
+ get { return cipher.AlgorithmName; }
+ }
+
+ public override int GetBlockSize()
+ {
+ return cipher.GetInputBlockSize();
+ }
+
+ public override int GetOutputSize(
+ int length)
+ {
+ return cipher.GetOutputBlockSize();
+ }
+
+ public override int GetUpdateOutputSize(
+ int length)
+ {
+ return 0;
+ }
+
+ /**
+ * initialise the buffer and the underlying cipher.
+ *
+ * @param forEncryption if true the cipher is initialised for
+ * encryption, if false for decryption.
+ * @param param the key and other data required by the cipher.
+ */
+ public override void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ Reset();
+
+ cipher.Init(forEncryption, parameters);
+
+ //
+ // we allow for an extra byte where people are using their own padding
+ // mechanisms on a raw cipher.
+ //
+ this.buffer = new byte[cipher.GetInputBlockSize() + (forEncryption ? 1 : 0)];
+ this.bufOff = 0;
+ }
+
+ public override byte[] ProcessByte(
+ byte input)
+ {
+ if (bufOff >= buffer.Length)
+ throw new DataLengthException("attempt to process message to long for cipher");
+
+ buffer[bufOff++] = input;
+ return null;
+ }
+
+ public override byte[] ProcessBytes(
+ byte[] input,
+ int inOff,
+ int length)
+ {
+ if (length < 1)
+ return null;
+
+ if (input == null)
+ throw new ArgumentNullException("input");
+ if (bufOff + length > buffer.Length)
+ throw new DataLengthException("attempt to process message to long for cipher");
+
+ Array.Copy(input, inOff, buffer, bufOff, length);
+ bufOff += length;
+ return null;
+ }
+
+ /**
+ * process the contents of the buffer using the underlying
+ * cipher.
+ *
+ * @return the result of the encryption/decryption process on the
+ * buffer.
+ * @exception InvalidCipherTextException if we are given a garbage block.
+ */
+ public override byte[] DoFinal()
+ {
+ byte[] outBytes = bufOff > 0
+ ? cipher.ProcessBlock(buffer, 0, bufOff)
+ : EmptyBuffer;
+
+ Reset();
+
+ return outBytes;
+ }
+
+ public override byte[] DoFinal(
+ byte[] input,
+ int inOff,
+ int length)
+ {
+ ProcessBytes(input, inOff, length);
+ return DoFinal();
+ }
+
+ /// Reset the buffer
+ public override void Reset()
+ {
+ if (buffer != null)
+ {
+ Array.Clear(buffer, 0, buffer.Length);
+ bufOff = 0;
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedAsymmetricBlockCipher.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedAsymmetricBlockCipher.cs.meta
new file mode 100644
index 00000000..eac7104d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedAsymmetricBlockCipher.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: f143b86b595928a4ba2e043ae553d1ce
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedBlockCipher.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedBlockCipher.cs
new file mode 100644
index 00000000..fcf48d29
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedBlockCipher.cs
@@ -0,0 +1,371 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Diagnostics;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ /**
+ * A wrapper class that allows block ciphers to be used to process data in
+ * a piecemeal fashion. The BufferedBlockCipher outputs a block only when the
+ * buffer is full and more data is being added, or on a doFinal.
+ *
+ * Note: in the case where the underlying cipher is either a CFB cipher or an
+ * OFB one the last block may not be a multiple of the block size.
+ *
+ */
+ public class BufferedBlockCipher
+ : BufferedCipherBase
+ {
+ internal byte[] buf;
+ internal int bufOff;
+ internal bool forEncryption;
+ internal IBlockCipher cipher;
+
+ /**
+ * constructor for subclasses
+ */
+ protected BufferedBlockCipher()
+ {
+ }
+
+ /**
+ * Create a buffered block cipher without padding.
+ *
+ * @param cipher the underlying block cipher this buffering object wraps.
+ * false otherwise.
+ */
+ public BufferedBlockCipher(
+ IBlockCipher cipher)
+ {
+ if (cipher == null)
+ throw new ArgumentNullException("cipher");
+
+ this.cipher = cipher;
+ buf = new byte[cipher.GetBlockSize()];
+ bufOff = 0;
+ }
+
+ public override string AlgorithmName
+ {
+ get { return cipher.AlgorithmName; }
+ }
+
+ /**
+ * initialise the cipher.
+ *
+ * @param forEncryption if true the cipher is initialised for
+ * encryption, if false for decryption.
+ * @param param the key and other data required by the cipher.
+ * @exception ArgumentException if the parameters argument is
+ * inappropriate.
+ */
+ // Note: This doubles as the Init in the event that this cipher is being used as an IWrapper
+ public override void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ this.forEncryption = forEncryption;
+
+ ParametersWithRandom pwr = parameters as ParametersWithRandom;
+ if (pwr != null)
+ parameters = pwr.Parameters;
+
+ Reset();
+
+ cipher.Init(forEncryption, parameters);
+ }
+
+ /**
+ * return the blocksize for the underlying cipher.
+ *
+ * @return the blocksize for the underlying cipher.
+ */
+ public override int GetBlockSize()
+ {
+ return cipher.GetBlockSize();
+ }
+
+ /**
+ * return the size of the output buffer required for an update
+ * an input of len bytes.
+ *
+ * @param len the length of the input.
+ * @return the space required to accommodate a call to update
+ * with len bytes of input.
+ */
+ public override int GetUpdateOutputSize(
+ int length)
+ {
+ int total = length + bufOff;
+ int leftOver = total % buf.Length;
+ return total - leftOver;
+ }
+
+ /**
+ * return the size of the output buffer required for an update plus a
+ * doFinal with an input of len bytes.
+ *
+ * @param len the length of the input.
+ * @return the space required to accommodate a call to update and doFinal
+ * with len bytes of input.
+ */
+ public override int GetOutputSize(
+ int length)
+ {
+ // Note: Can assume IsPartialBlockOkay is true for purposes of this calculation
+ return length + bufOff;
+ }
+
+ /**
+ * process a single byte, producing an output block if necessary.
+ *
+ * @param in the input byte.
+ * @param out the space for any output that might be produced.
+ * @param outOff the offset from which the output will be copied.
+ * @return the number of output bytes copied to out.
+ * @exception DataLengthException if there isn't enough space in out.
+ * @exception InvalidOperationException if the cipher isn't initialised.
+ */
+ public override int ProcessByte(
+ byte input,
+ byte[] output,
+ int outOff)
+ {
+ buf[bufOff++] = input;
+
+ if (bufOff == buf.Length)
+ {
+ if ((outOff + buf.Length) > output.Length)
+ throw new DataLengthException("output buffer too short");
+
+ bufOff = 0;
+ return cipher.ProcessBlock(buf, 0, output, outOff);
+ }
+
+ return 0;
+ }
+
+ public override byte[] ProcessByte(
+ byte input)
+ {
+ int outLength = GetUpdateOutputSize(1);
+
+ byte[] outBytes = outLength > 0 ? new byte[outLength] : null;
+
+ int pos = ProcessByte(input, outBytes, 0);
+
+ if (outLength > 0 && pos < outLength)
+ {
+ byte[] tmp = new byte[pos];
+ Array.Copy(outBytes, 0, tmp, 0, pos);
+ outBytes = tmp;
+ }
+
+ return outBytes;
+ }
+
+ public override byte[] ProcessBytes(
+ byte[] input,
+ int inOff,
+ int length)
+ {
+ if (input == null)
+ throw new ArgumentNullException("input");
+ if (length < 1)
+ return null;
+
+ int outLength = GetUpdateOutputSize(length);
+
+ byte[] outBytes = outLength > 0 ? new byte[outLength] : null;
+
+ int pos = ProcessBytes(input, inOff, length, outBytes, 0);
+
+ if (outLength > 0 && pos < outLength)
+ {
+ byte[] tmp = new byte[pos];
+ Array.Copy(outBytes, 0, tmp, 0, pos);
+ outBytes = tmp;
+ }
+
+ return outBytes;
+ }
+
+ /**
+ * process an array of bytes, producing output if necessary.
+ *
+ * @param in the input byte array.
+ * @param inOff the offset at which the input data starts.
+ * @param len the number of bytes to be copied out of the input array.
+ * @param out the space for any output that might be produced.
+ * @param outOff the offset from which the output will be copied.
+ * @return the number of output bytes copied to out.
+ * @exception DataLengthException if there isn't enough space in out.
+ * @exception InvalidOperationException if the cipher isn't initialised.
+ */
+ public override int ProcessBytes(
+ byte[] input,
+ int inOff,
+ int length,
+ byte[] output,
+ int outOff)
+ {
+ if (length < 1)
+ {
+ if (length < 0)
+ throw new ArgumentException("Can't have a negative input length!");
+
+ return 0;
+ }
+
+ int blockSize = GetBlockSize();
+ int outLength = GetUpdateOutputSize(length);
+
+ if (outLength > 0)
+ {
+ Check.OutputLength(output, outOff, outLength, "output buffer too short");
+ }
+
+ int resultLen = 0;
+ int gapLen = buf.Length - bufOff;
+ if (length > gapLen)
+ {
+ Array.Copy(input, inOff, buf, bufOff, gapLen);
+ resultLen += cipher.ProcessBlock(buf, 0, output, outOff);
+ bufOff = 0;
+ length -= gapLen;
+ inOff += gapLen;
+ while (length > buf.Length)
+ {
+ resultLen += cipher.ProcessBlock(input, inOff, output, outOff + resultLen);
+ length -= blockSize;
+ inOff += blockSize;
+ }
+ }
+ Array.Copy(input, inOff, buf, bufOff, length);
+ bufOff += length;
+ if (bufOff == buf.Length)
+ {
+ resultLen += cipher.ProcessBlock(buf, 0, output, outOff + resultLen);
+ bufOff = 0;
+ }
+ return resultLen;
+ }
+
+ public override byte[] DoFinal()
+ {
+ byte[] outBytes = EmptyBuffer;
+
+ int length = GetOutputSize(0);
+ if (length > 0)
+ {
+ outBytes = new byte[length];
+
+ int pos = DoFinal(outBytes, 0);
+ if (pos < outBytes.Length)
+ {
+ byte[] tmp = new byte[pos];
+ Array.Copy(outBytes, 0, tmp, 0, pos);
+ outBytes = tmp;
+ }
+ }
+ else
+ {
+ Reset();
+ }
+
+ return outBytes;
+ }
+
+ public override byte[] DoFinal(
+ byte[] input,
+ int inOff,
+ int inLen)
+ {
+ if (input == null)
+ throw new ArgumentNullException("input");
+
+ int length = GetOutputSize(inLen);
+
+ byte[] outBytes = EmptyBuffer;
+
+ if (length > 0)
+ {
+ outBytes = new byte[length];
+
+ int pos = (inLen > 0)
+ ? ProcessBytes(input, inOff, inLen, outBytes, 0)
+ : 0;
+
+ pos += DoFinal(outBytes, pos);
+
+ if (pos < outBytes.Length)
+ {
+ byte[] tmp = new byte[pos];
+ Array.Copy(outBytes, 0, tmp, 0, pos);
+ outBytes = tmp;
+ }
+ }
+ else
+ {
+ Reset();
+ }
+
+ return outBytes;
+ }
+
+ /**
+ * Process the last block in the buffer.
+ *
+ * @param out the array the block currently being held is copied into.
+ * @param outOff the offset at which the copying starts.
+ * @return the number of output bytes copied to out.
+ * @exception DataLengthException if there is insufficient space in out for
+ * the output, or the input is not block size aligned and should be.
+ * @exception InvalidOperationException if the underlying cipher is not
+ * initialised.
+ * @exception InvalidCipherTextException if padding is expected and not found.
+ * @exception DataLengthException if the input is not block size
+ * aligned.
+ */
+ public override int DoFinal(
+ byte[] output,
+ int outOff)
+ {
+ try
+ {
+ if (bufOff != 0)
+ {
+ Check.DataLength(!cipher.IsPartialBlockOkay, "data not block size aligned");
+ Check.OutputLength(output, outOff, bufOff, "output buffer too short for DoFinal()");
+
+ // NB: Can't copy directly, or we may write too much output
+ cipher.ProcessBlock(buf, 0, buf, 0);
+ Array.Copy(buf, 0, output, outOff, bufOff);
+ }
+
+ return bufOff;
+ }
+ finally
+ {
+ Reset();
+ }
+ }
+
+ /**
+ * Reset the buffer and cipher. After resetting the object is in the same
+ * state as it was after the last init (if there was one).
+ */
+ public override void Reset()
+ {
+ Array.Clear(buf, 0, buf.Length);
+ bufOff = 0;
+
+ cipher.Reset();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedBlockCipher.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedBlockCipher.cs.meta
new file mode 100644
index 00000000..0ed241ac
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedBlockCipher.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: e161ee652f7d84c49abc183b5ef37846
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedCipherBase.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedCipherBase.cs
new file mode 100644
index 00000000..7476ab40
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedCipherBase.cs
@@ -0,0 +1,117 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ public abstract class BufferedCipherBase
+ : IBufferedCipher
+ {
+ protected static readonly byte[] EmptyBuffer = new byte[0];
+
+ public abstract string AlgorithmName { get; }
+
+ public abstract void Init(bool forEncryption, ICipherParameters parameters);
+
+ public abstract int GetBlockSize();
+
+ public abstract int GetOutputSize(int inputLen);
+ public abstract int GetUpdateOutputSize(int inputLen);
+
+ public abstract byte[] ProcessByte(byte input);
+
+ public virtual int ProcessByte(
+ byte input,
+ byte[] output,
+ int outOff)
+ {
+ byte[] outBytes = ProcessByte(input);
+ if (outBytes == null)
+ return 0;
+ if (outOff + outBytes.Length > output.Length)
+ throw new DataLengthException("output buffer too short");
+ outBytes.CopyTo(output, outOff);
+ return outBytes.Length;
+ }
+
+ public virtual byte[] ProcessBytes(
+ byte[] input)
+ {
+ return ProcessBytes(input, 0, input.Length);
+ }
+
+ public abstract byte[] ProcessBytes(byte[] input, int inOff, int length);
+
+ public virtual int ProcessBytes(
+ byte[] input,
+ byte[] output,
+ int outOff)
+ {
+ return ProcessBytes(input, 0, input.Length, output, outOff);
+ }
+
+ public virtual int ProcessBytes(
+ byte[] input,
+ int inOff,
+ int length,
+ byte[] output,
+ int outOff)
+ {
+ byte[] outBytes = ProcessBytes(input, inOff, length);
+ if (outBytes == null)
+ return 0;
+ if (outOff + outBytes.Length > output.Length)
+ throw new DataLengthException("output buffer too short");
+ outBytes.CopyTo(output, outOff);
+ return outBytes.Length;
+ }
+
+ public abstract byte[] DoFinal();
+
+ public virtual byte[] DoFinal(
+ byte[] input)
+ {
+ return DoFinal(input, 0, input.Length);
+ }
+
+ public abstract byte[] DoFinal(
+ byte[] input,
+ int inOff,
+ int length);
+
+ public virtual int DoFinal(
+ byte[] output,
+ int outOff)
+ {
+ byte[] outBytes = DoFinal();
+ if (outOff + outBytes.Length > output.Length)
+ throw new DataLengthException("output buffer too short");
+ outBytes.CopyTo(output, outOff);
+ return outBytes.Length;
+ }
+
+ public virtual int DoFinal(
+ byte[] input,
+ byte[] output,
+ int outOff)
+ {
+ return DoFinal(input, 0, input.Length, output, outOff);
+ }
+
+ public virtual int DoFinal(
+ byte[] input,
+ int inOff,
+ int length,
+ byte[] output,
+ int outOff)
+ {
+ int len = ProcessBytes(input, inOff, length, output, outOff);
+ len += DoFinal(output, outOff + len);
+ return len;
+ }
+
+ public abstract void Reset();
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedCipherBase.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedCipherBase.cs.meta
new file mode 100644
index 00000000..b1ea27b9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedCipherBase.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 2c014e96623bd48488c402407e71df96
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedIesCipher.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedIesCipher.cs
new file mode 100644
index 00000000..855841a8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedIesCipher.cs
@@ -0,0 +1,117 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ public class BufferedIesCipher
+ : BufferedCipherBase
+ {
+ private readonly IesEngine engine;
+ private bool forEncryption;
+ private MemoryStream buffer = new MemoryStream();
+
+ public BufferedIesCipher(
+ IesEngine engine)
+ {
+ if (engine == null)
+ throw new ArgumentNullException("engine");
+
+ this.engine = engine;
+ }
+
+ public override string AlgorithmName
+ {
+ // TODO Create IESEngine.AlgorithmName
+ get { return "IES"; }
+ }
+
+ public override void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ this.forEncryption = forEncryption;
+
+ // TODO
+ throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("IES");
+ }
+
+ public override int GetBlockSize()
+ {
+ return 0;
+ }
+
+ public override int GetOutputSize(
+ int inputLen)
+ {
+ if (engine == null)
+ throw new InvalidOperationException("cipher not initialised");
+
+ int baseLen = inputLen + (int) buffer.Length;
+ return forEncryption
+ ? baseLen + 20
+ : baseLen - 20;
+ }
+
+ public override int GetUpdateOutputSize(
+ int inputLen)
+ {
+ return 0;
+ }
+
+ public override byte[] ProcessByte(
+ byte input)
+ {
+ buffer.WriteByte(input);
+ return null;
+ }
+
+ public override byte[] ProcessBytes(
+ byte[] input,
+ int inOff,
+ int length)
+ {
+ if (input == null)
+ throw new ArgumentNullException("input");
+ if (inOff < 0)
+ throw new ArgumentException("inOff");
+ if (length < 0)
+ throw new ArgumentException("length");
+ if (inOff + length > input.Length)
+ throw new ArgumentException("invalid offset/length specified for input array");
+
+ buffer.Write(input, inOff, length);
+ return null;
+ }
+
+ public override byte[] DoFinal()
+ {
+ byte[] buf = buffer.ToArray();
+
+ Reset();
+
+ return engine.ProcessBlock(buf, 0, buf.Length);
+ }
+
+ public override byte[] DoFinal(
+ byte[] input,
+ int inOff,
+ int length)
+ {
+ ProcessBytes(input, inOff, length);
+ return DoFinal();
+ }
+
+ public override void Reset()
+ {
+ buffer.SetLength(0);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedIesCipher.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedIesCipher.cs.meta
new file mode 100644
index 00000000..0951783f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedIesCipher.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: b73c34a06bcbdb3449c9b9221fc8a9c2
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedStreamCipher.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedStreamCipher.cs
new file mode 100644
index 00000000..20bc603d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedStreamCipher.cs
@@ -0,0 +1,135 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ public class BufferedStreamCipher
+ : BufferedCipherBase
+ {
+ private readonly IStreamCipher cipher;
+
+ public BufferedStreamCipher(
+ IStreamCipher cipher)
+ {
+ if (cipher == null)
+ throw new ArgumentNullException("cipher");
+
+ this.cipher = cipher;
+ }
+
+ public override string AlgorithmName
+ {
+ get { return cipher.AlgorithmName; }
+ }
+
+ public override void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ if (parameters is ParametersWithRandom)
+ {
+ parameters = ((ParametersWithRandom) parameters).Parameters;
+ }
+
+ cipher.Init(forEncryption, parameters);
+ }
+
+ public override int GetBlockSize()
+ {
+ return 0;
+ }
+
+ public override int GetOutputSize(
+ int inputLen)
+ {
+ return inputLen;
+ }
+
+ public override int GetUpdateOutputSize(
+ int inputLen)
+ {
+ return inputLen;
+ }
+
+ public override byte[] ProcessByte(
+ byte input)
+ {
+ return new byte[]{ cipher.ReturnByte(input) };
+ }
+
+ public override int ProcessByte(
+ byte input,
+ byte[] output,
+ int outOff)
+ {
+ if (outOff >= output.Length)
+ throw new DataLengthException("output buffer too short");
+
+ output[outOff] = cipher.ReturnByte(input);
+ return 1;
+ }
+
+ public override byte[] ProcessBytes(
+ byte[] input,
+ int inOff,
+ int length)
+ {
+ if (length < 1)
+ return null;
+
+ byte[] output = new byte[length];
+ cipher.ProcessBytes(input, inOff, length, output, 0);
+ return output;
+ }
+
+ public override int ProcessBytes(
+ byte[] input,
+ int inOff,
+ int length,
+ byte[] output,
+ int outOff)
+ {
+ if (length < 1)
+ return 0;
+
+ if (length > 0)
+ {
+ cipher.ProcessBytes(input, inOff, length, output, outOff);
+ }
+
+ return length;
+ }
+
+ public override byte[] DoFinal()
+ {
+ Reset();
+
+ return EmptyBuffer;
+ }
+
+ public override byte[] DoFinal(
+ byte[] input,
+ int inOff,
+ int length)
+ {
+ if (length < 1)
+ return EmptyBuffer;
+
+ byte[] output = ProcessBytes(input, inOff, length);
+
+ Reset();
+
+ return output;
+ }
+
+ public override void Reset()
+ {
+ cipher.Reset();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedStreamCipher.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedStreamCipher.cs.meta
new file mode 100644
index 00000000..e0f41bc2
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/BufferedStreamCipher.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 3f552bd4118a37e46b3c3e8b94df1660
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/Check.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/Check.cs
new file mode 100644
index 00000000..53024c1a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/Check.cs
@@ -0,0 +1,29 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ internal class Check
+ {
+ internal static void DataLength(bool condition, string msg)
+ {
+ if (condition)
+ throw new DataLengthException(msg);
+ }
+
+ internal static void DataLength(byte[] buf, int off, int len, string msg)
+ {
+ if (off + len > buf.Length)
+ throw new DataLengthException(msg);
+ }
+
+ internal static void OutputLength(byte[] buf, int off, int len, string msg)
+ {
+ if (off + len > buf.Length)
+ throw new OutputLengthException(msg);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/Check.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/Check.cs.meta
new file mode 100644
index 00000000..30f8a3d6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/Check.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 6dd41045620467949adfc127f66c0e85
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/CipherKeyGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/CipherKeyGenerator.cs
new file mode 100644
index 00000000..87e01e64
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/CipherKeyGenerator.cs
@@ -0,0 +1,87 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ /**
+ * The base class for symmetric, or secret, cipher key generators.
+ */
+ public class CipherKeyGenerator
+ {
+ protected internal SecureRandom random;
+ protected internal int strength;
+ private bool uninitialised = true;
+ private int defaultStrength;
+
+ public CipherKeyGenerator()
+ {
+ }
+
+ internal CipherKeyGenerator(
+ int defaultStrength)
+ {
+ if (defaultStrength < 1)
+ throw new ArgumentException("strength must be a positive value", "defaultStrength");
+
+ this.defaultStrength = defaultStrength;
+ }
+
+ public int DefaultStrength
+ {
+ get { return defaultStrength; }
+ }
+
+ /**
+ * initialise the key generator.
+ *
+ * @param param the parameters to be used for key generation
+ */
+ public void Init(
+ KeyGenerationParameters parameters)
+ {
+ if (parameters == null)
+ throw new ArgumentNullException("parameters");
+
+ this.uninitialised = false;
+
+ engineInit(parameters);
+ }
+
+ protected virtual void engineInit(
+ KeyGenerationParameters parameters)
+ {
+ this.random = parameters.Random;
+ this.strength = (parameters.Strength + 7) / 8;
+ }
+
+ /**
+ * Generate a secret key.
+ *
+ * @return a byte array containing the key value.
+ */
+ public byte[] GenerateKey()
+ {
+ if (uninitialised)
+ {
+ if (defaultStrength < 1)
+ throw new InvalidOperationException("Generator has not been initialised");
+
+ uninitialised = false;
+
+ engineInit(new KeyGenerationParameters(new SecureRandom(), defaultStrength));
+ }
+
+ return engineGenerateKey();
+ }
+
+ protected virtual byte[] engineGenerateKey()
+ {
+ return SecureRandom.GetNextBytes(random, strength);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/CipherKeyGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/CipherKeyGenerator.cs.meta
new file mode 100644
index 00000000..f465116f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/CipherKeyGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 83b99673c89b7be4491f695d8e374d3c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/CryptoException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/CryptoException.cs
new file mode 100644
index 00000000..96068045
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/CryptoException.cs
@@ -0,0 +1,32 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class CryptoException
+ : Exception
+ {
+ public CryptoException()
+ {
+ }
+
+ public CryptoException(
+ string message)
+ : base(message)
+ {
+ }
+
+ public CryptoException(
+ string message,
+ Exception exception)
+ : base(message, exception)
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/CryptoException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/CryptoException.cs.meta
new file mode 100644
index 00000000..25a38b6e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/CryptoException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: cd38a0fa65d30fc4eae48fa3319f9645
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/DataLengthException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/DataLengthException.cs
new file mode 100644
index 00000000..6fecb954
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/DataLengthException.cs
@@ -0,0 +1,46 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ /**
+ * this exception is thrown if a buffer that is meant to have output
+ * copied into it turns out to be too short, or if we've been given
+ * insufficient input. In general this exception will Get thrown rather
+ * than an ArrayOutOfBounds exception.
+ */
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class DataLengthException
+ : CryptoException
+ {
+ /**
+ * base constructor.
+ */
+ public DataLengthException()
+ {
+ }
+
+ /**
+ * create a DataLengthException with the given message.
+ *
+ * @param message the message to be carried with the exception.
+ */
+ public DataLengthException(
+ string message)
+ : base(message)
+ {
+ }
+
+ public DataLengthException(
+ string message,
+ Exception exception)
+ : base(message, exception)
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/DataLengthException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/DataLengthException.cs.meta
new file mode 100644
index 00000000..4fe44ff1
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/DataLengthException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 34a508389e47f4745921ea8106b00645
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IAsymmetricBlockCipher.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IAsymmetricBlockCipher.cs
new file mode 100644
index 00000000..8fba447e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IAsymmetricBlockCipher.cs
@@ -0,0 +1,34 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ /// Base interface for a public/private key block cipher.
+ public interface IAsymmetricBlockCipher
+ {
+ /// The name of the algorithm this cipher implements.
+ string AlgorithmName { get; }
+
+ /// Initialise the cipher.
+ /// Initialise for encryption if true, for decryption if false.
+ /// The key or other data required by the cipher.
+ void Init(bool forEncryption, ICipherParameters parameters);
+
+ /// The maximum size, in bytes, an input block may be.
+ int GetInputBlockSize();
+
+ /// The maximum size, in bytes, an output block will be.
+ int GetOutputBlockSize();
+
+ /// Process a block.
+ /// The input buffer.
+ /// The offset into inBuf that the input block begins.
+ /// The length of the input block.
+ /// Input decrypts improperly.
+ /// Input is too large for the cipher.
+ byte[] ProcessBlock(byte[] inBuf, int inOff, int inLen);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IAsymmetricBlockCipher.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IAsymmetricBlockCipher.cs.meta
new file mode 100644
index 00000000..88685e0a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IAsymmetricBlockCipher.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 6abbe02392e03f543a957ac413172bd3
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IAsymmetricCipherKeyPairGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IAsymmetricCipherKeyPairGenerator.cs
new file mode 100644
index 00000000..a67c7dc8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IAsymmetricCipherKeyPairGenerator.cs
@@ -0,0 +1,28 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ /**
+ * interface that a public/private key pair generator should conform to.
+ */
+ public interface IAsymmetricCipherKeyPairGenerator
+ {
+ /**
+ * intialise the key pair generator.
+ *
+ * @param the parameters the key pair is to be initialised with.
+ */
+ void Init(KeyGenerationParameters parameters);
+
+ /**
+ * return an AsymmetricCipherKeyPair containing the Generated keys.
+ *
+ * @return an AsymmetricCipherKeyPair containing the Generated keys.
+ */
+ AsymmetricCipherKeyPair GenerateKeyPair();
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IAsymmetricCipherKeyPairGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IAsymmetricCipherKeyPairGenerator.cs.meta
new file mode 100644
index 00000000..736a0567
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IAsymmetricCipherKeyPairGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: af1fbd88542b90240bb580ea2247b4cf
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IBasicAgreement.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IBasicAgreement.cs
new file mode 100644
index 00000000..e46733b8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IBasicAgreement.cs
@@ -0,0 +1,33 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ /**
+ * The basic interface that basic Diffie-Hellman implementations
+ * conforms to.
+ */
+ public interface IBasicAgreement
+ {
+ /**
+ * initialise the agreement engine.
+ */
+ void Init(ICipherParameters parameters);
+
+ /**
+ * return the field size for the agreement algorithm in bytes.
+ */
+ int GetFieldSize();
+
+ /**
+ * given a public key from a given party calculate the next
+ * message in the agreement sequence.
+ */
+ BigInteger CalculateAgreement(ICipherParameters pubKey);
+ }
+
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IBasicAgreement.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IBasicAgreement.cs.meta
new file mode 100644
index 00000000..f248610b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IBasicAgreement.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: cd9d504c0c209eb4ab0ba46c3f015a85
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IBlockCipher.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IBlockCipher.cs
new file mode 100644
index 00000000..ca98a4a8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IBlockCipher.cs
@@ -0,0 +1,40 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ /// Base interface for a symmetric key block cipher.
+ public interface IBlockCipher
+ {
+ /// The name of the algorithm this cipher implements.
+ string AlgorithmName { get; }
+
+ /// Initialise the cipher.
+ /// Initialise for encryption if true, for decryption if false.
+ /// The key or other data required by the cipher.
+ void Init(bool forEncryption, ICipherParameters parameters);
+
+ /// The block size for this cipher, in bytes.
+ int GetBlockSize();
+
+ /// Indicates whether this cipher can handle partial blocks.
+ bool IsPartialBlockOkay { get; }
+
+ /// Process a block.
+ /// The input buffer.
+ /// The offset into inBuf that the input block begins.
+ /// The output buffer.
+ /// The offset into outBuf to write the output block.
+ /// If input block is wrong size, or outBuf too small.
+ /// The number of bytes processed and produced.
+ int ProcessBlock(byte[] inBuf, int inOff, byte[] outBuf, int outOff);
+
+ ///
+ /// Reset the cipher to the same state as it was after the last init (if there was one).
+ ///
+ void Reset();
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IBlockCipher.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IBlockCipher.cs.meta
new file mode 100644
index 00000000..1fbd3c75
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IBlockCipher.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 4935d5699e88bf6459028d927973e8af
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IBlockResult.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IBlockResult.cs
new file mode 100644
index 00000000..d003e0e7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IBlockResult.cs
@@ -0,0 +1,28 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ ///
+ /// Operators that reduce their input to a single block return an object
+ /// of this type.
+ ///
+ public interface IBlockResult
+ {
+ ///
+ /// Return the final result of the operation.
+ ///
+ /// A block of bytes, representing the result of an operation.
+ byte[] Collect();
+
+ ///
+ /// Store the final result of the operation by copying it into the destination array.
+ ///
+ /// The number of bytes copied into destination.
+ /// The byte array to copy the result into.
+ /// The offset into destination to start copying the result at.
+ int Collect(byte[] destination, int offset);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IBlockResult.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IBlockResult.cs.meta
new file mode 100644
index 00000000..e6b803d9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IBlockResult.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 8ffde966c8f3b9c4282b23834e282a0c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IBufferedCipher.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IBufferedCipher.cs
new file mode 100644
index 00000000..29d09e81
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IBufferedCipher.cs
@@ -0,0 +1,48 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ /// Block cipher engines are expected to conform to this interface.
+ public interface IBufferedCipher
+ {
+ /// The name of the algorithm this cipher implements.
+ string AlgorithmName { get; }
+
+ /// Initialise the cipher.
+ /// If true the cipher is initialised for encryption,
+ /// if false for decryption.
+ /// The key and other data required by the cipher.
+ void Init(bool forEncryption, ICipherParameters parameters);
+
+ int GetBlockSize();
+
+ int GetOutputSize(int inputLen);
+
+ int GetUpdateOutputSize(int inputLen);
+
+ byte[] ProcessByte(byte input);
+ int ProcessByte(byte input, byte[] output, int outOff);
+
+ byte[] ProcessBytes(byte[] input);
+ byte[] ProcessBytes(byte[] input, int inOff, int length);
+ int ProcessBytes(byte[] input, byte[] output, int outOff);
+ int ProcessBytes(byte[] input, int inOff, int length, byte[] output, int outOff);
+
+ byte[] DoFinal();
+ byte[] DoFinal(byte[] input);
+ byte[] DoFinal(byte[] input, int inOff, int length);
+ int DoFinal(byte[] output, int outOff);
+ int DoFinal(byte[] input, byte[] output, int outOff);
+ int DoFinal(byte[] input, int inOff, int length, byte[] output, int outOff);
+
+ ///
+ /// Reset the cipher. After resetting the cipher is in the same state
+ /// as it was after the last init (if there was one).
+ ///
+ void Reset();
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IBufferedCipher.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IBufferedCipher.cs.meta
new file mode 100644
index 00000000..34fb872b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IBufferedCipher.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c8a92034d413bfc40b6680d876d7f8b1
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/ICipherParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/ICipherParameters.cs
new file mode 100644
index 00000000..7768de10
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/ICipherParameters.cs
@@ -0,0 +1,15 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ /**
+ * all parameter classes implement this.
+ */
+ public interface ICipherParameters
+ {
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/ICipherParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/ICipherParameters.cs.meta
new file mode 100644
index 00000000..610be997
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/ICipherParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 48f7fda0d1eff294e9c36d8da4c5b237
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDSA.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDSA.cs
new file mode 100644
index 00000000..7966c06d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDSA.cs
@@ -0,0 +1,45 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ /**
+ * interface for classes implementing the Digital Signature Algorithm
+ */
+ public interface IDsa
+ {
+ string AlgorithmName { get; }
+
+ /**
+ * initialise the signer for signature generation or signature
+ * verification.
+ *
+ * @param forSigning true if we are generating a signature, false
+ * otherwise.
+ * @param param key parameters for signature generation.
+ */
+ void Init(bool forSigning, ICipherParameters parameters);
+
+ /**
+ * sign the passed in message (usually the output of a hash function).
+ *
+ * @param message the message to be signed.
+ * @return two big integers representing the r and s values respectively.
+ */
+ BigInteger[] GenerateSignature(byte[] message);
+
+ /**
+ * verify the message message against the signature values r and s.
+ *
+ * @param message the message that was supposed to have been signed.
+ * @param r the r signature value.
+ * @param s the s signature value.
+ */
+ bool VerifySignature(byte[] message, BigInteger r, BigInteger s);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDSA.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDSA.cs.meta
new file mode 100644
index 00000000..312883bb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDSA.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 8cc954fc8fc070a45955c5a315ebc07a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDerivationFunction.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDerivationFunction.cs
new file mode 100644
index 00000000..dda4764c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDerivationFunction.cs
@@ -0,0 +1,28 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ /**
+ * base interface for general purpose byte derivation functions.
+ */
+ public interface IDerivationFunction
+ {
+ void Init(IDerivationParameters parameters);
+
+ /**
+ * return the message digest used as the basis for the function
+ */
+ IDigest Digest
+ {
+ get;
+ }
+
+ int GenerateBytes(byte[] output, int outOff, int length);
+ //throws DataLengthException, ArgumentException;
+ }
+
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDerivationFunction.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDerivationFunction.cs.meta
new file mode 100644
index 00000000..10f91f5a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDerivationFunction.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 4485e5cea1db5dc4ebed2d30a3bfa672
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDerivationParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDerivationParameters.cs
new file mode 100644
index 00000000..4d659639
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDerivationParameters.cs
@@ -0,0 +1,15 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ /**
+ * Parameters for key/byte stream derivation classes
+ */
+ public interface IDerivationParameters
+ {
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDerivationParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDerivationParameters.cs.meta
new file mode 100644
index 00000000..c1eee885
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDerivationParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ea9b134ee70b91b42b1ad2b5bf68204c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDigest.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDigest.cs
new file mode 100644
index 00000000..db4d58c3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDigest.cs
@@ -0,0 +1,65 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ /**
+ * interface that a message digest conforms to.
+ */
+ public interface IDigest
+ {
+ /**
+ * return the algorithm name
+ *
+ * @return the algorithm name
+ */
+ string AlgorithmName { get; }
+
+ /**
+ * return the size, in bytes, of the digest produced by this message digest.
+ *
+ * @return the size, in bytes, of the digest produced by this message digest.
+ */
+ int GetDigestSize();
+
+ /**
+ * return the size, in bytes, of the internal buffer used by this digest.
+ *
+ * @return the size, in bytes, of the internal buffer used by this digest.
+ */
+ int GetByteLength();
+
+ /**
+ * update the message digest with a single byte.
+ *
+ * @param inByte the input byte to be entered.
+ */
+ void Update(byte input);
+
+ /**
+ * update the message digest with a block of bytes.
+ *
+ * @param input the byte array containing the data.
+ * @param inOff the offset into the byte array where the data starts.
+ * @param len the length of the data.
+ */
+ void BlockUpdate(byte[] input, int inOff, int length);
+
+ /**
+ * Close the digest, producing the final digest value. The doFinal
+ * call leaves the digest reset.
+ *
+ * @param output the array the digest is to be copied into.
+ * @param outOff the offset into the out array the digest is to start at.
+ */
+ int DoFinal(byte[] output, int outOff);
+
+ /**
+ * reset the digest back to it's initial state.
+ */
+ void Reset();
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDigest.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDigest.cs.meta
new file mode 100644
index 00000000..819ccdc8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDigest.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 232948e340c96d0439b8c002b2ab0ec9
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDsaExt.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDsaExt.cs
new file mode 100644
index 00000000..01f936e2
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDsaExt.cs
@@ -0,0 +1,21 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ ///
+ /// An "extended" interface for classes implementing DSA-style algorithms, that provides access
+ /// to the group order.
+ ///
+ public interface IDsaExt
+ : IDsa
+ {
+ /// The order of the group that the r, s values in signatures belong to.
+ BigInteger Order { get; }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDsaExt.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDsaExt.cs.meta
new file mode 100644
index 00000000..ff629af7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IDsaExt.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 9976406cf62ec74429d860be2fec2ec0
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IEntropySource.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IEntropySource.cs
new file mode 100644
index 00000000..cfe0f696
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IEntropySource.cs
@@ -0,0 +1,33 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ ///
+ /// Base interface describing an entropy source for a DRBG.
+ ///
+ public interface IEntropySource
+ {
+ ///
+ /// Return whether or not this entropy source is regarded as prediction resistant.
+ ///
+ /// true if this instance is prediction resistant; otherwise, false.
+ bool IsPredictionResistant { get; }
+
+ ///
+ /// Return a byte array of entropy.
+ ///
+ /// The entropy bytes.
+ byte[] GetEntropy();
+
+ ///
+ /// Return the number of bits of entropy this source can produce.
+ ///
+ /// The size, in bits, of the return value of getEntropy.
+ int EntropySize { get; }
+ }
+}
+
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IEntropySource.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IEntropySource.cs.meta
new file mode 100644
index 00000000..26f3565d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IEntropySource.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: b41ded217d64e9d4a88e5a4f45785906
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IEntropySourceProvider.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IEntropySourceProvider.cs
new file mode 100644
index 00000000..f1e7c1bc
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IEntropySourceProvider.cs
@@ -0,0 +1,21 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ ///
+ /// Base interface describing a provider of entropy sources.
+ ///
+ public interface IEntropySourceProvider
+ {
+ ///
+ /// Return an entropy source providing a block of entropy.
+ ///
+ /// The size of the block of entropy required.
+ /// An entropy source providing bitsRequired blocks of entropy.
+ IEntropySource Get(int bitsRequired);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IEntropySourceProvider.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IEntropySourceProvider.cs.meta
new file mode 100644
index 00000000..6c118104
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IEntropySourceProvider.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a4e94522d8beb6942a87bb520c8bcbe1
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IMac.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IMac.cs
new file mode 100644
index 00000000..e4810e17
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IMac.cs
@@ -0,0 +1,73 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ /**
+ * The base interface for implementations of message authentication codes (MACs).
+ */
+ public interface IMac
+ {
+ /**
+ * Initialise the MAC.
+ *
+ * @param param the key and other data required by the MAC.
+ * @exception ArgumentException if the parameters argument is
+ * inappropriate.
+ */
+ void Init(ICipherParameters parameters);
+
+ /**
+ * Return the name of the algorithm the MAC implements.
+ *
+ * @return the name of the algorithm the MAC implements.
+ */
+ string AlgorithmName { get; }
+
+ /**
+ * Return the block size for this MAC (in bytes).
+ *
+ * @return the block size for this MAC in bytes.
+ */
+ int GetMacSize();
+
+ /**
+ * add a single byte to the mac for processing.
+ *
+ * @param in the byte to be processed.
+ * @exception InvalidOperationException if the MAC is not initialised.
+ */
+ void Update(byte input);
+
+ /**
+ * @param in the array containing the input.
+ * @param inOff the index in the array the data begins at.
+ * @param len the length of the input starting at inOff.
+ * @exception InvalidOperationException if the MAC is not initialised.
+ * @exception DataLengthException if there isn't enough data in in.
+ */
+ void BlockUpdate(byte[] input, int inOff, int len);
+
+ /**
+ * Compute the final stage of the MAC writing the output to the out
+ * parameter.
+ *
+ * doFinal leaves the MAC in the same state it was after the last init.
+ *
+ * @param out the array the MAC is to be output to.
+ * @param outOff the offset into the out buffer the output is to start at.
+ * @exception DataLengthException if there isn't enough space in out.
+ * @exception InvalidOperationException if the MAC is not initialised.
+ */
+ int DoFinal(byte[] output, int outOff);
+
+ /**
+ * Reset the MAC. At the end of resetting the MAC should be in the
+ * in the same state it was after the last init (if there was one).
+ */
+ void Reset();
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IMac.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IMac.cs.meta
new file mode 100644
index 00000000..f0fc5d77
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IMac.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 06c6c4ff752285d4181fc6f0f7a3bbc1
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IRawAgreement.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IRawAgreement.cs
new file mode 100644
index 00000000..91146e0b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IRawAgreement.cs
@@ -0,0 +1,17 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ public interface IRawAgreement
+ {
+ void Init(ICipherParameters parameters);
+
+ int AgreementSize { get; }
+
+ void CalculateAgreement(ICipherParameters publicKey, byte[] buf, int off);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IRawAgreement.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IRawAgreement.cs.meta
new file mode 100644
index 00000000..13cc19ab
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IRawAgreement.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a4955c6838f252e4cba62fb0ee5dc679
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IRsa.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IRsa.cs
new file mode 100644
index 00000000..8d9d1ce4
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IRsa.cs
@@ -0,0 +1,20 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ public interface IRsa
+ {
+ void Init(bool forEncryption, ICipherParameters parameters);
+ int GetInputBlockSize();
+ int GetOutputBlockSize();
+ BigInteger ConvertInput(byte[] buf, int off, int len);
+ BigInteger ProcessBlock(BigInteger input);
+ byte[] ConvertOutput(BigInteger result);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IRsa.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IRsa.cs.meta
new file mode 100644
index 00000000..6bc536e6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IRsa.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: bfae5f5df323ffa4d878ad34f7914052
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/ISignatureFactory.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/ISignatureFactory.cs
new file mode 100644
index 00000000..95dba2e8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/ISignatureFactory.cs
@@ -0,0 +1,27 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ ///
+ /// Base interface for operators that serve as stream-based signature calculators.
+ ///
+ public interface ISignatureFactory
+ {
+ /// The algorithm details object for this calculator.
+ Object AlgorithmDetails { get ; }
+
+ ///
+ /// Create a stream calculator for this signature calculator. The stream
+ /// calculator is used for the actual operation of entering the data to be signed
+ /// and producing the signature block.
+ ///
+ /// A calculator producing an IBlockResult with a signature in it.
+ IStreamCalculator CreateCalculator();
+ }
+}
+
+
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/ISignatureFactory.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/ISignatureFactory.cs.meta
new file mode 100644
index 00000000..5c1be3ea
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/ISignatureFactory.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 9b932d94d8fe22545b8c91109d2bf521
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/ISigner.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/ISigner.cs
new file mode 100644
index 00000000..0d50cefb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/ISigner.cs
@@ -0,0 +1,54 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+
+using System;
+using System.Text;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ public interface ISigner
+ {
+ /**
+ * Return the name of the algorithm the signer implements.
+ *
+ * @return the name of the algorithm the signer implements.
+ */
+ string AlgorithmName { get; }
+
+ /**
+ * Initialise the signer for signing or verification.
+ *
+ * @param forSigning true if for signing, false otherwise
+ * @param param necessary parameters.
+ */
+ void Init(bool forSigning, ICipherParameters parameters);
+
+ /**
+ * update the internal digest with the byte b
+ */
+ void Update(byte input);
+
+ /**
+ * update the internal digest with the byte array in
+ */
+ void BlockUpdate(byte[] input, int inOff, int length);
+
+ /**
+ * Generate a signature for the message we've been loaded with using
+ * the key we were initialised with.
+ */
+ byte[] GenerateSignature();
+ /**
+ * return true if the internal state represents the signature described
+ * in the passed in array.
+ */
+ bool VerifySignature(byte[] signature);
+
+ /**
+ * reset the internal state
+ */
+ void Reset();
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/ISigner.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/ISigner.cs.meta
new file mode 100644
index 00000000..cbe2da52
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/ISigner.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a3bcb10b760d17945bfcb44c2b23d5a7
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/ISignerWithRecovery.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/ISignerWithRecovery.cs
new file mode 100644
index 00000000..5c26f8d8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/ISignerWithRecovery.cs
@@ -0,0 +1,41 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Text;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ /**
+ * Signer with message recovery.
+ */
+ public interface ISignerWithRecovery
+ : ISigner
+ {
+ /**
+ * Returns true if the signer has recovered the full message as
+ * part of signature verification.
+ *
+ * @return true if full message recovered.
+ */
+ bool HasFullMessage();
+
+ /**
+ * Returns a reference to what message was recovered (if any).
+ *
+ * @return full/partial message, null if nothing.
+ */
+ byte[] GetRecoveredMessage();
+
+ /**
+ * Perform an update with the recovered message before adding any other data. This must
+ * be the first update method called, and calling it will result in the signer assuming
+ * that further calls to update will include message content past what is recoverable.
+ *
+ * @param signature the signature that we are in the process of verifying.
+ * @throws IllegalStateException
+ */
+ void UpdateWithRecoveredMessage(byte[] signature);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/ISignerWithRecovery.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/ISignerWithRecovery.cs.meta
new file mode 100644
index 00000000..dc03b037
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/ISignerWithRecovery.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: e65905090a3ed6d4d8a088adeef895f6
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IStreamCalculator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IStreamCalculator.cs
new file mode 100644
index 00000000..21966844
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IStreamCalculator.cs
@@ -0,0 +1,27 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ ///
+ /// Base interface for cryptographic operations such as Hashes, MACs, and Signatures which reduce a stream of data
+ /// to a single value.
+ ///
+ public interface IStreamCalculator
+ {
+ /// Return a "sink" stream which only exists to update the implementing object.
+ /// A stream to write to in order to update the implementing object.
+ Stream Stream { get; }
+
+ ///
+ /// Return the result of processing the stream. This value is only available once the stream
+ /// has been closed.
+ ///
+ /// The result of processing the stream.
+ Object GetResult();
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IStreamCalculator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IStreamCalculator.cs.meta
new file mode 100644
index 00000000..7aa32294
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IStreamCalculator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 71c66ead22110194abc4b7138f2fa247
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IStreamCipher.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IStreamCipher.cs
new file mode 100644
index 00000000..56017185
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IStreamCipher.cs
@@ -0,0 +1,49 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ /// The interface stream ciphers conform to.
+ public interface IStreamCipher
+ {
+ /// The name of the algorithm this cipher implements.
+ string AlgorithmName { get; }
+
+ /// Initialise the cipher.
+ /// If true the cipher is initialised for encryption,
+ /// if false for decryption.
+ /// The key and other data required by the cipher.
+ ///
+ /// If the parameters argument is inappropriate.
+ ///
+ void Init(bool forEncryption, ICipherParameters parameters);
+
+ /// encrypt/decrypt a single byte returning the result.
+ /// the byte to be processed.
+ /// the result of processing the input byte.
+ byte ReturnByte(byte input);
+
+ ///
+ /// Process a block of bytes from input putting the result into output.
+ ///
+ /// The input byte array.
+ ///
+ /// The offset into input where the data to be processed starts.
+ ///
+ /// The number of bytes to be processed.
+ /// The output buffer the processed bytes go into.
+ ///
+ /// The offset into output the processed data starts at.
+ ///
+ /// If the output buffer is too small.
+ void ProcessBytes(byte[] input, int inOff, int length, byte[] output, int outOff);
+
+ ///
+ /// Reset the cipher to the same state as it was after the last init (if there was one).
+ ///
+ void Reset();
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IStreamCipher.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IStreamCipher.cs.meta
new file mode 100644
index 00000000..be0d38cb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IStreamCipher.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ef95f78d58f8f2848a0600acae2dbde9
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IVerifier.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IVerifier.cs
new file mode 100644
index 00000000..255204a8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IVerifier.cs
@@ -0,0 +1,29 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ ///
+ /// Operators that reduce their input to the validation of a signature produce this type.
+ ///
+ public interface IVerifier
+ {
+ ///
+ /// Return true if the passed in data matches what is expected by the verification result.
+ ///
+ /// The bytes representing the signature.
+ /// true if the signature verifies, false otherwise.
+ bool IsVerified(byte[] data);
+
+ ///
+ /// Return true if the length bytes from off in the source array match the signature
+ /// expected by the verification result.
+ ///
+ /// Byte array containing the signature.
+ /// The offset into the source array where the signature starts.
+ /// The number of bytes in source making up the signature.
+ /// true if the signature verifies, false otherwise.
+ bool IsVerified(byte[] source, int off, int length);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IVerifier.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IVerifier.cs.meta
new file mode 100644
index 00000000..d3a1ccc2
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IVerifier.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: e9b2937c1d75e3a4a853544b58c02a98
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IVerifierFactory.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IVerifierFactory.cs
new file mode 100644
index 00000000..dc40f7db
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IVerifierFactory.cs
@@ -0,0 +1,25 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ ///
+ /// Base interface for operators that serve as stream-based signature verifiers.
+ ///
+ public interface IVerifierFactory
+ {
+ /// The algorithm details object for this verifier.
+ Object AlgorithmDetails { get ; }
+
+ ///
+ /// Create a stream calculator for this verifier. The stream
+ /// calculator is used for the actual operation of entering the data to be verified
+ /// and producing a result which can be used to verify the original signature.
+ ///
+ /// A calculator producing an IVerifier which can verify the signature.
+ IStreamCalculator CreateCalculator();
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IVerifierFactory.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IVerifierFactory.cs.meta
new file mode 100644
index 00000000..d90f7e97
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IVerifierFactory.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 2bb89900480afd44dbd6fd6f123f4197
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IVerifierFactoryProvider.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IVerifierFactoryProvider.cs
new file mode 100644
index 00000000..63133f96
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IVerifierFactoryProvider.cs
@@ -0,0 +1,22 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ ///
+ /// Base interface for a provider to support the dynamic creation of signature verifiers.
+ ///
+ public interface IVerifierFactoryProvider
+ {
+ ///
+ /// Return a signature verfier for signature algorithm described in the passed in algorithm details object.
+ ///
+ /// The details of the signature algorithm verification is required for.
+ /// A new signature verifier.
+ IVerifierFactory CreateVerifierFactory (Object algorithmDetails);
+ }
+}
+
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IVerifierFactoryProvider.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IVerifierFactoryProvider.cs.meta
new file mode 100644
index 00000000..71232a9a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IVerifierFactoryProvider.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 9d25c82ed85117949850d76a12de1304
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IWrapper.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IWrapper.cs
new file mode 100644
index 00000000..4bf5a156
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IWrapper.cs
@@ -0,0 +1,22 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ public interface IWrapper
+ {
+ /// The name of the algorithm this cipher implements.
+ string AlgorithmName { get; }
+
+ void Init(bool forWrapping, ICipherParameters parameters);
+
+ byte[] Wrap(byte[] input, int inOff, int length);
+
+ byte[] Unwrap(byte[] input, int inOff, int length);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IWrapper.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IWrapper.cs.meta
new file mode 100644
index 00000000..5b8285a0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IWrapper.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 9e6dd993ef516c2419ecc5849e22d756
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IXof.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IXof.cs
new file mode 100644
index 00000000..88fe9a02
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IXof.cs
@@ -0,0 +1,35 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ ///
+ /// With FIPS PUB 202 a new kind of message digest was announced which supported extendable output, or variable digest sizes.
+ /// This interface provides the extra method required to support variable output on a digest implementation.
+ ///
+ public interface IXof
+ : IDigest
+ {
+ ///
+ /// Output the results of the final calculation for this digest to outLen number of bytes.
+ ///
+ /// output array to write the output bytes to.
+ /// offset to start writing the bytes at.
+ /// the number of output bytes requested.
+ /// the number of bytes written
+ int DoFinal(byte[] output, int outOff, int outLen);
+
+ ///
+ /// Start outputting the results of the final calculation for this digest. Unlike DoFinal, this method
+ /// will continue producing output until the Xof is explicitly reset, or signals otherwise.
+ ///
+ /// output array to write the output bytes to.
+ /// offset to start writing the bytes at.
+ /// the number of output bytes requested.
+ /// the number of bytes written
+ int DoOutput(byte[] output, int outOff, int outLen);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IXof.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IXof.cs.meta
new file mode 100644
index 00000000..b7e4cdfd
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/IXof.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0dc703e606f9afc47a3e7859c663a442
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/InvalidCipherTextException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/InvalidCipherTextException.cs
new file mode 100644
index 00000000..a89918a1
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/InvalidCipherTextException.cs
@@ -0,0 +1,44 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ /**
+ * this exception is thrown whenever we find something we don't expect in a
+ * message.
+ */
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class InvalidCipherTextException
+ : CryptoException
+ {
+ /**
+ * base constructor.
+ */
+ public InvalidCipherTextException()
+ {
+ }
+
+ /**
+ * create a InvalidCipherTextException with the given message.
+ *
+ * @param message the message to be carried with the exception.
+ */
+ public InvalidCipherTextException(
+ string message)
+ : base(message)
+ {
+ }
+
+ public InvalidCipherTextException(
+ string message,
+ Exception exception)
+ : base(message, exception)
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/InvalidCipherTextException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/InvalidCipherTextException.cs.meta
new file mode 100644
index 00000000..87322c1e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/InvalidCipherTextException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 8853d9e74bb4d214ca464e63632d1f0c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/KeyGenerationParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/KeyGenerationParameters.cs
new file mode 100644
index 00000000..3c920c16
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/KeyGenerationParameters.cs
@@ -0,0 +1,59 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ /**
+ * The base class for parameters to key generators.
+ */
+ public class KeyGenerationParameters
+ {
+ private SecureRandom random;
+ private int strength;
+
+ /**
+ * initialise the generator with a source of randomness
+ * and a strength (in bits).
+ *
+ * @param random the random byte source.
+ * @param strength the size, in bits, of the keys we want to produce.
+ */
+ public KeyGenerationParameters(
+ SecureRandom random,
+ int strength)
+ {
+ if (random == null)
+ throw new ArgumentNullException("random");
+ if (strength < 1)
+ throw new ArgumentException("strength must be a positive value", "strength");
+
+ this.random = random;
+ this.strength = strength;
+ }
+
+ /**
+ * return the random source associated with this
+ * generator.
+ *
+ * @return the generators random source.
+ */
+ public SecureRandom Random
+ {
+ get { return random; }
+ }
+
+ /**
+ * return the bit strength for keys produced by this generator,
+ *
+ * @return the strength of the keys this generator produces (in bits).
+ */
+ public int Strength
+ {
+ get { return strength; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/KeyGenerationParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/KeyGenerationParameters.cs.meta
new file mode 100644
index 00000000..61d375d6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/KeyGenerationParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 04045d0d5f207b6429614236fbee6859
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/MaxBytesExceededException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/MaxBytesExceededException.cs
new file mode 100644
index 00000000..d09caf62
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/MaxBytesExceededException.cs
@@ -0,0 +1,36 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ ///
+ /// This exception is thrown whenever a cipher requires a change of key, iv
+ /// or similar after x amount of bytes enciphered
+ ///
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class MaxBytesExceededException
+ : CryptoException
+ {
+ public MaxBytesExceededException()
+ {
+ }
+
+ public MaxBytesExceededException(
+ string message)
+ : base(message)
+ {
+ }
+
+ public MaxBytesExceededException(
+ string message,
+ Exception e)
+ : base(message, e)
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/MaxBytesExceededException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/MaxBytesExceededException.cs.meta
new file mode 100644
index 00000000..e094f03f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/MaxBytesExceededException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 92610e3167822424cbf998e12a4d959a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/OutputLengthException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/OutputLengthException.cs
new file mode 100644
index 00000000..6fa64ed5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/OutputLengthException.cs
@@ -0,0 +1,32 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class OutputLengthException
+ : DataLengthException
+ {
+ public OutputLengthException()
+ {
+ }
+
+ public OutputLengthException(
+ string message)
+ : base(message)
+ {
+ }
+
+ public OutputLengthException(
+ string message,
+ Exception exception)
+ : base(message, exception)
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/OutputLengthException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/OutputLengthException.cs.meta
new file mode 100644
index 00000000..7085e8c6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/OutputLengthException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: aeef960a80a930f47af2e7599623e501
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/PbeParametersGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/PbeParametersGenerator.cs
new file mode 100644
index 00000000..ddf81148
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/PbeParametersGenerator.cs
@@ -0,0 +1,206 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ /**
+ * super class for all Password Based Encyrption (Pbe) parameter generator classes.
+ */
+ public abstract class PbeParametersGenerator
+ {
+ protected byte[] mPassword;
+ protected byte[] mSalt;
+ protected int mIterationCount;
+
+ /**
+ * base constructor.
+ */
+ protected PbeParametersGenerator()
+ {
+ }
+
+ /**
+ * initialise the Pbe generator.
+ *
+ * @param password the password converted into bytes (see below).
+ * @param salt the salt to be mixed with the password.
+ * @param iterationCount the number of iterations the "mixing" function
+ * is to be applied for.
+ */
+ public virtual void Init(
+ byte[] password,
+ byte[] salt,
+ int iterationCount)
+ {
+ if (password == null)
+ throw new ArgumentNullException("password");
+ if (salt == null)
+ throw new ArgumentNullException("salt");
+
+ this.mPassword = Arrays.Clone(password);
+ this.mSalt = Arrays.Clone(salt);
+ this.mIterationCount = iterationCount;
+ }
+
+ public virtual byte[] Password
+ {
+ get { return Arrays.Clone(mPassword); }
+ }
+
+ /**
+ * return the password byte array.
+ *
+ * @return the password byte array.
+ */
+ [Obsolete("Use 'Password' property")]
+ public byte[] GetPassword()
+ {
+ return Password;
+ }
+
+ public virtual byte[] Salt
+ {
+ get { return Arrays.Clone(mSalt); }
+ }
+
+ /**
+ * return the salt byte array.
+ *
+ * @return the salt byte array.
+ */
+ [Obsolete("Use 'Salt' property")]
+ public byte[] GetSalt()
+ {
+ return Salt;
+ }
+
+ /**
+ * return the iteration count.
+ *
+ * @return the iteration count.
+ */
+ public virtual int IterationCount
+ {
+ get { return mIterationCount; }
+ }
+
+ /**
+ * Generate derived parameters for a key of length keySize.
+ *
+ * @param keySize the length, in bits, of the key required.
+ * @return a parameters object representing a key.
+ */
+ [Obsolete("Use version with 'algorithm' parameter")]
+ public abstract ICipherParameters GenerateDerivedParameters(int keySize);
+ public abstract ICipherParameters GenerateDerivedParameters(string algorithm, int keySize);
+
+ /**
+ * Generate derived parameters for a key of length keySize, and
+ * an initialisation vector (IV) of length ivSize.
+ *
+ * @param keySize the length, in bits, of the key required.
+ * @param ivSize the length, in bits, of the iv required.
+ * @return a parameters object representing a key and an IV.
+ */
+ [Obsolete("Use version with 'algorithm' parameter")]
+ public abstract ICipherParameters GenerateDerivedParameters(int keySize, int ivSize);
+ public abstract ICipherParameters GenerateDerivedParameters(string algorithm, int keySize, int ivSize);
+
+ /**
+ * Generate derived parameters for a key of length keySize, specifically
+ * for use with a MAC.
+ *
+ * @param keySize the length, in bits, of the key required.
+ * @return a parameters object representing a key.
+ */
+ public abstract ICipherParameters GenerateDerivedMacParameters(int keySize);
+
+ /**
+ * converts a password to a byte array according to the scheme in
+ * Pkcs5 (ascii, no padding)
+ *
+ * @param password a character array representing the password.
+ * @return a byte array representing the password.
+ */
+ public static byte[] Pkcs5PasswordToBytes(
+ char[] password)
+ {
+ if (password == null)
+ return new byte[0];
+
+ return Strings.ToByteArray(password);
+ }
+
+ [Obsolete("Use version taking 'char[]' instead")]
+ public static byte[] Pkcs5PasswordToBytes(
+ string password)
+ {
+ if (password == null)
+ return new byte[0];
+
+ return Strings.ToByteArray(password);
+ }
+
+ /**
+ * converts a password to a byte array according to the scheme in
+ * PKCS5 (UTF-8, no padding)
+ *
+ * @param password a character array representing the password.
+ * @return a byte array representing the password.
+ */
+ public static byte[] Pkcs5PasswordToUtf8Bytes(
+ char[] password)
+ {
+ if (password == null)
+ return new byte[0];
+
+ return Encoding.UTF8.GetBytes(password);
+ }
+
+ [Obsolete("Use version taking 'char[]' instead")]
+ public static byte[] Pkcs5PasswordToUtf8Bytes(
+ string password)
+ {
+ if (password == null)
+ return new byte[0];
+
+ return Encoding.UTF8.GetBytes(password);
+ }
+
+ /**
+ * converts a password to a byte array according to the scheme in
+ * Pkcs12 (unicode, big endian, 2 zero pad bytes at the end).
+ *
+ * @param password a character array representing the password.
+ * @return a byte array representing the password.
+ */
+ public static byte[] Pkcs12PasswordToBytes(
+ char[] password)
+ {
+ return Pkcs12PasswordToBytes(password, false);
+ }
+
+ public static byte[] Pkcs12PasswordToBytes(
+ char[] password,
+ bool wrongPkcs12Zero)
+ {
+ if (password == null || password.Length < 1)
+ {
+ return new byte[wrongPkcs12Zero ? 2 : 0];
+ }
+
+ // +1 for extra 2 pad bytes.
+ byte[] bytes = new byte[(password.Length + 1) * 2];
+
+ Encoding.BigEndianUnicode.GetBytes(password, 0, password.Length, bytes, 0);
+
+ return bytes;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/PbeParametersGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/PbeParametersGenerator.cs.meta
new file mode 100644
index 00000000..493df6f5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/PbeParametersGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 1e8e08c20f9235643b9bc29aa415dfab
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/StreamBlockCipher.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/StreamBlockCipher.cs
new file mode 100644
index 00000000..fb40d160
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/StreamBlockCipher.cs
@@ -0,0 +1,113 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto
+{
+ /**
+ * a wrapper for block ciphers with a single byte block size, so that they
+ * can be treated like stream ciphers.
+ */
+ public class StreamBlockCipher
+ : IStreamCipher
+ {
+ private readonly IBlockCipher cipher;
+ private readonly byte[] oneByte = new byte[1];
+
+ /**
+ * basic constructor.
+ *
+ * @param cipher the block cipher to be wrapped.
+ * @exception ArgumentException if the cipher has a block size other than
+ * one.
+ */
+ public StreamBlockCipher(
+ IBlockCipher cipher)
+ {
+ if (cipher == null)
+ throw new ArgumentNullException("cipher");
+ if (cipher.GetBlockSize() != 1)
+ throw new ArgumentException("block cipher block size != 1.", "cipher");
+
+ this.cipher = cipher;
+ }
+
+ /**
+ * initialise the underlying cipher.
+ *
+ * @param forEncryption true if we are setting up for encryption, false otherwise.
+ * @param param the necessary parameters for the underlying cipher to be initialised.
+ */
+ public void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ cipher.Init(forEncryption, parameters);
+ }
+
+ /**
+ * return the name of the algorithm we are wrapping.
+ *
+ * @return the name of the algorithm we are wrapping.
+ */
+ public string AlgorithmName
+ {
+ get { return cipher.AlgorithmName; }
+ }
+
+ /**
+ * encrypt/decrypt a single byte returning the result.
+ *
+ * @param in the byte to be processed.
+ * @return the result of processing the input byte.
+ */
+ public byte ReturnByte(
+ byte input)
+ {
+ oneByte[0] = input;
+
+ cipher.ProcessBlock(oneByte, 0, oneByte, 0);
+
+ return oneByte[0];
+ }
+
+ /**
+ * process a block of bytes from in putting the result into out.
+ *
+ * @param in the input byte array.
+ * @param inOff the offset into the in array where the data to be processed starts.
+ * @param len the number of bytes to be processed.
+ * @param out the output buffer the processed bytes go into.
+ * @param outOff the offset into the output byte array the processed data stars at.
+ * @exception DataLengthException if the output buffer is too small.
+ */
+ public void ProcessBytes(
+ byte[] input,
+ int inOff,
+ int length,
+ byte[] output,
+ int outOff)
+ {
+ if (outOff + length > output.Length)
+ throw new DataLengthException("output buffer too small in ProcessBytes()");
+
+ for (int i = 0; i != length; i++)
+ {
+ cipher.ProcessBlock(input, inOff + i, output, outOff + i);
+ }
+ }
+
+ /**
+ * reset the underlying cipher. This leaves it in the same state
+ * it was at after the last init (if there was one).
+ */
+ public void Reset()
+ {
+ cipher.Reset();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/StreamBlockCipher.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/StreamBlockCipher.cs.meta
new file mode 100644
index 00000000..ed4f36bd
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/StreamBlockCipher.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 01d635ad1339b4c4a83239af73f165d7
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement.meta
new file mode 100644
index 00000000..816c289f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 2bc69c4ab864f9b47b55d5556201d098
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/DHAgreement.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/DHAgreement.cs
new file mode 100644
index 00000000..cbf7bfa2
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/DHAgreement.cs
@@ -0,0 +1,103 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Diagnostics;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement
+{
+ /**
+ * a Diffie-Hellman key exchange engine.
+ *
+ * note: This uses MTI/A0 key agreement in order to make the key agreement
+ * secure against passive attacks. If you're doing Diffie-Hellman and both
+ * parties have long term public keys you should look at using this. For
+ * further information have a look at RFC 2631.
+ *
+ * It's possible to extend this to more than two parties as well, for the moment
+ * that is left as an exercise for the reader.
+ */
+ public class DHAgreement
+ {
+ private DHPrivateKeyParameters key;
+ private DHParameters dhParams;
+ private BigInteger privateValue;
+ private SecureRandom random;
+
+ public void Init(
+ ICipherParameters parameters)
+ {
+ AsymmetricKeyParameter kParam;
+ if (parameters is ParametersWithRandom)
+ {
+ ParametersWithRandom rParam = (ParametersWithRandom)parameters;
+
+ this.random = rParam.Random;
+ kParam = (AsymmetricKeyParameter)rParam.Parameters;
+ }
+ else
+ {
+ this.random = new SecureRandom();
+ kParam = (AsymmetricKeyParameter)parameters;
+ }
+
+ if (!(kParam is DHPrivateKeyParameters))
+ {
+ throw new ArgumentException("DHEngine expects DHPrivateKeyParameters");
+ }
+
+ this.key = (DHPrivateKeyParameters)kParam;
+ this.dhParams = key.Parameters;
+ }
+
+ /**
+ * calculate our initial message.
+ */
+ public BigInteger CalculateMessage()
+ {
+ DHKeyPairGenerator dhGen = new DHKeyPairGenerator();
+ dhGen.Init(new DHKeyGenerationParameters(random, dhParams));
+ AsymmetricCipherKeyPair dhPair = dhGen.GenerateKeyPair();
+
+ this.privateValue = ((DHPrivateKeyParameters)dhPair.Private).X;
+
+ return ((DHPublicKeyParameters)dhPair.Public).Y;
+ }
+
+ /**
+ * given a message from a given party and the corresponding public key
+ * calculate the next message in the agreement sequence. In this case
+ * this will represent the shared secret.
+ */
+ public BigInteger CalculateAgreement(
+ DHPublicKeyParameters pub,
+ BigInteger message)
+ {
+ if (pub == null)
+ throw new ArgumentNullException("pub");
+ if (message == null)
+ throw new ArgumentNullException("message");
+
+ if (!pub.Parameters.Equals(dhParams))
+ throw new ArgumentException("Diffie-Hellman public key has wrong parameters.");
+
+ BigInteger p = dhParams.P;
+
+ BigInteger peerY = pub.Y;
+ if (peerY == null || peerY.CompareTo(BigInteger.One) <= 0 || peerY.CompareTo(p.Subtract(BigInteger.One)) >= 0)
+ throw new ArgumentException("Diffie-Hellman public key is weak");
+
+ BigInteger result = peerY.ModPow(privateValue, p);
+ if (result.Equals(BigInteger.One))
+ throw new InvalidOperationException("Shared key can't be 1");
+
+ return message.ModPow(key.X, p).Multiply(result).Mod(p);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/DHAgreement.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/DHAgreement.cs.meta
new file mode 100644
index 00000000..f7d4a73a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/DHAgreement.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 43b4c5b9cdeee0a4ea13e8d2efdb7a4a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/DHBasicAgreement.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/DHBasicAgreement.cs
new file mode 100644
index 00000000..63be8574
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/DHBasicAgreement.cs
@@ -0,0 +1,76 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement
+{
+ /**
+ * a Diffie-Hellman key agreement class.
+ *
+ * note: This is only the basic algorithm, it doesn't take advantage of
+ * long term public keys if they are available. See the DHAgreement class
+ * for a "better" implementation.
+ */
+ public class DHBasicAgreement
+ : IBasicAgreement
+ {
+ private DHPrivateKeyParameters key;
+ private DHParameters dhParams;
+
+ public virtual void Init(
+ ICipherParameters parameters)
+ {
+ if (parameters is ParametersWithRandom)
+ {
+ parameters = ((ParametersWithRandom) parameters).Parameters;
+ }
+
+ if (!(parameters is DHPrivateKeyParameters))
+ {
+ throw new ArgumentException("DHEngine expects DHPrivateKeyParameters");
+ }
+
+ this.key = (DHPrivateKeyParameters) parameters;
+ this.dhParams = key.Parameters;
+ }
+
+ public virtual int GetFieldSize()
+ {
+ return (key.Parameters.P.BitLength + 7) / 8;
+ }
+
+ /**
+ * given a short term public key from a given party calculate the next
+ * message in the agreement sequence.
+ */
+ public virtual BigInteger CalculateAgreement(
+ ICipherParameters pubKey)
+ {
+ if (this.key == null)
+ throw new InvalidOperationException("Agreement algorithm not initialised");
+
+ DHPublicKeyParameters pub = (DHPublicKeyParameters)pubKey;
+
+ if (!pub.Parameters.Equals(dhParams))
+ throw new ArgumentException("Diffie-Hellman public key has wrong parameters.");
+
+ BigInteger p = dhParams.P;
+
+ BigInteger peerY = pub.Y;
+ if (peerY == null || peerY.CompareTo(BigInteger.One) <= 0 || peerY.CompareTo(p.Subtract(BigInteger.One)) >= 0)
+ throw new ArgumentException("Diffie-Hellman public key is weak");
+
+ BigInteger result = peerY.ModPow(key.X, p);
+ if (result.Equals(BigInteger.One))
+ throw new InvalidOperationException("Shared key can't be 1");
+
+ return result;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/DHBasicAgreement.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/DHBasicAgreement.cs.meta
new file mode 100644
index 00000000..9ec23b82
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/DHBasicAgreement.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 784404322f00cbf4d8deb0ae525835dc
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/DHStandardGroups.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/DHStandardGroups.cs
new file mode 100644
index 00000000..ba184926
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/DHStandardGroups.cs
@@ -0,0 +1,311 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement
+{
+ /// Standard Diffie-Hellman groups from various IETF specifications.
+ public class DHStandardGroups
+ {
+ private static BigInteger FromHex(string hex)
+ {
+ return new BigInteger(1, Hex.Decode(hex));
+ }
+
+ private static DHParameters FromPG(string hexP, string hexG)
+ {
+ return new DHParameters(FromHex(hexP), FromHex(hexG));
+ }
+
+ private static DHParameters FromPGQ(string hexP, string hexG, string hexQ)
+ {
+ return new DHParameters(FromHex(hexP), FromHex(hexG), FromHex(hexQ));
+ }
+
+ private static DHParameters Rfc7919Parameters(string hexP, int l)
+ {
+ // NOTE: All the groups in RFC 7919 use safe primes, i.e. q = (p-1)/2, and generator g = 2
+ BigInteger p = FromHex(hexP);
+ return new DHParameters(p, BigInteger.Two, p.ShiftRight(1), l);
+ }
+
+ /*
+ * RFC 2409
+ */
+ private static readonly string rfc2409_768_p = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
+ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
+ + "E485B576625E7EC6F44C42E9A63A3620FFFFFFFFFFFFFFFF";
+ private static readonly string rfc2409_768_g = "02";
+ public static readonly DHParameters rfc2409_768 = FromPG(rfc2409_768_p, rfc2409_768_g);
+
+ private static readonly string rfc2409_1024_p = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
+ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
+ + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381"
+ + "FFFFFFFFFFFFFFFF";
+ private static readonly string rfc2409_1024_g = "02";
+ public static readonly DHParameters rfc2409_1024 = FromPG(rfc2409_1024_p, rfc2409_1024_g);
+
+ /*
+ * RFC 3526
+ */
+ private static readonly string rfc3526_1536_p = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
+ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
+ + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
+ + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" + "83655D23DCA3AD961C62F356208552BB9ED529077096966D"
+ + "670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF";
+ private static readonly string rfc3526_1536_g = "02";
+ public static readonly DHParameters rfc3526_1536 = FromPG(rfc3526_1536_p, rfc3526_1536_g);
+
+ private static readonly string rfc3526_2048_p = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
+ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
+ + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
+ + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" + "83655D23DCA3AD961C62F356208552BB9ED529077096966D"
+ + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
+ + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" + "15728E5A8AACAA68FFFFFFFFFFFFFFFF";
+ private static readonly string rfc3526_2048_g = "02";
+ public static readonly DHParameters rfc3526_2048 = FromPG(rfc3526_2048_p, rfc3526_2048_g);
+
+ private static readonly string rfc3526_3072_p = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
+ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
+ + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
+ + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" + "83655D23DCA3AD961C62F356208552BB9ED529077096966D"
+ + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
+ + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64"
+ + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B"
+ + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31"
+ + "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF";
+ private static readonly string rfc3526_3072_g = "02";
+ public static readonly DHParameters rfc3526_3072 = FromPG(rfc3526_3072_p, rfc3526_3072_g);
+
+ private static readonly string rfc3526_4096_p = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
+ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
+ + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
+ + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" + "83655D23DCA3AD961C62F356208552BB9ED529077096966D"
+ + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
+ + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64"
+ + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B"
+ + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31"
+ + "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7" + "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA"
+ + "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6" + "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED"
+ + "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9" + "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199"
+ + "FFFFFFFFFFFFFFFF";
+ private static readonly string rfc3526_4096_g = "02";
+ public static readonly DHParameters rfc3526_4096 = FromPG(rfc3526_4096_p, rfc3526_4096_g);
+
+ private static readonly string rfc3526_6144_p = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
+ + "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
+ + "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
+ + "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
+ + "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8"
+ + "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D"
+ + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C"
+ + "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718"
+ + "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D"
+ + "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D"
+ + "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226"
+ + "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
+ + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC"
+ + "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26"
+ + "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB"
+ + "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2"
+ + "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127"
+ + "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492"
+ + "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406"
+ + "AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918"
+ + "DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151"
+ + "2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03"
+ + "F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F"
+ + "BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA"
+ + "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B"
+ + "B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632"
+ + "387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E"
+ + "6DCC4024FFFFFFFFFFFFFFFF";
+ private static readonly string rfc3526_6144_g = "02";
+ public static readonly DHParameters rfc3526_6144 = FromPG(rfc3526_6144_p, rfc3526_6144_g);
+
+ private static readonly string rfc3526_8192_p = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
+ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
+ + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
+ + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" + "83655D23DCA3AD961C62F356208552BB9ED529077096966D"
+ + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
+ + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64"
+ + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B"
+ + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31"
+ + "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7" + "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA"
+ + "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6" + "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED"
+ + "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9" + "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492"
+ + "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BD" + "F8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831"
+ + "179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1B" + "DB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF"
+ + "5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6" + "D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F3"
+ + "23A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" + "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE328"
+ + "06A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55C" + "DA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE"
+ + "12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E4" + "38777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300"
+ + "741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F568" + "3423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9"
+ + "22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B" + "4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A"
+ + "062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A36" + "4597E899A0255DC164F31CC50846851DF9AB48195DED7EA1"
+ + "B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F92" + "4009438B481C6CD7889A002ED5EE382BC9190DA6FC026E47"
+ + "9558E4475677E9AA9E3050E2765694DFC81F56E880B96E71" + "60C980DD98EDD3DFFFFFFFFFFFFFFFFF";
+ private static readonly string rfc3526_8192_g = "02";
+ public static readonly DHParameters rfc3526_8192 = FromPG(rfc3526_8192_p, rfc3526_8192_g);
+
+ /*
+ * RFC 4306
+ */
+ public static readonly DHParameters rfc4306_768 = rfc2409_768;
+ public static readonly DHParameters rfc4306_1024 = rfc2409_1024;
+
+ /*
+ * RFC 5114
+ */
+ private static readonly string rfc5114_1024_160_p = "B10B8F96A080E01DDE92DE5EAE5D54EC52C99FBCFB06A3C6"
+ + "9A6A9DCA52D23B616073E28675A23D189838EF1E2EE652C0" + "13ECB4AEA906112324975C3CD49B83BFACCBDD7D90C4BD70"
+ + "98488E9C219A73724EFFD6FAE5644738FAA31A4FF55BCCC0" + "A151AF5F0DC8B4BD45BF37DF365C1A65E68CFDA76D4DA708"
+ + "DF1FB2BC2E4A4371";
+ private static readonly string rfc5114_1024_160_g = "A4D1CBD5C3FD34126765A442EFB99905F8104DD258AC507F"
+ + "D6406CFF14266D31266FEA1E5C41564B777E690F5504F213" + "160217B4B01B886A5E91547F9E2749F4D7FBD7D3B9A92EE1"
+ + "909D0D2263F80A76A6A24C087A091F531DBF0A0169B6A28A" + "D662A4D18E73AFA32D779D5918D08BC8858F4DCEF97C2A24"
+ + "855E6EEB22B3B2E5";
+ private static readonly string rfc5114_1024_160_q = "F518AA8781A8DF278ABA4E7D64B7CB9D49462353";
+
+ ///
+ /// Existence of a "hidden SNFS" backdoor cannot be ruled out. see https://eprint.iacr.org/2016/961.pdf .
+ ///
+ [Obsolete("Existence of a 'hidden SNFS' backdoor cannot be ruled out.")]
+ public static readonly DHParameters rfc5114_1024_160 = FromPGQ(rfc5114_1024_160_p, rfc5114_1024_160_g,
+ rfc5114_1024_160_q);
+
+ private static readonly string rfc5114_2048_224_p = "AD107E1E9123A9D0D660FAA79559C51FA20D64E5683B9FD1"
+ + "B54B1597B61D0A75E6FA141DF95A56DBAF9A3C407BA1DF15" + "EB3D688A309C180E1DE6B85A1274A0A66D3F8152AD6AC212"
+ + "9037C9EDEFDA4DF8D91E8FEF55B7394B7AD5B7D0B6C12207" + "C9F98D11ED34DBF6C6BA0B2C8BBC27BE6A00E0A0B9C49708"
+ + "B3BF8A317091883681286130BC8985DB1602E714415D9330" + "278273C7DE31EFDC7310F7121FD5A07415987D9ADC0A486D"
+ + "CDF93ACC44328387315D75E198C641A480CD86A1B9E587E8" + "BE60E69CC928B2B9C52172E413042E9B23F10B0E16E79763"
+ + "C9B53DCF4BA80A29E3FB73C16B8E75B97EF363E2FFA31F71" + "CF9DE5384E71B81C0AC4DFFE0C10E64F";
+ private static readonly string rfc5114_2048_224_g = "AC4032EF4F2D9AE39DF30B5C8FFDAC506CDEBE7B89998CAF"
+ + "74866A08CFE4FFE3A6824A4E10B9A6F0DD921F01A70C4AFA" + "AB739D7700C29F52C57DB17C620A8652BE5E9001A8D66AD7"
+ + "C17669101999024AF4D027275AC1348BB8A762D0521BC98A" + "E247150422EA1ED409939D54DA7460CDB5F6C6B250717CBE"
+ + "F180EB34118E98D119529A45D6F834566E3025E316A330EF" + "BB77A86F0C1AB15B051AE3D428C8F8ACB70A8137150B8EEB"
+ + "10E183EDD19963DDD9E263E4770589EF6AA21E7F5F2FF381" + "B539CCE3409D13CD566AFBB48D6C019181E1BCFE94B30269"
+ + "EDFE72FE9B6AA4BD7B5A0F1C71CFFF4C19C418E1F6EC0179" + "81BC087F2A7065B384B890D3191F2BFA";
+ private static readonly string rfc5114_2048_224_q = "801C0D34C58D93FE997177101F80535A4738CEBCBF389A99B36371EB";
+
+ ///
+ /// Existence of a "hidden SNFS" backdoor cannot be ruled out. see https://eprint.iacr.org/2016/961.pdf .
+ ///
+ [Obsolete("Existence of a 'hidden SNFS' backdoor cannot be ruled out.")]
+ public static readonly DHParameters rfc5114_2048_224 = FromPGQ(rfc5114_2048_224_p, rfc5114_2048_224_g,
+ rfc5114_2048_224_q);
+
+ private static readonly string rfc5114_2048_256_p = "87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F2"
+ + "5D2CEED4435E3B00E00DF8F1D61957D4FAF7DF4561B2AA30" + "16C3D91134096FAA3BF4296D830E9A7C209E0C6497517ABD"
+ + "5A8A9D306BCF67ED91F9E6725B4758C022E0B1EF4275BF7B" + "6C5BFC11D45F9088B941F54EB1E59BB8BC39A0BF12307F5C"
+ + "4FDB70C581B23F76B63ACAE1CAA6B7902D52526735488A0E" + "F13C6D9A51BFA4AB3AD8347796524D8EF6A167B5A41825D9"
+ + "67E144E5140564251CCACB83E6B486F6B3CA3F7971506026" + "C0B857F689962856DED4010ABD0BE621C3A3960A54E710C3"
+ + "75F26375D7014103A4B54330C198AF126116D2276E11715F" + "693877FAD7EF09CADB094AE91E1A1597";
+ private static readonly string rfc5114_2048_256_g = "3FB32C9B73134D0B2E77506660EDBD484CA7B18F21EF2054"
+ + "07F4793A1A0BA12510DBC15077BE463FFF4FED4AAC0BB555" + "BE3A6C1B0C6B47B1BC3773BF7E8C6F62901228F8C28CBB18"
+ + "A55AE31341000A650196F931C77A57F2DDF463E5E9EC144B" + "777DE62AAAB8A8628AC376D282D6ED3864E67982428EBC83"
+ + "1D14348F6F2F9193B5045AF2767164E1DFC967C1FB3F2E55" + "A4BD1BFFE83B9C80D052B985D182EA0ADB2A3B7313D3FE14"
+ + "C8484B1E052588B9B7D2BBD2DF016199ECD06E1557CD0915" + "B3353BBB64E0EC377FD028370DF92B52C7891428CDC67EB6"
+ + "184B523D1DB246C32F63078490F00EF8D647D148D4795451" + "5E2327CFEF98C582664B4C0F6CC41659";
+ private static readonly string rfc5114_2048_256_q = "8CF83642A709A097B447997640129DA299B1A47D1EB3750B"
+ + "A308B0FE64F5FBD3";
+
+ ///
+ /// Existence of a "hidden SNFS" backdoor cannot be ruled out. see https://eprint.iacr.org/2016/961.pdf .
+ ///
+ [Obsolete("Existence of a 'hidden SNFS' backdoor cannot be ruled out.")]
+ public static readonly DHParameters rfc5114_2048_256 = FromPGQ(rfc5114_2048_256_p, rfc5114_2048_256_g,
+ rfc5114_2048_256_q);
+
+ /*
+ * RFC 5996
+ */
+ public static readonly DHParameters rfc5996_768 = rfc4306_768;
+ public static readonly DHParameters rfc5996_1024 = rfc4306_1024;
+
+ /*
+ * RFC 7919
+ */
+ private static readonly string rfc7919_ffdhe2048_p = "FFFFFFFFFFFFFFFFADF85458A2BB4A9AAFDC5620273D3CF1"
+ + "D8B9C583CE2D3695A9E13641146433FBCC939DCE249B3EF9" + "7D2FE363630C75D8F681B202AEC4617AD3DF1ED5D5FD6561"
+ + "2433F51F5F066ED0856365553DED1AF3B557135E7F57C935" + "984F0C70E0E68B77E2A689DAF3EFE8721DF158A136ADE735"
+ + "30ACCA4F483A797ABC0AB182B324FB61D108A94BB2C8E3FB" + "B96ADAB760D7F4681D4F42A3DE394DF4AE56EDE76372BB19"
+ + "0B07A7C8EE0A6D709E02FCE1CDF7E2ECC03404CD28342F61" + "9172FE9CE98583FF8E4F1232EEF28183C3FE3B1B4C6FAD73"
+ + "3BB5FCBC2EC22005C58EF1837D1683B2C6F34A26C1B2EFFA" + "886B423861285C97FFFFFFFFFFFFFFFF";
+ public static readonly DHParameters rfc7919_ffdhe2048 = Rfc7919Parameters(rfc7919_ffdhe2048_p, 225);
+
+ private static readonly string rfc7919_ffdhe3072_p = "FFFFFFFFFFFFFFFFADF85458A2BB4A9AAFDC5620273D3CF1"
+ + "D8B9C583CE2D3695A9E13641146433FBCC939DCE249B3EF9" + "7D2FE363630C75D8F681B202AEC4617AD3DF1ED5D5FD6561"
+ + "2433F51F5F066ED0856365553DED1AF3B557135E7F57C935" + "984F0C70E0E68B77E2A689DAF3EFE8721DF158A136ADE735"
+ + "30ACCA4F483A797ABC0AB182B324FB61D108A94BB2C8E3FB" + "B96ADAB760D7F4681D4F42A3DE394DF4AE56EDE76372BB19"
+ + "0B07A7C8EE0A6D709E02FCE1CDF7E2ECC03404CD28342F61" + "9172FE9CE98583FF8E4F1232EEF28183C3FE3B1B4C6FAD73"
+ + "3BB5FCBC2EC22005C58EF1837D1683B2C6F34A26C1B2EFFA" + "886B4238611FCFDCDE355B3B6519035BBC34F4DEF99C0238"
+ + "61B46FC9D6E6C9077AD91D2691F7F7EE598CB0FAC186D91C" + "AEFE130985139270B4130C93BC437944F4FD4452E2D74DD3"
+ + "64F2E21E71F54BFF5CAE82AB9C9DF69EE86D2BC522363A0D" + "ABC521979B0DEADA1DBF9A42D5C4484E0ABCD06BFA53DDEF"
+ + "3C1B20EE3FD59D7C25E41D2B66C62E37FFFFFFFFFFFFFFFF";
+ public static readonly DHParameters rfc7919_ffdhe3072 = Rfc7919Parameters(rfc7919_ffdhe3072_p, 275);
+
+ private static readonly string rfc7919_ffdhe4096_p = "FFFFFFFFFFFFFFFFADF85458A2BB4A9AAFDC5620273D3CF1"
+ + "D8B9C583CE2D3695A9E13641146433FBCC939DCE249B3EF9" + "7D2FE363630C75D8F681B202AEC4617AD3DF1ED5D5FD6561"
+ + "2433F51F5F066ED0856365553DED1AF3B557135E7F57C935" + "984F0C70E0E68B77E2A689DAF3EFE8721DF158A136ADE735"
+ + "30ACCA4F483A797ABC0AB182B324FB61D108A94BB2C8E3FB" + "B96ADAB760D7F4681D4F42A3DE394DF4AE56EDE76372BB19"
+ + "0B07A7C8EE0A6D709E02FCE1CDF7E2ECC03404CD28342F61" + "9172FE9CE98583FF8E4F1232EEF28183C3FE3B1B4C6FAD73"
+ + "3BB5FCBC2EC22005C58EF1837D1683B2C6F34A26C1B2EFFA" + "886B4238611FCFDCDE355B3B6519035BBC34F4DEF99C0238"
+ + "61B46FC9D6E6C9077AD91D2691F7F7EE598CB0FAC186D91C" + "AEFE130985139270B4130C93BC437944F4FD4452E2D74DD3"
+ + "64F2E21E71F54BFF5CAE82AB9C9DF69EE86D2BC522363A0D" + "ABC521979B0DEADA1DBF9A42D5C4484E0ABCD06BFA53DDEF"
+ + "3C1B20EE3FD59D7C25E41D2B669E1EF16E6F52C3164DF4FB" + "7930E9E4E58857B6AC7D5F42D69F6D187763CF1D55034004"
+ + "87F55BA57E31CC7A7135C886EFB4318AED6A1E012D9E6832" + "A907600A918130C46DC778F971AD0038092999A333CB8B7A"
+ + "1A1DB93D7140003C2A4ECEA9F98D0ACC0A8291CDCEC97DCF" + "8EC9B55A7F88A46B4DB5A851F44182E1C68A007E5E655F6A"
+ + "FFFFFFFFFFFFFFFF";
+ public static readonly DHParameters rfc7919_ffdhe4096 = Rfc7919Parameters(rfc7919_ffdhe4096_p, 325);
+
+ private static readonly string rfc7919_ffdhe6144_p = "FFFFFFFFFFFFFFFFADF85458A2BB4A9AAFDC5620273D3CF1"
+ + "D8B9C583CE2D3695A9E13641146433FBCC939DCE249B3EF9" + "7D2FE363630C75D8F681B202AEC4617AD3DF1ED5D5FD6561"
+ + "2433F51F5F066ED0856365553DED1AF3B557135E7F57C935" + "984F0C70E0E68B77E2A689DAF3EFE8721DF158A136ADE735"
+ + "30ACCA4F483A797ABC0AB182B324FB61D108A94BB2C8E3FB" + "B96ADAB760D7F4681D4F42A3DE394DF4AE56EDE76372BB19"
+ + "0B07A7C8EE0A6D709E02FCE1CDF7E2ECC03404CD28342F61" + "9172FE9CE98583FF8E4F1232EEF28183C3FE3B1B4C6FAD73"
+ + "3BB5FCBC2EC22005C58EF1837D1683B2C6F34A26C1B2EFFA" + "886B4238611FCFDCDE355B3B6519035BBC34F4DEF99C0238"
+ + "61B46FC9D6E6C9077AD91D2691F7F7EE598CB0FAC186D91C" + "AEFE130985139270B4130C93BC437944F4FD4452E2D74DD3"
+ + "64F2E21E71F54BFF5CAE82AB9C9DF69EE86D2BC522363A0D" + "ABC521979B0DEADA1DBF9A42D5C4484E0ABCD06BFA53DDEF"
+ + "3C1B20EE3FD59D7C25E41D2B669E1EF16E6F52C3164DF4FB" + "7930E9E4E58857B6AC7D5F42D69F6D187763CF1D55034004"
+ + "87F55BA57E31CC7A7135C886EFB4318AED6A1E012D9E6832" + "A907600A918130C46DC778F971AD0038092999A333CB8B7A"
+ + "1A1DB93D7140003C2A4ECEA9F98D0ACC0A8291CDCEC97DCF" + "8EC9B55A7F88A46B4DB5A851F44182E1C68A007E5E0DD902"
+ + "0BFD64B645036C7A4E677D2C38532A3A23BA4442CAF53EA6" + "3BB454329B7624C8917BDD64B1C0FD4CB38E8C334C701C3A"
+ + "CDAD0657FCCFEC719B1F5C3E4E46041F388147FB4CFDB477" + "A52471F7A9A96910B855322EDB6340D8A00EF092350511E3"
+ + "0ABEC1FFF9E3A26E7FB29F8C183023C3587E38DA0077D9B4" + "763E4E4B94B2BBC194C6651E77CAF992EEAAC0232A281BF6"
+ + "B3A739C1226116820AE8DB5847A67CBEF9C9091B462D538C" + "D72B03746AE77F5E62292C311562A846505DC82DB854338A"
+ + "E49F5235C95B91178CCF2DD5CACEF403EC9D1810C6272B04" + "5B3B71F9DC6B80D63FDD4A8E9ADB1E6962A69526D43161C1"
+ + "A41D570D7938DAD4A40E329CD0E40E65FFFFFFFFFFFFFFFF";
+ public static readonly DHParameters rfc7919_ffdhe6144 = Rfc7919Parameters(rfc7919_ffdhe6144_p, 375);
+
+ private static readonly string rfc7919_ffdhe8192_p = "FFFFFFFFFFFFFFFFADF85458A2BB4A9AAFDC5620273D3CF1"
+ + "D8B9C583CE2D3695A9E13641146433FBCC939DCE249B3EF9" + "7D2FE363630C75D8F681B202AEC4617AD3DF1ED5D5FD6561"
+ + "2433F51F5F066ED0856365553DED1AF3B557135E7F57C935" + "984F0C70E0E68B77E2A689DAF3EFE8721DF158A136ADE735"
+ + "30ACCA4F483A797ABC0AB182B324FB61D108A94BB2C8E3FB" + "B96ADAB760D7F4681D4F42A3DE394DF4AE56EDE76372BB19"
+ + "0B07A7C8EE0A6D709E02FCE1CDF7E2ECC03404CD28342F61" + "9172FE9CE98583FF8E4F1232EEF28183C3FE3B1B4C6FAD73"
+ + "3BB5FCBC2EC22005C58EF1837D1683B2C6F34A26C1B2EFFA" + "886B4238611FCFDCDE355B3B6519035BBC34F4DEF99C0238"
+ + "61B46FC9D6E6C9077AD91D2691F7F7EE598CB0FAC186D91C" + "AEFE130985139270B4130C93BC437944F4FD4452E2D74DD3"
+ + "64F2E21E71F54BFF5CAE82AB9C9DF69EE86D2BC522363A0D" + "ABC521979B0DEADA1DBF9A42D5C4484E0ABCD06BFA53DDEF"
+ + "3C1B20EE3FD59D7C25E41D2B669E1EF16E6F52C3164DF4FB" + "7930E9E4E58857B6AC7D5F42D69F6D187763CF1D55034004"
+ + "87F55BA57E31CC7A7135C886EFB4318AED6A1E012D9E6832" + "A907600A918130C46DC778F971AD0038092999A333CB8B7A"
+ + "1A1DB93D7140003C2A4ECEA9F98D0ACC0A8291CDCEC97DCF" + "8EC9B55A7F88A46B4DB5A851F44182E1C68A007E5E0DD902"
+ + "0BFD64B645036C7A4E677D2C38532A3A23BA4442CAF53EA6" + "3BB454329B7624C8917BDD64B1C0FD4CB38E8C334C701C3A"
+ + "CDAD0657FCCFEC719B1F5C3E4E46041F388147FB4CFDB477" + "A52471F7A9A96910B855322EDB6340D8A00EF092350511E3"
+ + "0ABEC1FFF9E3A26E7FB29F8C183023C3587E38DA0077D9B4" + "763E4E4B94B2BBC194C6651E77CAF992EEAAC0232A281BF6"
+ + "B3A739C1226116820AE8DB5847A67CBEF9C9091B462D538C" + "D72B03746AE77F5E62292C311562A846505DC82DB854338A"
+ + "E49F5235C95B91178CCF2DD5CACEF403EC9D1810C6272B04" + "5B3B71F9DC6B80D63FDD4A8E9ADB1E6962A69526D43161C1"
+ + "A41D570D7938DAD4A40E329CCFF46AAA36AD004CF600C838" + "1E425A31D951AE64FDB23FCEC9509D43687FEB69EDD1CC5E"
+ + "0B8CC3BDF64B10EF86B63142A3AB8829555B2F747C932665" + "CB2C0F1CC01BD70229388839D2AF05E454504AC78B758282"
+ + "2846C0BA35C35F5C59160CC046FD8251541FC68C9C86B022" + "BB7099876A460E7451A8A93109703FEE1C217E6C3826E52C"
+ + "51AA691E0E423CFC99E9E31650C1217B624816CDAD9A95F9" + "D5B8019488D9C0A0A1FE3075A577E23183F81D4A3F2FA457"
+ + "1EFC8CE0BA8A4FE8B6855DFE72B0A66EDED2FBABFBE58A30" + "FAFABE1C5D71A87E2F741EF8C1FE86FEA6BBFDE530677F0D"
+ + "97D11D49F7A8443D0822E506A9F4614E011E2A94838FF88C" + "D68C8BB7C5C6424CFFFFFFFFFFFFFFFF";
+ public static readonly DHParameters rfc7919_ffdhe8192 = Rfc7919Parameters(rfc7919_ffdhe8192_p, 400);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/DHStandardGroups.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/DHStandardGroups.cs.meta
new file mode 100644
index 00000000..ad73ed30
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/DHStandardGroups.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 70ce942152c050a419149690a08eec59
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECDHBasicAgreement.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECDHBasicAgreement.cs
new file mode 100644
index 00000000..7fd1f7fa
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECDHBasicAgreement.cs
@@ -0,0 +1,78 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement
+{
+ /**
+ * P1363 7.2.1 ECSVDP-DH
+ *
+ * ECSVDP-DH is Elliptic Curve Secret Value Derivation Primitive,
+ * Diffie-Hellman version. It is based on the work of [DH76], [Mil86],
+ * and [Kob87]. This primitive derives a shared secret value from one
+ * party's private key and another party's public key, where both have
+ * the same set of EC domain parameters. If two parties correctly
+ * execute this primitive, they will produce the same output. This
+ * primitive can be invoked by a scheme to derive a shared secret key;
+ * specifically, it may be used with the schemes ECKAS-DH1 and
+ * DL/ECKAS-DH2. It assumes that the input keys are valid (see also
+ * Section 7.2.2).
+ */
+ public class ECDHBasicAgreement
+ : IBasicAgreement
+ {
+ protected internal ECPrivateKeyParameters privKey;
+
+ public virtual void Init(
+ ICipherParameters parameters)
+ {
+ if (parameters is ParametersWithRandom)
+ {
+ parameters = ((ParametersWithRandom)parameters).Parameters;
+ }
+
+ this.privKey = (ECPrivateKeyParameters)parameters;
+ }
+
+ public virtual int GetFieldSize()
+ {
+ return (privKey.Parameters.Curve.FieldSize + 7) / 8;
+ }
+
+ public virtual BigInteger CalculateAgreement(
+ ICipherParameters pubKey)
+ {
+ ECPublicKeyParameters pub = (ECPublicKeyParameters)pubKey;
+ ECDomainParameters dp = privKey.Parameters;
+ if (!dp.Equals(pub.Parameters))
+ throw new InvalidOperationException("ECDH public key has wrong domain parameters");
+
+ BigInteger d = privKey.D;
+
+ // Always perform calculations on the exact curve specified by our private key's parameters
+ ECPoint Q = ECAlgorithms.CleanPoint(dp.Curve, pub.Q);
+ if (Q.IsInfinity)
+ throw new InvalidOperationException("Infinity is not a valid public key for ECDH");
+
+ BigInteger h = dp.H;
+ if (!h.Equals(BigInteger.One))
+ {
+ d = dp.HInv.Multiply(d).Mod(dp.N);
+ Q = ECAlgorithms.ReferenceMultiply(Q, h);
+ }
+
+ ECPoint P = Q.Multiply(d).Normalize();
+ if (P.IsInfinity)
+ throw new InvalidOperationException("Infinity is not a valid agreement value for ECDH");
+
+ return P.AffineXCoord.ToBigInteger();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECDHBasicAgreement.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECDHBasicAgreement.cs.meta
new file mode 100644
index 00000000..cdce6536
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECDHBasicAgreement.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 113c4d3158892b44b9ffa9a028ad0762
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECDHCBasicAgreement.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECDHCBasicAgreement.cs
new file mode 100644
index 00000000..947b8ae6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECDHCBasicAgreement.cs
@@ -0,0 +1,76 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement
+{
+ /**
+ * P1363 7.2.2 ECSVDP-DHC
+ *
+ * ECSVDP-DHC is Elliptic Curve Secret Value Derivation Primitive,
+ * Diffie-Hellman version with cofactor multiplication. It is based on
+ * the work of [DH76], [Mil86], [Kob87], [LMQ98] and [Kal98a]. This
+ * primitive derives a shared secret value from one party's private key
+ * and another party's public key, where both have the same set of EC
+ * domain parameters. If two parties correctly execute this primitive,
+ * they will produce the same output. This primitive can be invoked by a
+ * scheme to derive a shared secret key; specifically, it may be used
+ * with the schemes ECKAS-DH1 and DL/ECKAS-DH2. It does not assume the
+ * validity of the input public key (see also Section 7.2.1).
+ *
+ * Note: As stated P1363 compatibility mode with ECDH can be preset, and
+ * in this case the implementation doesn't have a ECDH compatibility mode
+ * (if you want that just use ECDHBasicAgreement and note they both implement
+ * BasicAgreement!).
+ */
+ public class ECDHCBasicAgreement
+ : IBasicAgreement
+ {
+ private ECPrivateKeyParameters privKey;
+
+ public virtual void Init(
+ ICipherParameters parameters)
+ {
+ if (parameters is ParametersWithRandom)
+ {
+ parameters = ((ParametersWithRandom) parameters).Parameters;
+ }
+
+ this.privKey = (ECPrivateKeyParameters)parameters;
+ }
+
+ public virtual int GetFieldSize()
+ {
+ return (privKey.Parameters.Curve.FieldSize + 7) / 8;
+ }
+
+ public virtual BigInteger CalculateAgreement(
+ ICipherParameters pubKey)
+ {
+ ECPublicKeyParameters pub = (ECPublicKeyParameters)pubKey;
+ ECDomainParameters dp = privKey.Parameters;
+ if (!dp.Equals(pub.Parameters))
+ throw new InvalidOperationException("ECDHC public key has wrong domain parameters");
+
+ BigInteger hd = dp.H.Multiply(privKey.D).Mod(dp.N);
+
+ // Always perform calculations on the exact curve specified by our private key's parameters
+ ECPoint pubPoint = ECAlgorithms.CleanPoint(dp.Curve, pub.Q);
+ if (pubPoint.IsInfinity)
+ throw new InvalidOperationException("Infinity is not a valid public key for ECDHC");
+
+ ECPoint P = pubPoint.Multiply(hd).Normalize();
+ if (P.IsInfinity)
+ throw new InvalidOperationException("Infinity is not a valid agreement value for ECDHC");
+
+ return P.AffineXCoord.ToBigInteger();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECDHCBasicAgreement.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECDHCBasicAgreement.cs.meta
new file mode 100644
index 00000000..228181b2
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECDHCBasicAgreement.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0263cf715bcf72c4ab328faf462a207b
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECDHWithKdfBasicAgreement.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECDHWithKdfBasicAgreement.cs
new file mode 100644
index 00000000..a1e15339
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECDHWithKdfBasicAgreement.cs
@@ -0,0 +1,67 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement.Kdf;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement
+{
+ public class ECDHWithKdfBasicAgreement
+ : ECDHBasicAgreement
+ {
+ private readonly string algorithm;
+ private readonly IDerivationFunction kdf;
+
+ public ECDHWithKdfBasicAgreement(
+ string algorithm,
+ IDerivationFunction kdf)
+ {
+ if (algorithm == null)
+ throw new ArgumentNullException("algorithm");
+ if (kdf == null)
+ throw new ArgumentNullException("kdf");
+
+ this.algorithm = algorithm;
+ this.kdf = kdf;
+ }
+
+ public override BigInteger CalculateAgreement(
+ ICipherParameters pubKey)
+ {
+ // Note that the ec.KeyAgreement class in JCE only uses kdf in one
+ // of the engineGenerateSecret methods.
+
+ BigInteger result = base.CalculateAgreement(pubKey);
+
+ int keySize = GeneratorUtilities.GetDefaultKeySize(algorithm);
+
+ DHKdfParameters dhKdfParams = new DHKdfParameters(
+ new DerObjectIdentifier(algorithm),
+ keySize,
+ BigIntToBytes(result));
+
+ kdf.Init(dhKdfParams);
+
+ byte[] keyBytes = new byte[keySize / 8];
+ kdf.GenerateBytes(keyBytes, 0, keyBytes.Length);
+
+ return new BigInteger(1, keyBytes);
+ }
+
+ private byte[] BigIntToBytes(BigInteger r)
+ {
+ int byteLength = X9IntegerConverter.GetByteLength(privKey.Parameters.Curve);
+ return X9IntegerConverter.IntegerToBytes(r, byteLength);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECDHWithKdfBasicAgreement.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECDHWithKdfBasicAgreement.cs.meta
new file mode 100644
index 00000000..0c02a22d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECDHWithKdfBasicAgreement.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 7bbcd424d33a48544b430a90ee0e859d
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECMqvBasicAgreement.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECMqvBasicAgreement.cs
new file mode 100644
index 00000000..09229b6f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECMqvBasicAgreement.cs
@@ -0,0 +1,90 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement
+{
+ public class ECMqvBasicAgreement
+ : IBasicAgreement
+ {
+ protected internal MqvPrivateParameters privParams;
+
+ public virtual void Init(
+ ICipherParameters parameters)
+ {
+ if (parameters is ParametersWithRandom)
+ {
+ parameters = ((ParametersWithRandom)parameters).Parameters;
+ }
+
+ this.privParams = (MqvPrivateParameters)parameters;
+ }
+
+ public virtual int GetFieldSize()
+ {
+ return (privParams.StaticPrivateKey.Parameters.Curve.FieldSize + 7) / 8;
+ }
+
+ public virtual BigInteger CalculateAgreement(
+ ICipherParameters pubKey)
+ {
+ MqvPublicParameters pubParams = (MqvPublicParameters)pubKey;
+
+ ECPrivateKeyParameters staticPrivateKey = privParams.StaticPrivateKey;
+ ECDomainParameters parameters = staticPrivateKey.Parameters;
+
+ if (!parameters.Equals(pubParams.StaticPublicKey.Parameters))
+ throw new InvalidOperationException("ECMQV public key components have wrong domain parameters");
+
+ ECPoint agreement = CalculateMqvAgreement(parameters, staticPrivateKey,
+ privParams.EphemeralPrivateKey, privParams.EphemeralPublicKey,
+ pubParams.StaticPublicKey, pubParams.EphemeralPublicKey).Normalize();
+
+ if (agreement.IsInfinity)
+ throw new InvalidOperationException("Infinity is not a valid agreement value for MQV");
+
+ return agreement.AffineXCoord.ToBigInteger();
+ }
+
+ // The ECMQV Primitive as described in SEC-1, 3.4
+ private static ECPoint CalculateMqvAgreement(
+ ECDomainParameters parameters,
+ ECPrivateKeyParameters d1U,
+ ECPrivateKeyParameters d2U,
+ ECPublicKeyParameters Q2U,
+ ECPublicKeyParameters Q1V,
+ ECPublicKeyParameters Q2V)
+ {
+ BigInteger n = parameters.N;
+ int e = (n.BitLength + 1) / 2;
+ BigInteger powE = BigInteger.One.ShiftLeft(e);
+
+ ECCurve curve = parameters.Curve;
+
+ ECPoint q2u = ECAlgorithms.CleanPoint(curve, Q2U.Q);
+ ECPoint q1v = ECAlgorithms.CleanPoint(curve, Q1V.Q);
+ ECPoint q2v = ECAlgorithms.CleanPoint(curve, Q2V.Q);
+
+ BigInteger x = q2u.AffineXCoord.ToBigInteger();
+ BigInteger xBar = x.Mod(powE);
+ BigInteger Q2UBar = xBar.SetBit(e);
+ BigInteger s = d1U.D.Multiply(Q2UBar).Add(d2U.D).Mod(n);
+
+ BigInteger xPrime = q2v.AffineXCoord.ToBigInteger();
+ BigInteger xPrimeBar = xPrime.Mod(powE);
+ BigInteger Q2VBar = xPrimeBar.SetBit(e);
+
+ BigInteger hs = parameters.H.Multiply(s).Mod(n);
+
+ return ECAlgorithms.SumOfTwoMultiplies(
+ q1v, Q2VBar.Multiply(hs).Mod(n), q2v, hs);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECMqvBasicAgreement.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECMqvBasicAgreement.cs.meta
new file mode 100644
index 00000000..e41cd1a9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECMqvBasicAgreement.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 7e49c61c5cba8d548ad042204e8f501b
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECMqvWithKdfBasicAgreement.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECMqvWithKdfBasicAgreement.cs
new file mode 100644
index 00000000..fc5f4736
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECMqvWithKdfBasicAgreement.cs
@@ -0,0 +1,67 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement.Kdf;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement
+{
+ public class ECMqvWithKdfBasicAgreement
+ : ECMqvBasicAgreement
+ {
+ private readonly string algorithm;
+ private readonly IDerivationFunction kdf;
+
+ public ECMqvWithKdfBasicAgreement(
+ string algorithm,
+ IDerivationFunction kdf)
+ {
+ if (algorithm == null)
+ throw new ArgumentNullException("algorithm");
+ if (kdf == null)
+ throw new ArgumentNullException("kdf");
+
+ this.algorithm = algorithm;
+ this.kdf = kdf;
+ }
+
+ public override BigInteger CalculateAgreement(
+ ICipherParameters pubKey)
+ {
+ // Note that the ec.KeyAgreement class in JCE only uses kdf in one
+ // of the engineGenerateSecret methods.
+
+ BigInteger result = base.CalculateAgreement(pubKey);
+
+ int keySize = GeneratorUtilities.GetDefaultKeySize(algorithm);
+
+ DHKdfParameters dhKdfParams = new DHKdfParameters(
+ new DerObjectIdentifier(algorithm),
+ keySize,
+ BigIntToBytes(result));
+
+ kdf.Init(dhKdfParams);
+
+ byte[] keyBytes = new byte[keySize / 8];
+ kdf.GenerateBytes(keyBytes, 0, keyBytes.Length);
+
+ return new BigInteger(1, keyBytes);
+ }
+
+ private byte[] BigIntToBytes(BigInteger r)
+ {
+ int byteLength = X9IntegerConverter.GetByteLength(privParams.StaticPrivateKey.Parameters.Curve);
+ return X9IntegerConverter.IntegerToBytes(r, byteLength);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECMqvWithKdfBasicAgreement.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECMqvWithKdfBasicAgreement.cs.meta
new file mode 100644
index 00000000..cfb571a1
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/ECMqvWithKdfBasicAgreement.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 67f980d3d0ee56d4f912ba8597340259
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/SM2KeyExchange.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/SM2KeyExchange.cs
new file mode 100644
index 00000000..02575c99
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/SM2KeyExchange.cs
@@ -0,0 +1,278 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement
+{
+ ///
+ /// SM2 Key Exchange protocol - based on https://tools.ietf.org/html/draft-shen-sm2-ecdsa-02
+ ///
+ public class SM2KeyExchange
+ {
+ private readonly IDigest mDigest;
+
+ private byte[] mUserID;
+ private ECPrivateKeyParameters mStaticKey;
+ private ECPoint mStaticPubPoint;
+ private ECPoint mEphemeralPubPoint;
+ private ECDomainParameters mECParams;
+ private int mW;
+ private ECPrivateKeyParameters mEphemeralKey;
+ private bool mInitiator;
+
+ public SM2KeyExchange()
+ : this(new SM3Digest())
+ {
+ }
+
+ public SM2KeyExchange(IDigest digest)
+ {
+ this.mDigest = digest;
+ }
+
+ public virtual void Init(ICipherParameters privParam)
+ {
+ SM2KeyExchangePrivateParameters baseParam;
+
+ if (privParam is ParametersWithID)
+ {
+ baseParam = (SM2KeyExchangePrivateParameters)((ParametersWithID)privParam).Parameters;
+ mUserID = ((ParametersWithID)privParam).GetID();
+ }
+ else
+ {
+ baseParam = (SM2KeyExchangePrivateParameters)privParam;
+ mUserID = new byte[0];
+ }
+
+ mInitiator = baseParam.IsInitiator;
+ mStaticKey = baseParam.StaticPrivateKey;
+ mEphemeralKey = baseParam.EphemeralPrivateKey;
+ mECParams = mStaticKey.Parameters;
+ mStaticPubPoint = baseParam.StaticPublicPoint;
+ mEphemeralPubPoint = baseParam.EphemeralPublicPoint;
+ mW = mECParams.Curve.FieldSize / 2 - 1;
+ }
+
+ public virtual byte[] CalculateKey(int kLen, ICipherParameters pubParam)
+ {
+ SM2KeyExchangePublicParameters otherPub;
+ byte[] otherUserID;
+
+ if (pubParam is ParametersWithID)
+ {
+ otherPub = (SM2KeyExchangePublicParameters)((ParametersWithID)pubParam).Parameters;
+ otherUserID = ((ParametersWithID)pubParam).GetID();
+ }
+ else
+ {
+ otherPub = (SM2KeyExchangePublicParameters)pubParam;
+ otherUserID = new byte[0];
+ }
+
+ byte[] za = GetZ(mDigest, mUserID, mStaticPubPoint);
+ byte[] zb = GetZ(mDigest, otherUserID, otherPub.StaticPublicKey.Q);
+
+ ECPoint U = CalculateU(otherPub);
+
+ byte[] rv;
+ if (mInitiator)
+ {
+ rv = Kdf(U, za, zb, kLen);
+ }
+ else
+ {
+ rv = Kdf(U, zb, za, kLen);
+ }
+
+ return rv;
+ }
+
+ public virtual byte[][] CalculateKeyWithConfirmation(int kLen, byte[] confirmationTag, ICipherParameters pubParam)
+ {
+ SM2KeyExchangePublicParameters otherPub;
+ byte[] otherUserID;
+
+ if (pubParam is ParametersWithID)
+ {
+ otherPub = (SM2KeyExchangePublicParameters)((ParametersWithID)pubParam).Parameters;
+ otherUserID = ((ParametersWithID)pubParam).GetID();
+ }
+ else
+ {
+ otherPub = (SM2KeyExchangePublicParameters)pubParam;
+ otherUserID = new byte[0];
+ }
+
+ if (mInitiator && confirmationTag == null)
+ throw new ArgumentException("if initiating, confirmationTag must be set");
+
+ byte[] za = GetZ(mDigest, mUserID, mStaticPubPoint);
+ byte[] zb = GetZ(mDigest, otherUserID, otherPub.StaticPublicKey.Q);
+
+ ECPoint U = CalculateU(otherPub);
+
+ byte[] rv;
+ if (mInitiator)
+ {
+ rv = Kdf(U, za, zb, kLen);
+
+ byte[] inner = CalculateInnerHash(mDigest, U, za, zb, mEphemeralPubPoint, otherPub.EphemeralPublicKey.Q);
+
+ byte[] s1 = S1(mDigest, U, inner);
+
+ if (!Arrays.ConstantTimeAreEqual(s1, confirmationTag))
+ throw new InvalidOperationException("confirmation tag mismatch");
+
+ return new byte[][] { rv, S2(mDigest, U, inner)};
+ }
+ else
+ {
+ rv = Kdf(U, zb, za, kLen);
+
+ byte[] inner = CalculateInnerHash(mDigest, U, zb, za, otherPub.EphemeralPublicKey.Q, mEphemeralPubPoint);
+
+ return new byte[][] { rv, S1(mDigest, U, inner), S2(mDigest, U, inner) };
+ }
+ }
+
+ protected virtual ECPoint CalculateU(SM2KeyExchangePublicParameters otherPub)
+ {
+ ECDomainParameters dp = mStaticKey.Parameters;
+
+ ECPoint p1 = ECAlgorithms.CleanPoint(dp.Curve, otherPub.StaticPublicKey.Q);
+ ECPoint p2 = ECAlgorithms.CleanPoint(dp.Curve, otherPub.EphemeralPublicKey.Q);
+
+ BigInteger x1 = Reduce(mEphemeralPubPoint.AffineXCoord.ToBigInteger());
+ BigInteger x2 = Reduce(p2.AffineXCoord.ToBigInteger());
+ BigInteger tA = mStaticKey.D.Add(x1.Multiply(mEphemeralKey.D));
+ BigInteger k1 = mECParams.H.Multiply(tA).Mod(mECParams.N);
+ BigInteger k2 = k1.Multiply(x2).Mod(mECParams.N);
+
+ return ECAlgorithms.SumOfTwoMultiplies(p1, k1, p2, k2).Normalize();
+ }
+
+ protected virtual byte[] Kdf(ECPoint u, byte[] za, byte[] zb, int klen)
+ {
+ int digestSize = mDigest.GetDigestSize();
+ byte[] buf = new byte[System.Math.Max(4, digestSize)];
+ byte[] rv = new byte[(klen + 7) / 8];
+ int off = 0;
+
+ IMemoable memo = mDigest as IMemoable;
+ IMemoable copy = null;
+
+ if (memo != null)
+ {
+ AddFieldElement(mDigest, u.AffineXCoord);
+ AddFieldElement(mDigest, u.AffineYCoord);
+ mDigest.BlockUpdate(za, 0, za.Length);
+ mDigest.BlockUpdate(zb, 0, zb.Length);
+ copy = memo.Copy();
+ }
+
+ uint ct = 0;
+
+ while (off < rv.Length)
+ {
+ if (memo != null)
+ {
+ memo.Reset(copy);
+ }
+ else
+ {
+ AddFieldElement(mDigest, u.AffineXCoord);
+ AddFieldElement(mDigest, u.AffineYCoord);
+ mDigest.BlockUpdate(za, 0, za.Length);
+ mDigest.BlockUpdate(zb, 0, zb.Length);
+ }
+
+ Pack.UInt32_To_BE(++ct, buf, 0);
+ mDigest.BlockUpdate(buf, 0, 4);
+ mDigest.DoFinal(buf, 0);
+
+ int copyLen = System.Math.Min(digestSize, rv.Length - off);
+ Array.Copy(buf, 0, rv, off, copyLen);
+ off += copyLen;
+ }
+
+ return rv;
+ }
+
+ //x1~=2^w+(x1 AND (2^w-1))
+ private BigInteger Reduce(BigInteger x)
+ {
+ return x.And(BigInteger.One.ShiftLeft(mW).Subtract(BigInteger.One)).SetBit(mW);
+ }
+
+ private byte[] S1(IDigest digest, ECPoint u, byte[] inner)
+ {
+ digest.Update((byte)0x02);
+ AddFieldElement(digest, u.AffineYCoord);
+ digest.BlockUpdate(inner, 0, inner.Length);
+
+ return DigestUtilities.DoFinal(digest);
+ }
+
+ private byte[] CalculateInnerHash(IDigest digest, ECPoint u, byte[] za, byte[] zb, ECPoint p1, ECPoint p2)
+ {
+ AddFieldElement(digest, u.AffineXCoord);
+ digest.BlockUpdate(za, 0, za.Length);
+ digest.BlockUpdate(zb, 0, zb.Length);
+ AddFieldElement(digest, p1.AffineXCoord);
+ AddFieldElement(digest, p1.AffineYCoord);
+ AddFieldElement(digest, p2.AffineXCoord);
+ AddFieldElement(digest, p2.AffineYCoord);
+
+ return DigestUtilities.DoFinal(digest);
+ }
+
+ private byte[] S2(IDigest digest, ECPoint u, byte[] inner)
+ {
+ digest.Update((byte)0x03);
+ AddFieldElement(digest, u.AffineYCoord);
+ digest.BlockUpdate(inner, 0, inner.Length);
+
+ return DigestUtilities.DoFinal(digest);
+ }
+
+ private byte[] GetZ(IDigest digest, byte[] userID, ECPoint pubPoint)
+ {
+ AddUserID(digest, userID);
+
+ AddFieldElement(digest, mECParams.Curve.A);
+ AddFieldElement(digest, mECParams.Curve.B);
+ AddFieldElement(digest, mECParams.G.AffineXCoord);
+ AddFieldElement(digest, mECParams.G.AffineYCoord);
+ AddFieldElement(digest, pubPoint.AffineXCoord);
+ AddFieldElement(digest, pubPoint.AffineYCoord);
+
+ return DigestUtilities.DoFinal(digest);
+ }
+
+ private void AddUserID(IDigest digest, byte[] userID)
+ {
+ uint len = (uint)(userID.Length * 8);
+
+ digest.Update((byte)(len >> 8));
+ digest.Update((byte)len);
+ digest.BlockUpdate(userID, 0, userID.Length);
+ }
+
+ private void AddFieldElement(IDigest digest, ECFieldElement v)
+ {
+ byte[] p = v.GetEncoded();
+ digest.BlockUpdate(p, 0, p.Length);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/SM2KeyExchange.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/SM2KeyExchange.cs.meta
new file mode 100644
index 00000000..77951387
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/SM2KeyExchange.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c65b4245b6212194cb13060a735041cf
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/X25519Agreement.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/X25519Agreement.cs
new file mode 100644
index 00000000..46aa12cd
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/X25519Agreement.cs
@@ -0,0 +1,31 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement
+{
+ public sealed class X25519Agreement
+ : IRawAgreement
+ {
+ private X25519PrivateKeyParameters privateKey;
+
+ public void Init(ICipherParameters parameters)
+ {
+ this.privateKey = (X25519PrivateKeyParameters)parameters;
+ }
+
+ public int AgreementSize
+ {
+ get { return X25519PrivateKeyParameters.SecretSize; }
+ }
+
+ public void CalculateAgreement(ICipherParameters publicKey, byte[] buf, int off)
+ {
+ privateKey.GenerateSecret((X25519PublicKeyParameters)publicKey, buf, off);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/X25519Agreement.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/X25519Agreement.cs.meta
new file mode 100644
index 00000000..defe92d9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/X25519Agreement.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 8af8db1542a849649a3f82494db76443
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/X448Agreement.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/X448Agreement.cs
new file mode 100644
index 00000000..ffb70b63
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/X448Agreement.cs
@@ -0,0 +1,31 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement
+{
+ public sealed class X448Agreement
+ : IRawAgreement
+ {
+ private X448PrivateKeyParameters privateKey;
+
+ public void Init(ICipherParameters parameters)
+ {
+ this.privateKey = (X448PrivateKeyParameters)parameters;
+ }
+
+ public int AgreementSize
+ {
+ get { return X448PrivateKeyParameters.SecretSize; }
+ }
+
+ public void CalculateAgreement(ICipherParameters publicKey, byte[] buf, int off)
+ {
+ privateKey.GenerateSecret((X448PublicKeyParameters)publicKey, buf, off);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/X448Agreement.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/X448Agreement.cs.meta
new file mode 100644
index 00000000..66e115a4
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/X448Agreement.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ddbf1a879e5a42342899c3c269e0297d
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake.meta
new file mode 100644
index 00000000..617179cf
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 97ce8e71bc258e84e8329127d33eb89e
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeParticipant.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeParticipant.cs
new file mode 100644
index 00000000..f47d82c7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeParticipant.cs
@@ -0,0 +1,460 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement.JPake
+{
+ ///
+ /// A participant in a Password Authenticated Key Exchange by Juggling (J-PAKE) exchange.
+ ///
+ /// The J-PAKE exchange is defined by Feng Hao and Peter Ryan in the paper
+ ///
+ /// "Password Authenticated Key Exchange by Juggling, 2008."
+ ///
+ /// The J-PAKE protocol is symmetric.
+ /// There is no notion of a client or server, but rather just two participants.
+ /// An instance of JPakeParticipant represents one participant, and
+ /// is the primary interface for executing the exchange.
+ ///
+ /// To execute an exchange, construct a JPakeParticipant on each end,
+ /// and call the following 7 methods
+ /// (once and only once, in the given order, for each participant, sending messages between them as described):
+ ///
+ /// CreateRound1PayloadToSend() - and send the payload to the other participant
+ /// ValidateRound1PayloadReceived(JPakeRound1Payload) - use the payload received from the other participant
+ /// CreateRound2PayloadToSend() - and send the payload to the other participant
+ /// ValidateRound2PayloadReceived(JPakeRound2Payload) - use the payload received from the other participant
+ /// CalculateKeyingMaterial()
+ /// CreateRound3PayloadToSend(BigInteger) - and send the payload to the other participant
+ /// ValidateRound3PayloadReceived(JPakeRound3Payload, BigInteger) - use the payload received from the other participant
+ ///
+ /// Each side should derive a session key from the keying material returned by CalculateKeyingMaterial().
+ /// The caller is responsible for deriving the session key using a secure key derivation function (KDF).
+ ///
+ /// Round 3 is an optional key confirmation process.
+ /// If you do not execute round 3, then there is no assurance that both participants are using the same key.
+ /// (i.e. if the participants used different passwords, then their session keys will differ.)
+ ///
+ /// If the round 3 validation succeeds, then the keys are guaranteed to be the same on both sides.
+ ///
+ /// The symmetric design can easily support the asymmetric cases when one party initiates the communication.
+ /// e.g. Sometimes the round1 payload and round2 payload may be sent in one pass.
+ /// Also, in some cases, the key confirmation payload can be sent together with the round2 payload.
+ /// These are the trivial techniques to optimize the communication.
+ ///
+ /// The key confirmation process is implemented as specified in
+ /// NIST SP 800-56A Revision 1,
+ /// Section 8.2 Unilateral Key Confirmation for Key Agreement Schemes.
+ ///
+ /// This class is stateful and NOT threadsafe.
+ /// Each instance should only be used for ONE complete J-PAKE exchange
+ /// (i.e. a new JPakeParticipant should be constructed for each new J-PAKE exchange).
+ ///
+ public class JPakeParticipant
+ {
+ // Possible internal states. Used for state checking.
+ public static readonly int STATE_INITIALIZED = 0;
+ public static readonly int STATE_ROUND_1_CREATED = 10;
+ public static readonly int STATE_ROUND_1_VALIDATED = 20;
+ public static readonly int STATE_ROUND_2_CREATED = 30;
+ public static readonly int STATE_ROUND_2_VALIDATED = 40;
+ public static readonly int STATE_KEY_CALCULATED = 50;
+ public static readonly int STATE_ROUND_3_CREATED = 60;
+ public static readonly int STATE_ROUND_3_VALIDATED = 70;
+
+ // Unique identifier of this participant.
+ // The two participants in the exchange must NOT share the same id.
+ private string participantId;
+
+ // Shared secret. This only contains the secret between construction
+ // and the call to CalculateKeyingMaterial().
+ //
+ // i.e. When CalculateKeyingMaterial() is called, this buffer overwritten with 0's,
+ // and the field is set to null.
+ private char[] password;
+
+ // Digest to use during calculations.
+ private IDigest digest;
+
+ // Source of secure random data.
+ private readonly SecureRandom random;
+
+ private readonly BigInteger p;
+ private readonly BigInteger q;
+ private readonly BigInteger g;
+
+ // The participantId of the other participant in this exchange.
+ private string partnerParticipantId;
+
+ // Alice's x1 or Bob's x3.
+ private BigInteger x1;
+ // Alice's x2 or Bob's x4.
+ private BigInteger x2;
+ // Alice's g^x1 or Bob's g^x3.
+ private BigInteger gx1;
+ // Alice's g^x2 or Bob's g^x4.
+ private BigInteger gx2;
+ // Alice's g^x3 or Bob's g^x1.
+ private BigInteger gx3;
+ // Alice's g^x4 or Bob's g^x2.
+ private BigInteger gx4;
+ // Alice's B or Bob's A.
+ private BigInteger b;
+
+ // The current state.
+ // See the STATE_* constants for possible values.
+ private int state;
+
+ ///
+ /// Convenience constructor for a new JPakeParticipant that uses
+ /// the JPakePrimeOrderGroups#NIST_3072 prime order group,
+ /// a SHA-256 digest, and a default SecureRandom implementation.
+ ///
+ /// After construction, the State state will be STATE_INITIALIZED.
+ ///
+ /// Throws NullReferenceException if any argument is null. Throws
+ /// ArgumentException if password is empty.
+ ///
+ /// Unique identifier of this participant.
+ /// The two participants in the exchange must NOT share the same id.
+ /// Shared secret.
+ /// A defensive copy of this array is made (and cleared once CalculateKeyingMaterial() is called).
+ /// Caller should clear the input password as soon as possible.
+ public JPakeParticipant(string participantId, char[] password)
+ : this(participantId, password, JPakePrimeOrderGroups.NIST_3072) { }
+
+ ///
+ /// Convenience constructor for a new JPakeParticipant that uses
+ /// a SHA-256 digest, and a default SecureRandom implementation.
+ ///
+ /// After construction, the State state will be STATE_INITIALIZED.
+ ///
+ /// Throws NullReferenceException if any argument is null. Throws
+ /// ArgumentException if password is empty.
+ ///
+ /// Unique identifier of this participant.
+ /// The two participants in the exchange must NOT share the same id.
+ /// Shared secret.
+ /// A defensive copy of this array is made (and cleared once CalculateKeyingMaterial() is called).
+ /// Caller should clear the input password as soon as possible.
+ /// Prime order group. See JPakePrimeOrderGroups for standard groups.
+ public JPakeParticipant(string participantId, char[] password, JPakePrimeOrderGroup group)
+ : this(participantId, password, group, new Sha256Digest(), new SecureRandom()) { }
+
+
+ ///
+ /// Constructor for a new JPakeParticipant.
+ ///
+ /// After construction, the State state will be STATE_INITIALIZED.
+ ///
+ /// Throws NullReferenceException if any argument is null. Throws
+ /// ArgumentException if password is empty.
+ ///
+ /// Unique identifier of this participant.
+ /// The two participants in the exchange must NOT share the same id.
+ /// Shared secret.
+ /// A defensive copy of this array is made (and cleared once CalculateKeyingMaterial() is called).
+ /// Caller should clear the input password as soon as possible.
+ /// Prime order group. See JPakePrimeOrderGroups for standard groups.
+ /// Digest to use during zero knowledge proofs and key confirmation
+ /// (SHA-256 or stronger preferred).
+ /// Source of secure random data for x1 and x2, and for the zero knowledge proofs.
+ public JPakeParticipant(string participantId, char[] password, JPakePrimeOrderGroup group, IDigest digest, SecureRandom random)
+ {
+ JPakeUtilities.ValidateNotNull(participantId, "participantId");
+ JPakeUtilities.ValidateNotNull(password, "password");
+ JPakeUtilities.ValidateNotNull(group, "p");
+ JPakeUtilities.ValidateNotNull(digest, "digest");
+ JPakeUtilities.ValidateNotNull(random, "random");
+
+ if (password.Length == 0)
+ {
+ throw new ArgumentException("Password must not be empty.");
+ }
+
+ this.participantId = participantId;
+
+ // Create a defensive copy so as to fully encapsulate the password.
+ //
+ // This array will contain the password for the lifetime of this
+ // participant BEFORE CalculateKeyingMaterial() is called.
+ //
+ // i.e. When CalculateKeyingMaterial() is called, the array will be cleared
+ // in order to remove the password from memory.
+ //
+ // The caller is responsible for clearing the original password array
+ // given as input to this constructor.
+ this.password = new char[password.Length];
+ Array.Copy(password, this.password, password.Length);
+
+ this.p = group.P;
+ this.q = group.Q;
+ this.g = group.G;
+
+ this.digest = digest;
+ this.random = random;
+
+ this.state = STATE_INITIALIZED;
+ }
+
+ ///
+ /// Gets the current state of this participant.
+ /// See the STATE_* constants for possible values.
+ ///
+ public virtual int State
+ {
+ get { return state; }
+ }
+
+
+ ///
+ /// Creates and returns the payload to send to the other participant during round 1.
+ ///
+ /// After execution, the State state} will be STATE_ROUND_1_CREATED}.
+ ///
+ public virtual JPakeRound1Payload CreateRound1PayloadToSend()
+ {
+ if (this.state >= STATE_ROUND_1_CREATED)
+ throw new InvalidOperationException("Round 1 payload already created for " + this.participantId);
+
+ this.x1 = JPakeUtilities.GenerateX1(q, random);
+ this.x2 = JPakeUtilities.GenerateX2(q, random);
+
+ this.gx1 = JPakeUtilities.CalculateGx(p, g, x1);
+ this.gx2 = JPakeUtilities.CalculateGx(p, g, x2);
+ BigInteger[] knowledgeProofForX1 = JPakeUtilities.CalculateZeroKnowledgeProof(p, q, g, gx1, x1, participantId, digest, random);
+ BigInteger[] knowledgeProofForX2 = JPakeUtilities.CalculateZeroKnowledgeProof(p, q, g, gx2, x2, participantId, digest, random);
+
+ this.state = STATE_ROUND_1_CREATED;
+
+ return new JPakeRound1Payload(participantId, gx1, gx2, knowledgeProofForX1, knowledgeProofForX2);
+ }
+
+ ///
+ /// Validates the payload received from the other participant during round 1.
+ ///
+ /// Must be called prior to CreateRound2PayloadToSend().
+ ///
+ /// After execution, the State state will be STATE_ROUND_1_VALIDATED.
+ ///
+ /// Throws CryptoException if validation fails. Throws InvalidOperationException
+ /// if called multiple times.
+ ///
+ public virtual void ValidateRound1PayloadReceived(JPakeRound1Payload round1PayloadReceived)
+ {
+ if (this.state >= STATE_ROUND_1_VALIDATED)
+ throw new InvalidOperationException("Validation already attempted for round 1 payload for " + this.participantId);
+
+ this.partnerParticipantId = round1PayloadReceived.ParticipantId;
+ this.gx3 = round1PayloadReceived.Gx1;
+ this.gx4 = round1PayloadReceived.Gx2;
+
+ BigInteger[] knowledgeProofForX3 = round1PayloadReceived.KnowledgeProofForX1;
+ BigInteger[] knowledgeProofForX4 = round1PayloadReceived.KnowledgeProofForX2;
+
+ JPakeUtilities.ValidateParticipantIdsDiffer(participantId, round1PayloadReceived.ParticipantId);
+ JPakeUtilities.ValidateGx4(gx4);
+ JPakeUtilities.ValidateZeroKnowledgeProof(p, q, g, gx3, knowledgeProofForX3, round1PayloadReceived.ParticipantId, digest);
+ JPakeUtilities.ValidateZeroKnowledgeProof(p, q, g, gx4, knowledgeProofForX4, round1PayloadReceived.ParticipantId, digest);
+ this.state = STATE_ROUND_1_VALIDATED;
+ }
+
+ ///
+ /// Creates and returns the payload to send to the other participant during round 2.
+ ///
+ /// ValidateRound1PayloadReceived(JPakeRound1Payload) must be called prior to this method.
+ ///
+ /// After execution, the State state will be STATE_ROUND_2_CREATED.
+ ///
+ /// Throws InvalidOperationException if called prior to ValidateRound1PayloadReceived(JPakeRound1Payload), or multiple times
+ ///
+ public virtual JPakeRound2Payload CreateRound2PayloadToSend()
+ {
+ if (this.state >= STATE_ROUND_2_CREATED)
+ throw new InvalidOperationException("Round 2 payload already created for " + this.participantId);
+ if (this.state < STATE_ROUND_1_VALIDATED)
+ throw new InvalidOperationException("Round 1 payload must be validated prior to creating round 2 payload for " + this.participantId);
+
+ BigInteger gA = JPakeUtilities.CalculateGA(p, gx1, gx3, gx4);
+ BigInteger s = JPakeUtilities.CalculateS(password);
+ BigInteger x2s = JPakeUtilities.CalculateX2s(q, x2, s);
+ BigInteger A = JPakeUtilities.CalculateA(p, q, gA, x2s);
+ BigInteger[] knowledgeProofForX2s = JPakeUtilities.CalculateZeroKnowledgeProof(p, q, gA, A, x2s, participantId, digest, random);
+
+ this.state = STATE_ROUND_2_CREATED;
+
+ return new JPakeRound2Payload(participantId, A, knowledgeProofForX2s);
+ }
+
+ ///
+ /// Validates the payload received from the other participant during round 2.
+ /// Note that this DOES NOT detect a non-common password.
+ /// The only indication of a non-common password is through derivation
+ /// of different keys (which can be detected explicitly by executing round 3 and round 4)
+ ///
+ /// Must be called prior to CalculateKeyingMaterial().
+ ///
+ /// After execution, the State state will be STATE_ROUND_2_VALIDATED.
+ ///
+ /// Throws CryptoException if validation fails. Throws
+ /// InvalidOperationException if called prior to ValidateRound1PayloadReceived(JPakeRound1Payload), or multiple times
+ ///
+ public virtual void ValidateRound2PayloadReceived(JPakeRound2Payload round2PayloadReceived)
+ {
+ if (this.state >= STATE_ROUND_2_VALIDATED)
+ throw new InvalidOperationException("Validation already attempted for round 2 payload for " + this.participantId);
+ if (this.state < STATE_ROUND_1_VALIDATED)
+ throw new InvalidOperationException("Round 1 payload must be validated prior to validation round 2 payload for " + this.participantId);
+
+ BigInteger gB = JPakeUtilities.CalculateGA(p, gx3, gx1, gx2);
+ this.b = round2PayloadReceived.A;
+ BigInteger[] knowledgeProofForX4s = round2PayloadReceived.KnowledgeProofForX2s;
+
+ JPakeUtilities.ValidateParticipantIdsDiffer(participantId, round2PayloadReceived.ParticipantId);
+ JPakeUtilities.ValidateParticipantIdsEqual(this.partnerParticipantId, round2PayloadReceived.ParticipantId);
+ JPakeUtilities.ValidateGa(gB);
+ JPakeUtilities.ValidateZeroKnowledgeProof(p, q, gB, b, knowledgeProofForX4s, round2PayloadReceived.ParticipantId, digest);
+
+ this.state = STATE_ROUND_2_VALIDATED;
+ }
+
+ ///
+ /// Calculates and returns the key material.
+ /// A session key must be derived from this key material using a secure key derivation function (KDF).
+ /// The KDF used to derive the key is handled externally (i.e. not by JPakeParticipant).
+ ///
+ /// The keying material will be identical for each participant if and only if
+ /// each participant's password is the same. i.e. If the participants do not
+ /// share the same password, then each participant will derive a different key.
+ /// Therefore, if you immediately start using a key derived from
+ /// the keying material, then you must handle detection of incorrect keys.
+ /// If you want to handle this detection explicitly, you can optionally perform
+ /// rounds 3 and 4. See JPakeParticipant for details on how to execute
+ /// rounds 3 and 4.
+ ///
+ /// The keying material will be in the range [0, p-1].
+ ///
+ /// ValidateRound2PayloadReceived(JPakeRound2Payload) must be called prior to this method.
+ ///
+ /// As a side effect, the internal password array is cleared, since it is no longer needed.
+ ///
+ /// After execution, the State state will be STATE_KEY_CALCULATED.
+ ///
+ /// Throws InvalidOperationException if called prior to ValidateRound2PayloadReceived(JPakeRound2Payload),
+ /// or if called multiple times.
+ ///
+ public virtual BigInteger CalculateKeyingMaterial()
+ {
+ if (this.state >= STATE_KEY_CALCULATED)
+ throw new InvalidOperationException("Key already calculated for " + participantId);
+ if (this.state < STATE_ROUND_2_VALIDATED)
+ throw new InvalidOperationException("Round 2 payload must be validated prior to creating key for " + participantId);
+
+ BigInteger s = JPakeUtilities.CalculateS(password);
+
+ // Clear the password array from memory, since we don't need it anymore.
+ // Also set the field to null as a flag to indicate that the key has already been calculated.
+ Array.Clear(password, 0, password.Length);
+ this.password = null;
+
+ BigInteger keyingMaterial = JPakeUtilities.CalculateKeyingMaterial(p, q, gx4, x2, s, b);
+
+ // Clear the ephemeral private key fields as well.
+ // Note that we're relying on the garbage collector to do its job to clean these up.
+ // The old objects will hang around in memory until the garbage collector destroys them.
+ //
+ // If the ephemeral private keys x1 and x2 are leaked,
+ // the attacker might be able to brute-force the password.
+ this.x1 = null;
+ this.x2 = null;
+ this.b = null;
+
+ // Do not clear gx* yet, since those are needed by round 3.
+
+ this.state = STATE_KEY_CALCULATED;
+
+ return keyingMaterial;
+ }
+
+ ///
+ /// Creates and returns the payload to send to the other participant during round 3.
+ ///
+ /// See JPakeParticipant for more details on round 3.
+ ///
+ /// After execution, the State state} will be STATE_ROUND_3_CREATED.
+ /// Throws InvalidOperationException if called prior to CalculateKeyingMaterial, or multiple
+ /// times.
+ ///
+ /// The keying material as returned from CalculateKeyingMaterial().
+ public virtual JPakeRound3Payload CreateRound3PayloadToSend(BigInteger keyingMaterial)
+ {
+ if (this.state >= STATE_ROUND_3_CREATED)
+ throw new InvalidOperationException("Round 3 payload already created for " + this.participantId);
+ if (this.state < STATE_KEY_CALCULATED)
+ throw new InvalidOperationException("Keying material must be calculated prior to creating round 3 payload for " + this.participantId);
+
+ BigInteger macTag = JPakeUtilities.CalculateMacTag(
+ this.participantId,
+ this.partnerParticipantId,
+ this.gx1,
+ this.gx2,
+ this.gx3,
+ this.gx4,
+ keyingMaterial,
+ this.digest);
+
+ this.state = STATE_ROUND_3_CREATED;
+
+ return new JPakeRound3Payload(participantId, macTag);
+ }
+
+ ///
+ /// Validates the payload received from the other participant during round 3.
+ ///
+ /// See JPakeParticipant for more details on round 3.
+ ///
+ /// After execution, the State state will be STATE_ROUND_3_VALIDATED.
+ ///
+ /// Throws CryptoException if validation fails. Throws InvalidOperationException if called prior to
+ /// CalculateKeyingMaterial or multiple times
+ ///
+ /// The round 3 payload received from the other participant.
+ /// The keying material as returned from CalculateKeyingMaterial().
+ public virtual void ValidateRound3PayloadReceived(JPakeRound3Payload round3PayloadReceived, BigInteger keyingMaterial)
+ {
+ if (this.state >= STATE_ROUND_3_VALIDATED)
+ throw new InvalidOperationException("Validation already attempted for round 3 payload for " + this.participantId);
+ if (this.state < STATE_KEY_CALCULATED)
+ throw new InvalidOperationException("Keying material must be calculated prior to validating round 3 payload for " + this.participantId);
+
+ JPakeUtilities.ValidateParticipantIdsDiffer(participantId, round3PayloadReceived.ParticipantId);
+ JPakeUtilities.ValidateParticipantIdsEqual(this.partnerParticipantId, round3PayloadReceived.ParticipantId);
+
+ JPakeUtilities.ValidateMacTag(
+ this.participantId,
+ this.partnerParticipantId,
+ this.gx1,
+ this.gx2,
+ this.gx3,
+ this.gx4,
+ keyingMaterial,
+ this.digest,
+ round3PayloadReceived.MacTag);
+
+ // Clear the rest of the fields.
+ this.gx1 = null;
+ this.gx2 = null;
+ this.gx3 = null;
+ this.gx4 = null;
+
+ this.state = STATE_ROUND_3_VALIDATED;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeParticipant.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeParticipant.cs.meta
new file mode 100644
index 00000000..6e8d86e3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeParticipant.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 8a86105cd9524ff40925c8a6fa7cb124
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakePrimeOrderGroup.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakePrimeOrderGroup.cs
new file mode 100644
index 00000000..42107e13
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakePrimeOrderGroup.cs
@@ -0,0 +1,107 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement.JPake
+{
+ ///
+ /// A pre-computed prime order group for use during a J-PAKE exchange.
+ ///
+ /// Typically a Schnorr group is used. In general, J-PAKE can use any prime order group
+ /// that is suitable for public key cryptography, including elliptic curve cryptography.
+ ///
+ /// See JPakePrimeOrderGroups for convenient standard groups.
+ ///
+ /// NIST publishes
+ /// many groups that can be used for the desired level of security.
+ ///
+ public class JPakePrimeOrderGroup
+ {
+ private readonly BigInteger p;
+ private readonly BigInteger q;
+ private readonly BigInteger g;
+
+ ///
+ /// Constructs a new JPakePrimeOrderGroup.
+ ///
+ /// In general, you should use one of the pre-approved groups from
+ /// JPakePrimeOrderGroups, rather than manually constructing one.
+ ///
+ /// The following basic checks are performed:
+ ///
+ /// p-1 must be evenly divisible by q
+ /// g must be in [2, p-1]
+ /// g^q mod p must equal 1
+ /// p must be prime (within reasonably certainty)
+ /// q must be prime (within reasonably certainty)
+ ///
+ /// The prime checks are performed using BigInteger#isProbablePrime(int),
+ /// and are therefore subject to the same probability guarantees.
+ ///
+ /// These checks prevent trivial mistakes.
+ /// However, due to the small uncertainties if p and q are not prime,
+ /// advanced attacks are not prevented.
+ /// Use it at your own risk.
+ ///
+ /// Throws NullReferenceException if any argument is null. Throws
+ /// InvalidOperationException is any of the above validations fail.
+ ///
+ public JPakePrimeOrderGroup(BigInteger p, BigInteger q, BigInteger g)
+ : this(p, q, g, false)
+ {
+ // Don't skip the checks on user-specified groups.
+ }
+
+ ///
+ /// Constructor used by the pre-approved groups in JPakePrimeOrderGroups.
+ /// These pre-approved groups can avoid the expensive checks.
+ /// User-specified groups should not use this constructor.
+ ///
+ public JPakePrimeOrderGroup(BigInteger p, BigInteger q, BigInteger g, bool skipChecks)
+ {
+ JPakeUtilities.ValidateNotNull(p, "p");
+ JPakeUtilities.ValidateNotNull(q, "q");
+ JPakeUtilities.ValidateNotNull(g, "g");
+
+ if (!skipChecks)
+ {
+ if (!p.Subtract(JPakeUtilities.One).Mod(q).Equals(JPakeUtilities.Zero))
+ throw new ArgumentException("p-1 must be evenly divisible by q");
+ if (g.CompareTo(BigInteger.Two) == -1 || g.CompareTo(p.Subtract(JPakeUtilities.One)) == 1)
+ throw new ArgumentException("g must be in [2, p-1]");
+ if (!g.ModPow(q, p).Equals(JPakeUtilities.One))
+ throw new ArgumentException("g^q mod p must equal 1");
+
+ // Note these checks do not guarantee that p and q are prime.
+ // We just have reasonable certainty that they are prime.
+ if (!p.IsProbablePrime(20))
+ throw new ArgumentException("p must be prime");
+ if (!q.IsProbablePrime(20))
+ throw new ArgumentException("q must be prime");
+ }
+
+ this.p = p;
+ this.q = q;
+ this.g = g;
+ }
+
+ public virtual BigInteger P
+ {
+ get { return p; }
+ }
+
+ public virtual BigInteger Q
+ {
+ get { return q; }
+ }
+
+ public virtual BigInteger G
+ {
+ get { return g; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakePrimeOrderGroup.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakePrimeOrderGroup.cs.meta
new file mode 100644
index 00000000..5f78d44a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakePrimeOrderGroup.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 815a3d26dbbb4e047a319b26542acdb1
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakePrimeOrderGroups.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakePrimeOrderGroups.cs
new file mode 100644
index 00000000..1d1a92f2
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakePrimeOrderGroups.cs
@@ -0,0 +1,112 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement.JPake
+{
+ ///
+ /// Standard pre-computed prime order groups for use by J-PAKE.
+ /// (J-PAKE can use pre-computed prime order groups, same as DSA and Diffie-Hellman.)
+ ///
+ /// This class contains some convenient constants for use as input for
+ /// constructing {@link JPAKEParticipant}s.
+ ///
+ /// The prime order groups below are taken from Sun's JDK JavaDoc (docs/guide/security/CryptoSpec.html#AppB),
+ /// and from the prime order groups
+ /// published by NIST.
+ ///
+ public class JPakePrimeOrderGroups
+ {
+ ///
+ /// From Sun's JDK JavaDoc (docs/guide/security/CryptoSpec.html#AppB)
+ /// 1024-bit p, 160-bit q and 1024-bit g for 80-bit security.
+ ///
+ public static readonly JPakePrimeOrderGroup SUN_JCE_1024 = new JPakePrimeOrderGroup(
+ // p
+ new BigInteger(
+ "fd7f53811d75122952df4a9c2eece4e7f611b7523cef4400c31e3f80b6512669" +
+ "455d402251fb593d8d58fabfc5f5ba30f6cb9b556cd7813b801d346ff26660b7" +
+ "6b9950a5a49f9fe8047b1022c24fbba9d7feb7c61bf83b57e7c6a8a6150f04fb" +
+ "83f6d3c51ec3023554135a169132f675f3ae2b61d72aeff22203199dd14801c7", 16),
+ // q
+ new BigInteger("9760508f15230bccb292b982a2eb840bf0581cf5", 16),
+ // g
+ new BigInteger(
+ "f7e1a085d69b3ddecbbcab5c36b857b97994afbbfa3aea82f9574c0b3d078267" +
+ "5159578ebad4594fe67107108180b449167123e84c281613b7cf09328cc8a6e1" +
+ "3c167a8b547c8d28e0a3ae1e2bb3a675916ea37f0bfa213562f1fb627a01243b" +
+ "cca4f1bea8519089a883dfe15ae59f06928b665e807b552564014c3bfecf492a", 16),
+ true
+ );
+
+ ///
+ /// From NIST.
+ /// 2048-bit p, 224-bit q and 2048-bit g for 112-bit security.
+ ///
+ public static readonly JPakePrimeOrderGroup NIST_2048 = new JPakePrimeOrderGroup(
+ // p
+ new BigInteger(
+ "C196BA05AC29E1F9C3C72D56DFFC6154A033F1477AC88EC37F09BE6C5BB95F51" +
+ "C296DD20D1A28A067CCC4D4316A4BD1DCA55ED1066D438C35AEBAABF57E7DAE4" +
+ "28782A95ECA1C143DB701FD48533A3C18F0FE23557EA7AE619ECACC7E0B51652" +
+ "A8776D02A425567DED36EABD90CA33A1E8D988F0BBB92D02D1D20290113BB562" +
+ "CE1FC856EEB7CDD92D33EEA6F410859B179E7E789A8F75F645FAE2E136D252BF" +
+ "FAFF89528945C1ABE705A38DBC2D364AADE99BE0D0AAD82E5320121496DC65B3" +
+ "930E38047294FF877831A16D5228418DE8AB275D7D75651CEFED65F78AFC3EA7" +
+ "FE4D79B35F62A0402A1117599ADAC7B269A59F353CF450E6982D3B1702D9CA83", 16),
+ // q
+ new BigInteger("90EAF4D1AF0708B1B612FF35E0A2997EB9E9D263C9CE659528945C0D", 16),
+ // g
+ new BigInteger(
+ "A59A749A11242C58C894E9E5A91804E8FA0AC64B56288F8D47D51B1EDC4D6544" +
+ "4FECA0111D78F35FC9FDD4CB1F1B79A3BA9CBEE83A3F811012503C8117F98E50" +
+ "48B089E387AF6949BF8784EBD9EF45876F2E6A5A495BE64B6E770409494B7FEE" +
+ "1DBB1E4B2BC2A53D4F893D418B7159592E4FFFDF6969E91D770DAEBD0B5CB14C" +
+ "00AD68EC7DC1E5745EA55C706C4A1C5C88964E34D09DEB753AD418C1AD0F4FDF" +
+ "D049A955E5D78491C0B7A2F1575A008CCD727AB376DB6E695515B05BD412F5B8" +
+ "C2F4C77EE10DA48ABD53F5DD498927EE7B692BBBCDA2FB23A516C5B4533D7398" +
+ "0B2A3B60E384ED200AE21B40D273651AD6060C13D97FD69AA13C5611A51B9085", 16),
+ true
+ );
+
+ ///
+ /// From NIST.
+ /// 3072-bit p, 256-bit q and 3072-bit g for 128-bit security.
+ ///
+ public static readonly JPakePrimeOrderGroup NIST_3072 = new JPakePrimeOrderGroup(
+ // p
+ new BigInteger(
+ "90066455B5CFC38F9CAA4A48B4281F292C260FEEF01FD61037E56258A7795A1C" +
+ "7AD46076982CE6BB956936C6AB4DCFE05E6784586940CA544B9B2140E1EB523F" +
+ "009D20A7E7880E4E5BFA690F1B9004A27811CD9904AF70420EEFD6EA11EF7DA1" +
+ "29F58835FF56B89FAA637BC9AC2EFAAB903402229F491D8D3485261CD068699B" +
+ "6BA58A1DDBBEF6DB51E8FE34E8A78E542D7BA351C21EA8D8F1D29F5D5D159394" +
+ "87E27F4416B0CA632C59EFD1B1EB66511A5A0FBF615B766C5862D0BD8A3FE7A0" +
+ "E0DA0FB2FE1FCB19E8F9996A8EA0FCCDE538175238FC8B0EE6F29AF7F642773E" +
+ "BE8CD5402415A01451A840476B2FCEB0E388D30D4B376C37FE401C2A2C2F941D" +
+ "AD179C540C1C8CE030D460C4D983BE9AB0B20F69144C1AE13F9383EA1C08504F" +
+ "B0BF321503EFE43488310DD8DC77EC5B8349B8BFE97C2C560EA878DE87C11E3D" +
+ "597F1FEA742D73EEC7F37BE43949EF1A0D15C3F3E3FC0A8335617055AC91328E" +
+ "C22B50FC15B941D3D1624CD88BC25F3E941FDDC6200689581BFEC416B4B2CB73", 16),
+ // q
+ new BigInteger("CFA0478A54717B08CE64805B76E5B14249A77A4838469DF7F7DC987EFCCFB11D", 16),
+ // g
+ new BigInteger(
+ "5E5CBA992E0A680D885EB903AEA78E4A45A469103D448EDE3B7ACCC54D521E37" +
+ "F84A4BDD5B06B0970CC2D2BBB715F7B82846F9A0C393914C792E6A923E2117AB" +
+ "805276A975AADB5261D91673EA9AAFFEECBFA6183DFCB5D3B7332AA19275AFA1" +
+ "F8EC0B60FB6F66CC23AE4870791D5982AAD1AA9485FD8F4A60126FEB2CF05DB8" +
+ "A7F0F09B3397F3937F2E90B9E5B9C9B6EFEF642BC48351C46FB171B9BFA9EF17" +
+ "A961CE96C7E7A7CC3D3D03DFAD1078BA21DA425198F07D2481622BCE45969D9C" +
+ "4D6063D72AB7A0F08B2F49A7CC6AF335E08C4720E31476B67299E231F8BD90B3" +
+ "9AC3AE3BE0C6B6CACEF8289A2E2873D58E51E029CAFBD55E6841489AB66B5B4B" +
+ "9BA6E2F784660896AFF387D92844CCB8B69475496DE19DA2E58259B090489AC8" +
+ "E62363CDF82CFD8EF2A427ABCD65750B506F56DDE3B988567A88126B914D7828" +
+ "E2B63A6D7ED0747EC59E0E0A23CE7D8A74C1D2C2A7AFB6A29799620F00E11C33" +
+ "787F7DED3B30E1A22D09F1FBDA1ABBBFBF25CAE05A13F812E34563F99410E73B", 16),
+ true
+ );
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakePrimeOrderGroups.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakePrimeOrderGroups.cs.meta
new file mode 100644
index 00000000..fac13fdf
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakePrimeOrderGroups.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 13d01b3239aa0c7408aecd78c5976f60
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeRound1Payload.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeRound1Payload.cs
new file mode 100644
index 00000000..38c31fba
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeRound1Payload.cs
@@ -0,0 +1,105 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement.JPake
+{
+ ///
+ /// The payload sent/received during the first round of a J-PAKE exchange.
+ ///
+ /// Each JPAKEParticipant creates and sends an instance of this payload to
+ /// the other. The payload to send should be created via
+ /// JPAKEParticipant.CreateRound1PayloadToSend().
+ ///
+ /// Each participant must also validate the payload received from the other.
+ /// The received payload should be validated via
+ /// JPAKEParticipant.ValidateRound1PayloadReceived(JPakeRound1Payload).
+ ///
+ public class JPakeRound1Payload
+ {
+ ///
+ /// The id of the JPAKEParticipant who created/sent this payload.
+ ///
+ private readonly string participantId;
+
+ ///
+ /// The value of g^x1
+ ///
+ private readonly BigInteger gx1;
+
+ ///
+ /// The value of g^x2
+ ///
+ private readonly BigInteger gx2;
+
+ ///
+ /// The zero knowledge proof for x1.
+ ///
+ /// This is a two element array, containing {g^v, r} for x1.
+ ///
+ private readonly BigInteger[] knowledgeProofForX1;
+
+ ///
+ /// The zero knowledge proof for x2.
+ ///
+ /// This is a two element array, containing {g^v, r} for x2.
+ ///
+ private readonly BigInteger[] knowledgeProofForX2;
+
+ public JPakeRound1Payload(string participantId, BigInteger gx1, BigInteger gx2, BigInteger[] knowledgeProofForX1, BigInteger[] knowledgeProofForX2)
+ {
+ JPakeUtilities.ValidateNotNull(participantId, "participantId");
+ JPakeUtilities.ValidateNotNull(gx1, "gx1");
+ JPakeUtilities.ValidateNotNull(gx2, "gx2");
+ JPakeUtilities.ValidateNotNull(knowledgeProofForX1, "knowledgeProofForX1");
+ JPakeUtilities.ValidateNotNull(knowledgeProofForX2, "knowledgeProofForX2");
+
+ this.participantId = participantId;
+ this.gx1 = gx1;
+ this.gx2 = gx2;
+ this.knowledgeProofForX1 = new BigInteger[knowledgeProofForX1.Length];
+ Array.Copy(knowledgeProofForX1, this.knowledgeProofForX1, knowledgeProofForX1.Length);
+ this.knowledgeProofForX2 = new BigInteger[knowledgeProofForX2.Length];
+ Array.Copy(knowledgeProofForX2, this.knowledgeProofForX2, knowledgeProofForX2.Length);
+ }
+
+ public virtual string ParticipantId
+ {
+ get { return participantId; }
+ }
+
+ public virtual BigInteger Gx1
+ {
+ get { return gx1; }
+ }
+
+ public virtual BigInteger Gx2
+ {
+ get { return gx2; }
+ }
+
+ public virtual BigInteger[] KnowledgeProofForX1
+ {
+ get
+ {
+ BigInteger[] kp = new BigInteger[knowledgeProofForX1.Length];
+ Array.Copy(knowledgeProofForX1, kp, knowledgeProofForX1.Length);
+ return kp;
+ }
+ }
+
+ public virtual BigInteger[] KnowledgeProofForX2
+ {
+ get
+ {
+ BigInteger[] kp = new BigInteger[knowledgeProofForX2.Length];
+ Array.Copy(knowledgeProofForX2, kp, knowledgeProofForX2.Length);
+ return kp;
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeRound1Payload.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeRound1Payload.cs.meta
new file mode 100644
index 00000000..4bd2b84d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeRound1Payload.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 7fc56df6fc654ef4bb43c5563964146f
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeRound2Payload.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeRound2Payload.cs
new file mode 100644
index 00000000..5e900653
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeRound2Payload.cs
@@ -0,0 +1,76 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement.JPake
+{
+ ///
+ /// The payload sent/received during the second round of a J-PAKE exchange.
+ ///
+ /// Each JPAKEParticipant creates and sends an instance
+ /// of this payload to the other JPAKEParticipant.
+ /// The payload to send should be created via
+ /// JPAKEParticipant#createRound2PayloadToSend()
+ ///
+ /// Each JPAKEParticipant must also validate the payload
+ /// received from the other JPAKEParticipant.
+ /// The received payload should be validated via
+ /// JPAKEParticipant#validateRound2PayloadReceived(JPakeRound2Payload)
+ ///
+ public class JPakeRound2Payload
+ {
+ ///
+ /// The id of the JPAKEParticipant who created/sent this payload.
+ ///
+ private readonly string participantId;
+
+ ///
+ /// The value of A, as computed during round 2.
+ ///
+ private readonly BigInteger a;
+
+ ///
+ /// The zero knowledge proof for x2 * s.
+ ///
+ /// This is a two element array, containing {g^v, r} for x2 * s.
+ ///
+ private readonly BigInteger[] knowledgeProofForX2s;
+
+ public JPakeRound2Payload(string participantId, BigInteger a, BigInteger[] knowledgeProofForX2s)
+ {
+ JPakeUtilities.ValidateNotNull(participantId, "participantId");
+ JPakeUtilities.ValidateNotNull(a, "a");
+ JPakeUtilities.ValidateNotNull(knowledgeProofForX2s, "knowledgeProofForX2s");
+
+ this.participantId = participantId;
+ this.a = a;
+ this.knowledgeProofForX2s = new BigInteger[knowledgeProofForX2s.Length];
+ knowledgeProofForX2s.CopyTo(this.knowledgeProofForX2s, 0);
+ }
+
+ public virtual string ParticipantId
+ {
+ get { return participantId; }
+ }
+
+ public virtual BigInteger A
+ {
+ get { return a; }
+ }
+
+ public virtual BigInteger[] KnowledgeProofForX2s
+ {
+ get
+ {
+ BigInteger[] kp = new BigInteger[knowledgeProofForX2s.Length];
+ Array.Copy(knowledgeProofForX2s, kp, knowledgeProofForX2s.Length);
+ return kp;
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeRound2Payload.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeRound2Payload.cs.meta
new file mode 100644
index 00000000..f5e1f9a9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeRound2Payload.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: d1d38ef449df8e44a932211b157b405c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeRound3Payload.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeRound3Payload.cs
new file mode 100644
index 00000000..e98a53a7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeRound3Payload.cs
@@ -0,0 +1,55 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement.JPake
+{
+ ///
+ /// The payload sent/received during the optional third round of a J-PAKE exchange,
+ /// which is for explicit key confirmation.
+ ///
+ /// Each JPAKEParticipant creates and sends an instance
+ /// of this payload to the other JPAKEParticipant.
+ /// The payload to send should be created via
+ /// JPAKEParticipant#createRound3PayloadToSend(BigInteger)
+ ///
+ /// Eeach JPAKEParticipant must also validate the payload
+ /// received from the other JPAKEParticipant.
+ /// The received payload should be validated via
+ /// JPAKEParticipant#validateRound3PayloadReceived(JPakeRound3Payload, BigInteger)
+ ///
+ public class JPakeRound3Payload
+ {
+ ///
+ /// The id of the {@link JPAKEParticipant} who created/sent this payload.
+ ///
+ private readonly string participantId;
+
+ ///
+ /// The value of MacTag, as computed by round 3.
+ ///
+ /// See JPAKEUtil#calculateMacTag(string, string, BigInteger, BigInteger, BigInteger, BigInteger, BigInteger, org.bouncycastle.crypto.Digest)
+ ///
+ private readonly BigInteger macTag;
+
+ public JPakeRound3Payload(string participantId, BigInteger magTag)
+ {
+ this.participantId = participantId;
+ this.macTag = magTag;
+ }
+
+ public virtual string ParticipantId
+ {
+ get { return participantId; }
+ }
+
+ public virtual BigInteger MacTag
+ {
+ get { return macTag; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeRound3Payload.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeRound3Payload.cs.meta
new file mode 100644
index 00000000..b7fb8040
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeRound3Payload.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 569e3cdfa1c67e04090ea2d99c91f427
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeUtilities.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeUtilities.cs
new file mode 100644
index 00000000..d2c84c31
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeUtilities.cs
@@ -0,0 +1,394 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement.JPake
+{
+ ///
+ /// Primitives needed for a J-PAKE exchange.
+ ///
+ /// The recommended way to perform a J-PAKE exchange is by using
+ /// two JPAKEParticipants. Internally, those participants
+ /// call these primitive operations in JPakeUtilities.
+ ///
+ /// The primitives, however, can be used without a JPAKEParticipant if needed.
+ ///
+ public abstract class JPakeUtilities
+ {
+ public static readonly BigInteger Zero = BigInteger.Zero;
+ public static readonly BigInteger One = BigInteger.One;
+
+ ///
+ /// Return a value that can be used as x1 or x3 during round 1.
+ /// The returned value is a random value in the range [0, q-1].
+ ///
+ public static BigInteger GenerateX1(BigInteger q, SecureRandom random)
+ {
+ BigInteger min = Zero;
+ BigInteger max = q.Subtract(One);
+ return BigIntegers.CreateRandomInRange(min, max, random);
+ }
+
+ ///
+ /// Return a value that can be used as x2 or x4 during round 1.
+ /// The returned value is a random value in the range [1, q-1].
+ ///
+ public static BigInteger GenerateX2(BigInteger q, SecureRandom random)
+ {
+ BigInteger min = One;
+ BigInteger max = q.Subtract(One);
+ return BigIntegers.CreateRandomInRange(min, max, random);
+ }
+
+ ///
+ /// Converts the given password to a BigInteger
+ /// for use in arithmetic calculations.
+ ///
+ public static BigInteger CalculateS(char[] password)
+ {
+ return new BigInteger(Encoding.UTF8.GetBytes(password));
+ }
+
+ ///
+ /// Calculate g^x mod p as done in round 1.
+ ///
+ public static BigInteger CalculateGx(BigInteger p, BigInteger g, BigInteger x)
+ {
+ return g.ModPow(x, p);
+ }
+
+ ///
+ /// Calculate ga as done in round 2.
+ ///
+ public static BigInteger CalculateGA(BigInteger p, BigInteger gx1, BigInteger gx3, BigInteger gx4)
+ {
+ // ga = g^(x1+x3+x4) = g^x1 * g^x3 * g^x4
+ return gx1.Multiply(gx3).Multiply(gx4).Mod(p);
+ }
+
+ ///
+ /// Calculate x2 * s as done in round 2.
+ ///
+ public static BigInteger CalculateX2s(BigInteger q, BigInteger x2, BigInteger s)
+ {
+ return x2.Multiply(s).Mod(q);
+ }
+
+ ///
+ /// Calculate A as done in round 2.
+ ///
+ public static BigInteger CalculateA(BigInteger p, BigInteger q, BigInteger gA, BigInteger x2s)
+ {
+ // A = ga^(x*s)
+ return gA.ModPow(x2s, p);
+ }
+
+ ///
+ /// Calculate a zero knowledge proof of x using Schnorr's signature.
+ /// The returned array has two elements {g^v, r = v-x*h} for x.
+ ///
+ public static BigInteger[] CalculateZeroKnowledgeProof(BigInteger p, BigInteger q, BigInteger g,
+ BigInteger gx, BigInteger x, string participantId, IDigest digest, SecureRandom random)
+ {
+ /* Generate a random v, and compute g^v */
+ BigInteger vMin = Zero;
+ BigInteger vMax = q.Subtract(One);
+ BigInteger v = BigIntegers.CreateRandomInRange(vMin, vMax, random);
+
+ BigInteger gv = g.ModPow(v, p);
+ BigInteger h = CalculateHashForZeroKnowledgeProof(g, gv, gx, participantId, digest); // h
+
+ return new BigInteger[]
+ {
+ gv,
+ v.Subtract(x.Multiply(h)).Mod(q) // r = v-x*h
+ };
+ }
+
+ private static BigInteger CalculateHashForZeroKnowledgeProof(BigInteger g, BigInteger gr, BigInteger gx,
+ string participantId, IDigest digest)
+ {
+ digest.Reset();
+
+ UpdateDigestIncludingSize(digest, g);
+
+ UpdateDigestIncludingSize(digest, gr);
+
+ UpdateDigestIncludingSize(digest, gx);
+
+ UpdateDigestIncludingSize(digest, participantId);
+
+ byte[] output = DigestUtilities.DoFinal(digest);
+
+ return new BigInteger(output);
+ }
+
+ ///
+ /// Validates that g^x4 is not 1.
+ /// throws CryptoException if g^x4 is 1
+ ///
+ public static void ValidateGx4(BigInteger gx4)
+ {
+ if (gx4.Equals(One))
+ throw new CryptoException("g^x validation failed. g^x should not be 1.");
+ }
+
+ ///
+ /// Validates that ga is not 1.
+ ///
+ /// As described by Feng Hao...
+ /// Alice could simply check ga != 1 to ensure it is a generator.
+ /// In fact, as we will explain in Section 3, (x1 + x3 + x4 ) is random over Zq even in the face of active attacks.
+ /// Hence, the probability for ga = 1 is extremely small - on the order of 2^160 for 160-bit q.
+ ///
+ /// throws CryptoException if ga is 1
+ ///
+ public static void ValidateGa(BigInteger ga)
+ {
+ if (ga.Equals(One))
+ throw new CryptoException("ga is equal to 1. It should not be. The chances of this happening are on the order of 2^160 for a 160-bit q. Try again.");
+ }
+
+ ///
+ /// Validates the zero knowledge proof (generated by
+ /// calculateZeroKnowledgeProof(BigInteger, BigInteger, BigInteger, BigInteger, BigInteger, string, Digest, SecureRandom)
+ /// is correct.
+ ///
+ /// throws CryptoException if the zero knowledge proof is not correct
+ ///
+ public static void ValidateZeroKnowledgeProof(BigInteger p, BigInteger q, BigInteger g,
+ BigInteger gx, BigInteger[] zeroKnowledgeProof, string participantId, IDigest digest)
+ {
+ /* sig={g^v,r} */
+ BigInteger gv = zeroKnowledgeProof[0];
+ BigInteger r = zeroKnowledgeProof[1];
+
+ BigInteger h = CalculateHashForZeroKnowledgeProof(g, gv, gx, participantId, digest);
+ if (!(gx.CompareTo(Zero) == 1 && // g^x > 0
+ gx.CompareTo(p) == -1 && // g^x < p
+ gx.ModPow(q, p).CompareTo(One) == 0 && // g^x^q mod q = 1
+ /*
+ * Below, I took a straightforward way to compute g^r * g^x^h,
+ * which needs 2 exp. Using a simultaneous computation technique
+ * would only need 1 exp.
+ */
+ g.ModPow(r, p).Multiply(gx.ModPow(h, p)).Mod(p).CompareTo(gv) == 0)) // g^v=g^r * g^x^h
+ {
+ throw new CryptoException("Zero-knowledge proof validation failed");
+ }
+ }
+
+ ///
+ /// Calculates the keying material, which can be done after round 2 has completed.
+ /// A session key must be derived from this key material using a secure key derivation function (KDF).
+ /// The KDF used to derive the key is handled externally (i.e. not by JPAKEParticipant).
+ ///
+ /// KeyingMaterial = (B/g^{x2*x4*s})^x2
+ ///
+ public static BigInteger CalculateKeyingMaterial(BigInteger p, BigInteger q,
+ BigInteger gx4, BigInteger x2, BigInteger s, BigInteger B)
+ {
+ return gx4.ModPow(x2.Multiply(s).Negate().Mod(q), p).Multiply(B).ModPow(x2, p);
+ }
+
+ ///
+ /// Validates that the given participant ids are not equal.
+ /// (For the J-PAKE exchange, each participant must use a unique id.)
+ ///
+ /// Throws CryptoException if the participantId strings are equal.
+ ///
+ public static void ValidateParticipantIdsDiffer(string participantId1, string participantId2)
+ {
+ if (participantId1.Equals(participantId2))
+ {
+ throw new CryptoException(
+ "Both participants are using the same participantId ("
+ + participantId1
+ + "). This is not allowed. "
+ + "Each participant must use a unique participantId.");
+ }
+ }
+
+ ///
+ /// Validates that the given participant ids are equal.
+ /// This is used to ensure that the payloads received from
+ /// each round all come from the same participant.
+ ///
+ public static void ValidateParticipantIdsEqual(string expectedParticipantId, string actualParticipantId)
+ {
+ if (!expectedParticipantId.Equals(actualParticipantId))
+ {
+ throw new CryptoException(
+ "Received payload from incorrect partner ("
+ + actualParticipantId
+ + "). Expected to receive payload from "
+ + expectedParticipantId
+ + ".");
+ }
+ }
+
+ ///
+ /// Validates that the given object is not null.
+ /// throws NullReferenceException if the object is null.
+ ///
+ /// object in question
+ /// name of the object (to be used in exception message)
+ public static void ValidateNotNull(object obj, string description)
+ {
+ if (obj == null)
+ throw new ArgumentNullException(description);
+ }
+
+ ///
+ /// Calculates the MacTag (to be used for key confirmation), as defined by
+ /// NIST SP 800-56A Revision 1,
+ /// Section 8.2 Unilateral Key Confirmation for Key Agreement Schemes.
+ ///
+ /// MacTag = HMAC(MacKey, MacLen, MacData)
+ /// MacKey = H(K || "JPAKE_KC")
+ /// MacData = "KC_1_U" || participantId || partnerParticipantId || gx1 || gx2 || gx3 || gx4
+ ///
+ /// Note that both participants use "KC_1_U" because the sender of the round 3 message
+ /// is always the initiator for key confirmation.
+ ///
+ /// HMAC = {@link HMac} used with the given {@link Digest}
+ /// H = The given {@link Digest}
+ /// MacLen = length of MacTag
+ ///
+ public static BigInteger CalculateMacTag(string participantId, string partnerParticipantId,
+ BigInteger gx1, BigInteger gx2, BigInteger gx3, BigInteger gx4, BigInteger keyingMaterial, IDigest digest)
+ {
+ byte[] macKey = CalculateMacKey(keyingMaterial, digest);
+
+ HMac mac = new HMac(digest);
+ mac.Init(new KeyParameter(macKey));
+ Arrays.Fill(macKey, (byte)0);
+
+ /*
+ * MacData = "KC_1_U" || participantId_Alice || participantId_Bob || gx1 || gx2 || gx3 || gx4.
+ */
+ UpdateMac(mac, "KC_1_U");
+ UpdateMac(mac, participantId);
+ UpdateMac(mac, partnerParticipantId);
+ UpdateMac(mac, gx1);
+ UpdateMac(mac, gx2);
+ UpdateMac(mac, gx3);
+ UpdateMac(mac, gx4);
+
+ byte[] macOutput = MacUtilities.DoFinal(mac);
+
+ return new BigInteger(macOutput);
+ }
+
+ ///
+ /// Calculates the MacKey (i.e. the key to use when calculating the MagTag for key confirmation).
+ ///
+ /// MacKey = H(K || "JPAKE_KC")
+ ///
+ private static byte[] CalculateMacKey(BigInteger keyingMaterial, IDigest digest)
+ {
+ digest.Reset();
+
+ UpdateDigest(digest, keyingMaterial);
+ /*
+ * This constant is used to ensure that the macKey is NOT the same as the derived key.
+ */
+ UpdateDigest(digest, "JPAKE_KC");
+
+ return DigestUtilities.DoFinal(digest);
+ }
+
+ ///
+ /// Validates the MacTag received from the partner participant.
+ ///
+ /// throws CryptoException if the participantId strings are equal.
+ ///
+ public static void ValidateMacTag(string participantId, string partnerParticipantId,
+ BigInteger gx1, BigInteger gx2, BigInteger gx3, BigInteger gx4,
+ BigInteger keyingMaterial, IDigest digest, BigInteger partnerMacTag)
+ {
+ /*
+ * Calculate the expected MacTag using the parameters as the partner
+ * would have used when the partner called calculateMacTag.
+ *
+ * i.e. basically all the parameters are reversed.
+ * participantId <-> partnerParticipantId
+ * x1 <-> x3
+ * x2 <-> x4
+ */
+ BigInteger expectedMacTag = CalculateMacTag(partnerParticipantId, participantId, gx3, gx4, gx1, gx2, keyingMaterial, digest);
+
+ if (!expectedMacTag.Equals(partnerMacTag))
+ {
+ throw new CryptoException(
+ "Partner MacTag validation failed. "
+ + "Therefore, the password, MAC, or digest algorithm of each participant does not match.");
+ }
+ }
+
+ private static void UpdateDigest(IDigest digest, BigInteger bigInteger)
+ {
+ UpdateDigest(digest, BigIntegers.AsUnsignedByteArray(bigInteger));
+ }
+
+ private static void UpdateDigest(IDigest digest, string str)
+ {
+ UpdateDigest(digest, Encoding.UTF8.GetBytes(str));
+ }
+
+ private static void UpdateDigest(IDigest digest, byte[] bytes)
+ {
+ digest.BlockUpdate(bytes, 0, bytes.Length);
+ Arrays.Fill(bytes, (byte)0);
+ }
+
+ private static void UpdateDigestIncludingSize(IDigest digest, BigInteger bigInteger)
+ {
+ UpdateDigestIncludingSize(digest, BigIntegers.AsUnsignedByteArray(bigInteger));
+ }
+
+ private static void UpdateDigestIncludingSize(IDigest digest, string str)
+ {
+ UpdateDigestIncludingSize(digest, Encoding.UTF8.GetBytes(str));
+ }
+
+ private static void UpdateDigestIncludingSize(IDigest digest, byte[] bytes)
+ {
+ digest.BlockUpdate(IntToByteArray(bytes.Length), 0, 4);
+ digest.BlockUpdate(bytes, 0, bytes.Length);
+ Arrays.Fill(bytes, (byte)0);
+ }
+
+ private static void UpdateMac(IMac mac, BigInteger bigInteger)
+ {
+ UpdateMac(mac, BigIntegers.AsUnsignedByteArray(bigInteger));
+ }
+
+ private static void UpdateMac(IMac mac, string str)
+ {
+ UpdateMac(mac, Encoding.UTF8.GetBytes(str));
+ }
+
+ private static void UpdateMac(IMac mac, byte[] bytes)
+ {
+ mac.BlockUpdate(bytes, 0, bytes.Length);
+ Arrays.Fill(bytes, (byte)0);
+ }
+
+ private static byte[] IntToByteArray(int value)
+ {
+ return Pack.UInt32_To_BE((uint)value);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeUtilities.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeUtilities.cs.meta
new file mode 100644
index 00000000..2efcff6a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/jpake/JPakeUtilities.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: be8c03db27c054b4dbee7970d93bba33
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/kdf.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/kdf.meta
new file mode 100644
index 00000000..22b27a38
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/kdf.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 46e2b05f22025dd47b5d1c86ce8f0c93
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/kdf/ConcatenationKdfGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/kdf/ConcatenationKdfGenerator.cs
new file mode 100644
index 00000000..33475567
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/kdf/ConcatenationKdfGenerator.cs
@@ -0,0 +1,104 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement.Kdf
+{
+ /**
+ * Generator for Concatenation Key Derivation Function defined in NIST SP 800-56A, Sect 5.8.1
+ */
+ public class ConcatenationKdfGenerator
+ : IDerivationFunction
+ {
+ private readonly IDigest mDigest;
+
+ private byte[] mShared;
+ private byte[] mOtherInfo;
+ private int mHLen;
+
+ /**
+ * @param digest the digest to be used as the source of generated bytes
+ */
+ public ConcatenationKdfGenerator(IDigest digest)
+ {
+ this.mDigest = digest;
+ this.mHLen = digest.GetDigestSize();
+ }
+
+ public virtual void Init(IDerivationParameters param)
+ {
+ if (!(param is KdfParameters))
+ throw new ArgumentException("KDF parameters required for ConcatenationKdfGenerator");
+
+ KdfParameters p = (KdfParameters)param;
+
+ mShared = p.GetSharedSecret();
+ mOtherInfo = p.GetIV();
+ }
+
+ /**
+ * return the underlying digest.
+ */
+ public virtual IDigest Digest
+ {
+ get { return mDigest; }
+ }
+
+ /**
+ * fill len bytes of the output buffer with bytes generated from
+ * the derivation function.
+ *
+ * @throws DataLengthException if the out buffer is too small.
+ */
+ public virtual int GenerateBytes(byte[] outBytes, int outOff, int len)
+ {
+ if ((outBytes.Length - len) < outOff)
+ throw new DataLengthException("output buffer too small");
+
+ byte[] hashBuf = new byte[mHLen];
+ byte[] C = new byte[4];
+ uint counter = 1;
+ int outputLen = 0;
+
+ mDigest.Reset();
+
+ if (len > mHLen)
+ {
+ do
+ {
+ Pack.UInt32_To_BE(counter, C);
+
+ mDigest.BlockUpdate(C, 0, C.Length);
+ mDigest.BlockUpdate(mShared, 0, mShared.Length);
+ mDigest.BlockUpdate(mOtherInfo, 0, mOtherInfo.Length);
+
+ mDigest.DoFinal(hashBuf, 0);
+
+ Array.Copy(hashBuf, 0, outBytes, outOff + outputLen, mHLen);
+ outputLen += mHLen;
+ }
+ while ((counter++) < (len / mHLen));
+ }
+
+ if (outputLen < len)
+ {
+ Pack.UInt32_To_BE(counter, C);
+
+ mDigest.BlockUpdate(C, 0, C.Length);
+ mDigest.BlockUpdate(mShared, 0, mShared.Length);
+ mDigest.BlockUpdate(mOtherInfo, 0, mOtherInfo.Length);
+
+ mDigest.DoFinal(hashBuf, 0);
+
+ Array.Copy(hashBuf, 0, outBytes, outOff + outputLen, len - outputLen);
+ }
+
+ return len;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/kdf/ConcatenationKdfGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/kdf/ConcatenationKdfGenerator.cs.meta
new file mode 100644
index 00000000..f82a3a96
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/kdf/ConcatenationKdfGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 2968651d26eab974fbac139e56e083ed
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/kdf/DHKdfParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/kdf/DHKdfParameters.cs
new file mode 100644
index 00000000..3bde996a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/kdf/DHKdfParameters.cs
@@ -0,0 +1,61 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement.Kdf
+{
+ public class DHKdfParameters
+ : IDerivationParameters
+ {
+ private readonly DerObjectIdentifier algorithm;
+ private readonly int keySize;
+ private readonly byte[] z;
+ private readonly byte[] extraInfo;
+
+ public DHKdfParameters(
+ DerObjectIdentifier algorithm,
+ int keySize,
+ byte[] z)
+ : this(algorithm, keySize, z, null)
+ {
+ }
+
+ public DHKdfParameters(
+ DerObjectIdentifier algorithm,
+ int keySize,
+ byte[] z,
+ byte[] extraInfo)
+ {
+ this.algorithm = algorithm;
+ this.keySize = keySize;
+ this.z = z; // TODO Clone?
+ this.extraInfo = extraInfo;
+ }
+
+ public DerObjectIdentifier Algorithm
+ {
+ get { return algorithm; }
+ }
+
+ public int KeySize
+ {
+ get { return keySize; }
+ }
+
+ public byte[] GetZ()
+ {
+ // TODO Clone?
+ return z;
+ }
+
+ public byte[] GetExtraInfo()
+ {
+ // TODO Clone?
+ return extraInfo;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/kdf/DHKdfParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/kdf/DHKdfParameters.cs.meta
new file mode 100644
index 00000000..1b10be0d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/kdf/DHKdfParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 37821fa6280a2bf4a96d3dc5f096c6ac
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/kdf/DHKekGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/kdf/DHKekGenerator.cs
new file mode 100644
index 00000000..3d929667
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/kdf/DHKekGenerator.cs
@@ -0,0 +1,116 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement.Kdf
+{
+ /**
+ * RFC 2631 Diffie-hellman KEK derivation function.
+ */
+ public class DHKekGenerator
+ : IDerivationFunction
+ {
+ private readonly IDigest digest;
+
+ private DerObjectIdentifier algorithm;
+ private int keySize;
+ private byte[] z;
+ private byte[] partyAInfo;
+
+ public DHKekGenerator(IDigest digest)
+ {
+ this.digest = digest;
+ }
+
+ public virtual void Init(IDerivationParameters param)
+ {
+ DHKdfParameters parameters = (DHKdfParameters)param;
+
+ this.algorithm = parameters.Algorithm;
+ this.keySize = parameters.KeySize;
+ this.z = parameters.GetZ(); // TODO Clone?
+ this.partyAInfo = parameters.GetExtraInfo(); // TODO Clone?
+ }
+
+ public virtual IDigest Digest
+ {
+ get { return digest; }
+ }
+
+ public virtual int GenerateBytes(byte[] outBytes, int outOff, int len)
+ {
+ if ((outBytes.Length - len) < outOff)
+ {
+ throw new DataLengthException("output buffer too small");
+ }
+
+ long oBytes = len;
+ int outLen = digest.GetDigestSize();
+
+ //
+ // this is at odds with the standard implementation, the
+ // maximum value should be hBits * (2^32 - 1) where hBits
+ // is the digest output size in bits. We can't have an
+ // array with a long index at the moment...
+ //
+ if (oBytes > ((2L << 32) - 1))
+ {
+ throw new ArgumentException("Output length too large");
+ }
+
+ int cThreshold = (int)((oBytes + outLen - 1) / outLen);
+
+ byte[] dig = new byte[digest.GetDigestSize()];
+
+ uint counter = 1;
+
+ for (int i = 0; i < cThreshold; i++)
+ {
+ digest.BlockUpdate(z, 0, z.Length);
+
+ // KeySpecificInfo
+ DerSequence keyInfo = new DerSequence(
+ algorithm,
+ new DerOctetString(Pack.UInt32_To_BE(counter)));
+
+ // OtherInfo
+ Asn1EncodableVector v1 = new Asn1EncodableVector(keyInfo);
+
+ if (partyAInfo != null)
+ {
+ v1.Add(new DerTaggedObject(true, 0, new DerOctetString(partyAInfo)));
+ }
+
+ v1.Add(new DerTaggedObject(true, 2, new DerOctetString(Pack.UInt32_To_BE((uint)keySize))));
+
+ byte[] other = new DerSequence(v1).GetDerEncoded();
+
+ digest.BlockUpdate(other, 0, other.Length);
+
+ digest.DoFinal(dig, 0);
+
+ if (len > outLen)
+ {
+ Array.Copy(dig, 0, outBytes, outOff, outLen);
+ outOff += outLen;
+ len -= outLen;
+ }
+ else
+ {
+ Array.Copy(dig, 0, outBytes, outOff, len);
+ }
+
+ counter++;
+ }
+
+ digest.Reset();
+
+ return (int)oBytes;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/kdf/DHKekGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/kdf/DHKekGenerator.cs.meta
new file mode 100644
index 00000000..1549ad03
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/kdf/DHKekGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 15d1d1044377c8349b064a27a6649808
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/kdf/ECDHKekGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/kdf/ECDHKekGenerator.cs
new file mode 100644
index 00000000..14d5159d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/kdf/ECDHKekGenerator.cs
@@ -0,0 +1,59 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement.Kdf
+{
+ /**
+ * X9.63 based key derivation function for ECDH CMS.
+ */
+ public class ECDHKekGenerator
+ : IDerivationFunction
+ {
+ private readonly IDerivationFunction kdf;
+
+ private DerObjectIdentifier algorithm;
+ private int keySize;
+ private byte[] z;
+
+ public ECDHKekGenerator(IDigest digest)
+ {
+ this.kdf = new Kdf2BytesGenerator(digest);
+ }
+
+ public virtual void Init(IDerivationParameters param)
+ {
+ DHKdfParameters parameters = (DHKdfParameters)param;
+
+ this.algorithm = parameters.Algorithm;
+ this.keySize = parameters.KeySize;
+ this.z = parameters.GetZ(); // TODO Clone?
+ }
+
+ public virtual IDigest Digest
+ {
+ get { return kdf.Digest; }
+ }
+
+ public virtual int GenerateBytes(byte[] outBytes, int outOff, int len)
+ {
+ // TODO Create an ASN.1 class for this (RFC3278)
+ // ECC-CMS-SharedInfo
+ DerSequence s = new DerSequence(
+ new AlgorithmIdentifier(algorithm, DerNull.Instance),
+ new DerTaggedObject(true, 2, new DerOctetString(Pack.UInt32_To_BE((uint)keySize))));
+
+ kdf.Init(new KdfParameters(z, s.GetDerEncoded()));
+
+ return kdf.GenerateBytes(outBytes, outOff, len);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/kdf/ECDHKekGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/kdf/ECDHKekGenerator.cs.meta
new file mode 100644
index 00000000..7806536b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/kdf/ECDHKekGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 1cfab31e18f7d80498fe6cee2a7e4955
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp.meta
new file mode 100644
index 00000000..07781139
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: b6aacc3094b914340b5c92347295dc21
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6Client.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6Client.cs
new file mode 100644
index 00000000..a060206e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6Client.cs
@@ -0,0 +1,168 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement.Srp
+{
+ /**
+ * Implements the client side SRP-6a protocol. Note that this class is stateful, and therefore NOT threadsafe.
+ * This implementation of SRP is based on the optimized message sequence put forth by Thomas Wu in the paper
+ * "SRP-6: Improvements and Refinements to the Secure Remote Password Protocol, 2002"
+ */
+ public class Srp6Client
+ {
+ protected BigInteger N;
+ protected BigInteger g;
+
+ protected BigInteger privA;
+ protected BigInteger pubA;
+
+ protected BigInteger B;
+
+ protected BigInteger x;
+ protected BigInteger u;
+ protected BigInteger S;
+
+ protected BigInteger M1;
+ protected BigInteger M2;
+ protected BigInteger Key;
+
+ protected IDigest digest;
+ protected SecureRandom random;
+
+ public Srp6Client()
+ {
+ }
+
+ /**
+ * Initialises the client to begin new authentication attempt
+ * @param N The safe prime associated with the client's verifier
+ * @param g The group parameter associated with the client's verifier
+ * @param digest The digest algorithm associated with the client's verifier
+ * @param random For key generation
+ */
+ public virtual void Init(BigInteger N, BigInteger g, IDigest digest, SecureRandom random)
+ {
+ this.N = N;
+ this.g = g;
+ this.digest = digest;
+ this.random = random;
+ }
+
+ public virtual void Init(Srp6GroupParameters group, IDigest digest, SecureRandom random)
+ {
+ Init(group.N, group.G, digest, random);
+ }
+
+ /**
+ * Generates client's credentials given the client's salt, identity and password
+ * @param salt The salt used in the client's verifier.
+ * @param identity The user's identity (eg. username)
+ * @param password The user's password
+ * @return Client's public value to send to server
+ */
+ public virtual BigInteger GenerateClientCredentials(byte[] salt, byte[] identity, byte[] password)
+ {
+ this.x = Srp6Utilities.CalculateX(digest, N, salt, identity, password);
+ this.privA = SelectPrivateValue();
+ this.pubA = g.ModPow(privA, N);
+
+ return pubA;
+ }
+
+ /**
+ * Generates client's verification message given the server's credentials
+ * @param serverB The server's credentials
+ * @return Client's verification message for the server
+ * @throws CryptoException If server's credentials are invalid
+ */
+ public virtual BigInteger CalculateSecret(BigInteger serverB)
+ {
+ this.B = Srp6Utilities.ValidatePublicValue(N, serverB);
+ this.u = Srp6Utilities.CalculateU(digest, N, pubA, B);
+ this.S = CalculateS();
+
+ return S;
+ }
+
+ protected virtual BigInteger SelectPrivateValue()
+ {
+ return Srp6Utilities.GeneratePrivateValue(digest, N, g, random);
+ }
+
+ private BigInteger CalculateS()
+ {
+ BigInteger k = Srp6Utilities.CalculateK(digest, N, g);
+ BigInteger exp = u.Multiply(x).Add(privA);
+ BigInteger tmp = g.ModPow(x, N).Multiply(k).Mod(N);
+ return B.Subtract(tmp).Mod(N).ModPow(exp, N);
+ }
+
+ /**
+ * Computes the client evidence message M1 using the previously received values.
+ * To be called after calculating the secret S.
+ * @return M1: the client side generated evidence message
+ * @throws CryptoException
+ */
+ public virtual BigInteger CalculateClientEvidenceMessage()
+ {
+ // Verify pre-requirements
+ if (this.pubA == null || this.B == null || this.S == null)
+ {
+ throw new CryptoException("Impossible to compute M1: " +
+ "some data are missing from the previous operations (A,B,S)");
+ }
+ // compute the client evidence message 'M1'
+ this.M1 = Srp6Utilities.CalculateM1(digest, N, pubA, B, S);
+ return M1;
+ }
+
+ /** Authenticates the server evidence message M2 received and saves it only if correct.
+ * @param M2: the server side generated evidence message
+ * @return A boolean indicating if the server message M2 was the expected one.
+ * @throws CryptoException
+ */
+ public virtual bool VerifyServerEvidenceMessage(BigInteger serverM2)
+ {
+ // Verify pre-requirements
+ if (this.pubA == null || this.M1 == null || this.S == null)
+ {
+ throw new CryptoException("Impossible to compute and verify M2: " +
+ "some data are missing from the previous operations (A,M1,S)");
+ }
+
+ // Compute the own server evidence message 'M2'
+ BigInteger computedM2 = Srp6Utilities.CalculateM2(digest, N, pubA, M1, S);
+ if (computedM2.Equals(serverM2))
+ {
+ this.M2 = serverM2;
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Computes the final session key as a result of the SRP successful mutual authentication
+ * To be called after verifying the server evidence message M2.
+ * @return Key: the mutually authenticated symmetric session key
+ * @throws CryptoException
+ */
+ public virtual BigInteger CalculateSessionKey()
+ {
+ // Verify pre-requirements (here we enforce a previous calculation of M1 and M2)
+ if (this.S == null || this.M1 == null || this.M2 == null)
+ {
+ throw new CryptoException("Impossible to compute Key: " +
+ "some data are missing from the previous operations (S,M1,M2)");
+ }
+ this.Key = Srp6Utilities.CalculateKey(digest, N, S);
+ return Key;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6Client.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6Client.cs.meta
new file mode 100644
index 00000000..4bc10502
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6Client.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c97144c9d901452429331664aae38f7b
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6Server.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6Server.cs
new file mode 100644
index 00000000..905766fd
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6Server.cs
@@ -0,0 +1,167 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement.Srp
+{
+ /**
+ * Implements the server side SRP-6a protocol. Note that this class is stateful, and therefore NOT threadsafe.
+ * This implementation of SRP is based on the optimized message sequence put forth by Thomas Wu in the paper
+ * "SRP-6: Improvements and Refinements to the Secure Remote Password Protocol, 2002"
+ */
+ public class Srp6Server
+ {
+ protected BigInteger N;
+ protected BigInteger g;
+ protected BigInteger v;
+
+ protected SecureRandom random;
+ protected IDigest digest;
+
+ protected BigInteger A;
+
+ protected BigInteger privB;
+ protected BigInteger pubB;
+
+ protected BigInteger u;
+ protected BigInteger S;
+ protected BigInteger M1;
+ protected BigInteger M2;
+ protected BigInteger Key;
+
+ public Srp6Server()
+ {
+ }
+
+ /**
+ * Initialises the server to accept a new client authentication attempt
+ * @param N The safe prime associated with the client's verifier
+ * @param g The group parameter associated with the client's verifier
+ * @param v The client's verifier
+ * @param digest The digest algorithm associated with the client's verifier
+ * @param random For key generation
+ */
+ public virtual void Init(BigInteger N, BigInteger g, BigInteger v, IDigest digest, SecureRandom random)
+ {
+ this.N = N;
+ this.g = g;
+ this.v = v;
+
+ this.random = random;
+ this.digest = digest;
+ }
+
+ public virtual void Init(Srp6GroupParameters group, BigInteger v, IDigest digest, SecureRandom random)
+ {
+ Init(group.N, group.G, v, digest, random);
+ }
+
+ /**
+ * Generates the server's credentials that are to be sent to the client.
+ * @return The server's public value to the client
+ */
+ public virtual BigInteger GenerateServerCredentials()
+ {
+ BigInteger k = Srp6Utilities.CalculateK(digest, N, g);
+ this.privB = SelectPrivateValue();
+ this.pubB = k.Multiply(v).Mod(N).Add(g.ModPow(privB, N)).Mod(N);
+
+ return pubB;
+ }
+
+ /**
+ * Processes the client's credentials. If valid the shared secret is generated and returned.
+ * @param clientA The client's credentials
+ * @return A shared secret BigInteger
+ * @throws CryptoException If client's credentials are invalid
+ */
+ public virtual BigInteger CalculateSecret(BigInteger clientA)
+ {
+ this.A = Srp6Utilities.ValidatePublicValue(N, clientA);
+ this.u = Srp6Utilities.CalculateU(digest, N, A, pubB);
+ this.S = CalculateS();
+
+ return S;
+ }
+
+ protected virtual BigInteger SelectPrivateValue()
+ {
+ return Srp6Utilities.GeneratePrivateValue(digest, N, g, random);
+ }
+
+ private BigInteger CalculateS()
+ {
+ return v.ModPow(u, N).Multiply(A).Mod(N).ModPow(privB, N);
+ }
+
+ /**
+ * Authenticates the received client evidence message M1 and saves it only if correct.
+ * To be called after calculating the secret S.
+ * @param M1: the client side generated evidence message
+ * @return A boolean indicating if the client message M1 was the expected one.
+ * @throws CryptoException
+ */
+ public virtual bool VerifyClientEvidenceMessage(BigInteger clientM1)
+ {
+ // Verify pre-requirements
+ if (this.A == null || this.pubB == null || this.S == null)
+ {
+ throw new CryptoException("Impossible to compute and verify M1: " +
+ "some data are missing from the previous operations (A,B,S)");
+ }
+
+ // Compute the own client evidence message 'M1'
+ BigInteger computedM1 = Srp6Utilities.CalculateM1(digest, N, A, pubB, S);
+ if (computedM1.Equals(clientM1))
+ {
+ this.M1 = clientM1;
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Computes the server evidence message M2 using the previously verified values.
+ * To be called after successfully verifying the client evidence message M1.
+ * @return M2: the server side generated evidence message
+ * @throws CryptoException
+ */
+ public virtual BigInteger CalculateServerEvidenceMessage()
+ {
+ // Verify pre-requirements
+ if (this.A == null || this.M1 == null || this.S == null)
+ {
+ throw new CryptoException("Impossible to compute M2: " +
+ "some data are missing from the previous operations (A,M1,S)");
+ }
+
+ // Compute the server evidence message 'M2'
+ this.M2 = Srp6Utilities.CalculateM2(digest, N, A, M1, S);
+ return M2;
+ }
+
+ /**
+ * Computes the final session key as a result of the SRP successful mutual authentication
+ * To be called after calculating the server evidence message M2.
+ * @return Key: the mutual authenticated symmetric session key
+ * @throws CryptoException
+ */
+ public virtual BigInteger CalculateSessionKey()
+ {
+ // Verify pre-requirements
+ if (this.S == null || this.M1 == null || this.M2 == null)
+ {
+ throw new CryptoException("Impossible to compute Key: " +
+ "some data are missing from the previous operations (S,M1,M2)");
+ }
+ this.Key = Srp6Utilities.CalculateKey(digest, N, S);
+ return Key;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6Server.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6Server.cs.meta
new file mode 100644
index 00000000..851efd2a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6Server.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 036c95a84f457134c94137d3f36c6603
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6StandardGroups.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6StandardGroups.cs
new file mode 100644
index 00000000..0e6e4207
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6StandardGroups.cs
@@ -0,0 +1,163 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement.Srp
+{
+ public class Srp6StandardGroups
+ {
+ private static BigInteger FromHex(string hex)
+ {
+ return new BigInteger(1, Hex.Decode(hex));
+ }
+
+ private static Srp6GroupParameters FromNG(string hexN, string hexG)
+ {
+ return new Srp6GroupParameters(FromHex(hexN), FromHex(hexG));
+ }
+
+ /*
+ * RFC 5054
+ */
+ private const string rfc5054_1024_N = "EEAF0AB9ADB38DD69C33F80AFA8FC5E86072618775FF3C0B9EA2314C"
+ + "9C256576D674DF7496EA81D3383B4813D692C6E0E0D5D8E250B98BE4"
+ + "8E495C1D6089DAD15DC7D7B46154D6B6CE8EF4AD69B15D4982559B29"
+ + "7BCF1885C529F566660E57EC68EDBC3C05726CC02FD4CBF4976EAA9A" + "FD5138FE8376435B9FC61D2FC0EB06E3";
+ private const string rfc5054_1024_g = "02";
+ public static readonly Srp6GroupParameters rfc5054_1024 = FromNG(rfc5054_1024_N, rfc5054_1024_g);
+
+ private const string rfc5054_1536_N = "9DEF3CAFB939277AB1F12A8617A47BBBDBA51DF499AC4C80BEEEA961"
+ + "4B19CC4D5F4F5F556E27CBDE51C6A94BE4607A291558903BA0D0F843"
+ + "80B655BB9A22E8DCDF028A7CEC67F0D08134B1C8B97989149B609E0B"
+ + "E3BAB63D47548381DBC5B1FC764E3F4B53DD9DA1158BFD3E2B9C8CF5"
+ + "6EDF019539349627DB2FD53D24B7C48665772E437D6C7F8CE442734A"
+ + "F7CCB7AE837C264AE3A9BEB87F8A2FE9B8B5292E5A021FFF5E91479E"
+ + "8CE7A28C2442C6F315180F93499A234DCF76E3FED135F9BB";
+ private const string rfc5054_1536_g = "02";
+ public static readonly Srp6GroupParameters rfc5054_1536 = FromNG(rfc5054_1536_N, rfc5054_1536_g);
+
+ private const string rfc5054_2048_N = "AC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC319294"
+ + "3DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310D"
+ + "CD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FB"
+ + "D5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF74"
+ + "7359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A"
+ + "436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D"
+ + "5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E73"
+ + "03CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB6"
+ + "94B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F" + "9E4AFF73";
+ private const string rfc5054_2048_g = "02";
+ public static readonly Srp6GroupParameters rfc5054_2048 = FromNG(rfc5054_2048_N, rfc5054_2048_g);
+
+ private const string rfc5054_3072_N = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
+ + "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
+ + "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
+ + "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
+ + "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8"
+ + "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D"
+ + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C"
+ + "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718"
+ + "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D"
+ + "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D"
+ + "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226"
+ + "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
+ + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + "E0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF";
+ private const string rfc5054_3072_g = "05";
+ public static readonly Srp6GroupParameters rfc5054_3072 = FromNG(rfc5054_3072_N, rfc5054_3072_g);
+
+ private const string rfc5054_4096_N = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
+ + "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
+ + "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
+ + "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
+ + "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8"
+ + "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D"
+ + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C"
+ + "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718"
+ + "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D"
+ + "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D"
+ + "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226"
+ + "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
+ + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC"
+ + "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26"
+ + "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB"
+ + "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2"
+ + "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127"
+ + "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199" + "FFFFFFFFFFFFFFFF";
+ private const string rfc5054_4096_g = "05";
+ public static readonly Srp6GroupParameters rfc5054_4096 = FromNG(rfc5054_4096_N, rfc5054_4096_g);
+
+ private const string rfc5054_6144_N = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
+ + "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
+ + "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
+ + "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
+ + "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8"
+ + "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D"
+ + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C"
+ + "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718"
+ + "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D"
+ + "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D"
+ + "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226"
+ + "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
+ + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC"
+ + "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26"
+ + "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB"
+ + "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2"
+ + "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127"
+ + "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492"
+ + "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406"
+ + "AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918"
+ + "DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151"
+ + "2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03"
+ + "F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F"
+ + "BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA"
+ + "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B"
+ + "B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632"
+ + "387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E" + "6DCC4024FFFFFFFFFFFFFFFF";
+ private const string rfc5054_6144_g = "05";
+ public static readonly Srp6GroupParameters rfc5054_6144 = FromNG(rfc5054_6144_N, rfc5054_6144_g);
+
+ private const string rfc5054_8192_N = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
+ + "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
+ + "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
+ + "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
+ + "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8"
+ + "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D"
+ + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C"
+ + "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718"
+ + "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D"
+ + "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D"
+ + "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226"
+ + "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
+ + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC"
+ + "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26"
+ + "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB"
+ + "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2"
+ + "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127"
+ + "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492"
+ + "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406"
+ + "AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918"
+ + "DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151"
+ + "2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03"
+ + "F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F"
+ + "BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA"
+ + "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B"
+ + "B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632"
+ + "387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E"
+ + "6DBE115974A3926F12FEE5E438777CB6A932DF8CD8BEC4D073B931BA"
+ + "3BC832B68D9DD300741FA7BF8AFC47ED2576F6936BA424663AAB639C"
+ + "5AE4F5683423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9"
+ + "22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B4BCBC886"
+ + "2F8385DDFA9D4B7FA2C087E879683303ED5BDD3A062B3CF5B3A278A6"
+ + "6D2A13F83F44F82DDF310EE074AB6A364597E899A0255DC164F31CC5"
+ + "0846851DF9AB48195DED7EA1B1D510BD7EE74D73FAF36BC31ECFA268"
+ + "359046F4EB879F924009438B481C6CD7889A002ED5EE382BC9190DA6"
+ + "FC026E479558E4475677E9AA9E3050E2765694DFC81F56E880B96E71" + "60C980DD98EDD3DFFFFFFFFFFFFFFFFF";
+ private const string rfc5054_8192_g = "13";
+ public static readonly Srp6GroupParameters rfc5054_8192 = FromNG(rfc5054_8192_N, rfc5054_8192_g);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6StandardGroups.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6StandardGroups.cs.meta
new file mode 100644
index 00000000..d68e5d37
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6StandardGroups.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 031c325c69c0dde4090a9a0a0fc4ac5e
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6Utilities.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6Utilities.cs
new file mode 100644
index 00000000..52941e96
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6Utilities.cs
@@ -0,0 +1,157 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement.Srp
+{
+ public class Srp6Utilities
+ {
+ public static BigInteger CalculateK(IDigest digest, BigInteger N, BigInteger g)
+ {
+ return HashPaddedPair(digest, N, N, g);
+ }
+
+ public static BigInteger CalculateU(IDigest digest, BigInteger N, BigInteger A, BigInteger B)
+ {
+ return HashPaddedPair(digest, N, A, B);
+ }
+
+ public static BigInteger CalculateX(IDigest digest, BigInteger N, byte[] salt, byte[] identity, byte[] password)
+ {
+ byte[] output = new byte[digest.GetDigestSize()];
+
+ digest.BlockUpdate(identity, 0, identity.Length);
+ digest.Update((byte)':');
+ digest.BlockUpdate(password, 0, password.Length);
+ digest.DoFinal(output, 0);
+
+ digest.BlockUpdate(salt, 0, salt.Length);
+ digest.BlockUpdate(output, 0, output.Length);
+ digest.DoFinal(output, 0);
+
+ return new BigInteger(1, output);
+ }
+
+ public static BigInteger GeneratePrivateValue(IDigest digest, BigInteger N, BigInteger g, SecureRandom random)
+ {
+ int minBits = System.Math.Min(256, N.BitLength / 2);
+ BigInteger min = BigInteger.One.ShiftLeft(minBits - 1);
+ BigInteger max = N.Subtract(BigInteger.One);
+
+ return BigIntegers.CreateRandomInRange(min, max, random);
+ }
+
+ public static BigInteger ValidatePublicValue(BigInteger N, BigInteger val)
+ {
+ val = val.Mod(N);
+
+ // Check that val % N != 0
+ if (val.Equals(BigInteger.Zero))
+ throw new CryptoException("Invalid public value: 0");
+
+ return val;
+ }
+
+ /**
+ * Computes the client evidence message (M1) according to the standard routine:
+ * M1 = H( A | B | S )
+ * @param digest The Digest used as the hashing function H
+ * @param N Modulus used to get the pad length
+ * @param A The public client value
+ * @param B The public server value
+ * @param S The secret calculated by both sides
+ * @return M1 The calculated client evidence message
+ */
+ public static BigInteger CalculateM1(IDigest digest, BigInteger N, BigInteger A, BigInteger B, BigInteger S)
+ {
+ BigInteger M1 = HashPaddedTriplet(digest, N, A, B, S);
+ return M1;
+ }
+
+ /**
+ * Computes the server evidence message (M2) according to the standard routine:
+ * M2 = H( A | M1 | S )
+ * @param digest The Digest used as the hashing function H
+ * @param N Modulus used to get the pad length
+ * @param A The public client value
+ * @param M1 The client evidence message
+ * @param S The secret calculated by both sides
+ * @return M2 The calculated server evidence message
+ */
+ public static BigInteger CalculateM2(IDigest digest, BigInteger N, BigInteger A, BigInteger M1, BigInteger S)
+ {
+ BigInteger M2 = HashPaddedTriplet(digest, N, A, M1, S);
+ return M2;
+ }
+
+ /**
+ * Computes the final Key according to the standard routine: Key = H(S)
+ * @param digest The Digest used as the hashing function H
+ * @param N Modulus used to get the pad length
+ * @param S The secret calculated by both sides
+ * @return
+ */
+ public static BigInteger CalculateKey(IDigest digest, BigInteger N, BigInteger S)
+ {
+ int padLength = (N.BitLength + 7) / 8;
+ byte[] _S = GetPadded(S, padLength);
+ digest.BlockUpdate(_S, 0, _S.Length);
+
+ byte[] output = new byte[digest.GetDigestSize()];
+ digest.DoFinal(output, 0);
+ return new BigInteger(1, output);
+ }
+
+ private static BigInteger HashPaddedTriplet(IDigest digest, BigInteger N, BigInteger n1, BigInteger n2, BigInteger n3)
+ {
+ int padLength = (N.BitLength + 7) / 8;
+
+ byte[] n1_bytes = GetPadded(n1, padLength);
+ byte[] n2_bytes = GetPadded(n2, padLength);
+ byte[] n3_bytes = GetPadded(n3, padLength);
+
+ digest.BlockUpdate(n1_bytes, 0, n1_bytes.Length);
+ digest.BlockUpdate(n2_bytes, 0, n2_bytes.Length);
+ digest.BlockUpdate(n3_bytes, 0, n3_bytes.Length);
+
+ byte[] output = new byte[digest.GetDigestSize()];
+ digest.DoFinal(output, 0);
+
+ return new BigInteger(1, output);
+ }
+
+ private static BigInteger HashPaddedPair(IDigest digest, BigInteger N, BigInteger n1, BigInteger n2)
+ {
+ int padLength = (N.BitLength + 7) / 8;
+
+ byte[] n1_bytes = GetPadded(n1, padLength);
+ byte[] n2_bytes = GetPadded(n2, padLength);
+
+ digest.BlockUpdate(n1_bytes, 0, n1_bytes.Length);
+ digest.BlockUpdate(n2_bytes, 0, n2_bytes.Length);
+
+ byte[] output = new byte[digest.GetDigestSize()];
+ digest.DoFinal(output, 0);
+
+ return new BigInteger(1, output);
+ }
+
+ private static byte[] GetPadded(BigInteger n, int length)
+ {
+ byte[] bs = BigIntegers.AsUnsignedByteArray(n);
+ if (bs.Length < length)
+ {
+ byte[] tmp = new byte[length];
+ Array.Copy(bs, 0, tmp, length - bs.Length, bs.Length);
+ bs = tmp;
+ }
+ return bs;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6Utilities.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6Utilities.cs.meta
new file mode 100644
index 00000000..5eca1e59
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6Utilities.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: f2d639deca700ab4ebd379e19bf15295
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6VerifierGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6VerifierGenerator.cs
new file mode 100644
index 00000000..f3eef55d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6VerifierGenerator.cs
@@ -0,0 +1,59 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement.Srp
+{
+ /**
+ * Generates new SRP verifier for user
+ */
+ public class Srp6VerifierGenerator
+ {
+ protected BigInteger N;
+ protected BigInteger g;
+ protected IDigest digest;
+
+ public Srp6VerifierGenerator()
+ {
+ }
+
+ /**
+ * Initialises generator to create new verifiers
+ * @param N The safe prime to use (see DHParametersGenerator)
+ * @param g The group parameter to use (see DHParametersGenerator)
+ * @param digest The digest to use. The same digest type will need to be used later for the actual authentication
+ * attempt. Also note that the final session key size is dependent on the chosen digest.
+ */
+ public virtual void Init(BigInteger N, BigInteger g, IDigest digest)
+ {
+ this.N = N;
+ this.g = g;
+ this.digest = digest;
+ }
+
+ public virtual void Init(Srp6GroupParameters group, IDigest digest)
+ {
+ Init(group.N, group.G, digest);
+ }
+
+ /**
+ * Creates a new SRP verifier
+ * @param salt The salt to use, generally should be large and random
+ * @param identity The user's identifying information (eg. username)
+ * @param password The user's password
+ * @return A new verifier for use in future SRP authentication
+ */
+ public virtual BigInteger GenerateVerifier(byte[] salt, byte[] identity, byte[] password)
+ {
+ BigInteger x = Srp6Utilities.CalculateX(digest, N, salt, identity, password);
+
+ return g.ModPow(x, N);
+ }
+ }
+}
+
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6VerifierGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6VerifierGenerator.cs.meta
new file mode 100644
index 00000000..027da287
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/agreement/srp/SRP6VerifierGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 2e48df3dca5d9954b9cad7406b784e1b
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/digests.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/digests.meta
new file mode 100644
index 00000000..07abf1fa
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/digests.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 1e980ab0e11551042aa0a47cac1b3062
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/digests/Blake2bDigest.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/digests/Blake2bDigest.cs
new file mode 100644
index 00000000..07c5717a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/digests/Blake2bDigest.cs
@@ -0,0 +1,535 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests
+{
+ /* The BLAKE2 cryptographic hash function was designed by Jean-
+ Philippe Aumasson, Samuel Neves, Zooko Wilcox-O'Hearn, and Christian
+ Winnerlein.
+
+ Reference Implementation and Description can be found at: https://blake2.net/
+ Internet Draft: https://tools.ietf.org/html/draft-saarinen-blake2-02
+
+ This implementation does not support the Tree Hashing Mode.
+
+ For unkeyed hashing, developers adapting BLAKE2 to ASN.1 - based
+ message formats SHOULD use the OID tree at x = 1.3.6.1.4.1.1722.12.2.
+
+ Algorithm | Target | Collision | Hash | Hash ASN.1 |
+ Identifier | Arch | Security | nn | OID Suffix |
+ ---------------+--------+-----------+------+------------+
+ id-blake2b160 | 64-bit | 2**80 | 20 | x.1.20 |
+ id-blake2b256 | 64-bit | 2**128 | 32 | x.1.32 |
+ id-blake2b384 | 64-bit | 2**192 | 48 | x.1.48 |
+ id-blake2b512 | 64-bit | 2**256 | 64 | x.1.64 |
+ ---------------+--------+-----------+------+------------+
+ */
+
+ /**
+ * Implementation of the cryptographic hash function Blakbe2b.
+ *
+ * Blake2b offers a built-in keying mechanism to be used directly
+ * for authentication ("Prefix-MAC") rather than a HMAC construction.
+ *
+ * Blake2b offers a built-in support for a salt for randomized hashing
+ * and a personal string for defining a unique hash function for each application.
+ *
+ * BLAKE2b is optimized for 64-bit platforms and produces digests of any size
+ * between 1 and 64 bytes.
+ */
+ public class Blake2bDigest
+ : IDigest
+ {
+ // Blake2b Initialization Vector:
+ private static readonly ulong[] blake2b_IV =
+ // Produced from the square root of primes 2, 3, 5, 7, 11, 13, 17, 19.
+ // The same as SHA-512 IV.
+ {
+ 0x6a09e667f3bcc908UL, 0xbb67ae8584caa73bUL, 0x3c6ef372fe94f82bUL,
+ 0xa54ff53a5f1d36f1UL, 0x510e527fade682d1UL, 0x9b05688c2b3e6c1fUL,
+ 0x1f83d9abfb41bd6bUL, 0x5be0cd19137e2179UL
+ };
+
+ // Message word permutations:
+ private static readonly byte[,] blake2b_sigma =
+ {
+ { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 },
+ { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 },
+ { 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 },
+ { 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 },
+ { 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 },
+ { 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 },
+ { 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 },
+ { 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 },
+ { 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 },
+ { 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 },
+ { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 },
+ { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }
+ };
+
+ private const int ROUNDS = 12; // to use for Catenas H'
+ private const int BLOCK_LENGTH_BYTES = 128;// bytes
+
+ // General parameters:
+ private int digestLength = 64; // 1- 64 bytes
+ private int keyLength = 0; // 0 - 64 bytes for keyed hashing for MAC
+ private byte[] salt = null;// new byte[16];
+ private byte[] personalization = null;// new byte[16];
+
+ // the key
+ private byte[] key = null;
+
+ // Tree hashing parameters:
+ // Because this class does not implement the Tree Hashing Mode,
+ // these parameters can be treated as constants (see init() function)
+ /*
+ * private int fanout = 1; // 0-255 private int depth = 1; // 1 - 255
+ * private int leafLength= 0; private long nodeOffset = 0L; private int
+ * nodeDepth = 0; private int innerHashLength = 0;
+ */
+
+ // whenever this buffer overflows, it will be processed
+ // in the Compress() function.
+ // For performance issues, long messages will not use this buffer.
+ private byte[] buffer = null;// new byte[BLOCK_LENGTH_BYTES];
+ // Position of last inserted byte:
+ private int bufferPos = 0;// a value from 0 up to 128
+
+ private ulong[] internalState = new ulong[16]; // In the Blake2b paper it is
+ // called: v
+ private ulong[] chainValue = null; // state vector, in the Blake2b paper it
+ // is called: h
+
+ private ulong t0 = 0UL; // holds last significant bits, counter (counts bytes)
+ private ulong t1 = 0UL; // counter: Length up to 2^128 are supported
+ private ulong f0 = 0UL; // finalization flag, for last block: ~0L
+
+ // For Tree Hashing Mode, not used here:
+ // private long f1 = 0L; // finalization flag, for last node: ~0L
+
+ public Blake2bDigest()
+ : this(512)
+ {
+ }
+
+ public Blake2bDigest(Blake2bDigest digest)
+ {
+ this.bufferPos = digest.bufferPos;
+ this.buffer = Arrays.Clone(digest.buffer);
+ this.keyLength = digest.keyLength;
+ this.key = Arrays.Clone(digest.key);
+ this.digestLength = digest.digestLength;
+ this.chainValue = Arrays.Clone(digest.chainValue);
+ this.personalization = Arrays.Clone(digest.personalization);
+ this.salt = Arrays.Clone(digest.salt);
+ this.t0 = digest.t0;
+ this.t1 = digest.t1;
+ this.f0 = digest.f0;
+ }
+
+ /**
+ * Basic sized constructor - size in bits.
+ *
+ * @param digestSize size of the digest in bits
+ */
+ public Blake2bDigest(int digestSize)
+ {
+ if (digestSize < 8 || digestSize > 512 || digestSize % 8 != 0)
+ throw new ArgumentException("BLAKE2b digest bit length must be a multiple of 8 and not greater than 512");
+
+ buffer = new byte[BLOCK_LENGTH_BYTES];
+ keyLength = 0;
+ this.digestLength = digestSize / 8;
+ Init();
+ }
+
+ /**
+ * Blake2b for authentication ("Prefix-MAC mode").
+ * After calling the doFinal() method, the key will
+ * remain to be used for further computations of
+ * this instance.
+ * The key can be overwritten using the clearKey() method.
+ *
+ * @param key A key up to 64 bytes or null
+ */
+ public Blake2bDigest(byte[] key)
+ {
+ buffer = new byte[BLOCK_LENGTH_BYTES];
+ if (key != null)
+ {
+ this.key = new byte[key.Length];
+ Array.Copy(key, 0, this.key, 0, key.Length);
+
+ if (key.Length > 64)
+ throw new ArgumentException("Keys > 64 are not supported");
+
+ keyLength = key.Length;
+ Array.Copy(key, 0, buffer, 0, key.Length);
+ bufferPos = BLOCK_LENGTH_BYTES; // zero padding
+ }
+ digestLength = 64;
+ Init();
+ }
+
+ /**
+ * Blake2b with key, required digest length (in bytes), salt and personalization.
+ * After calling the doFinal() method, the key, the salt and the personal string
+ * will remain and might be used for further computations with this instance.
+ * The key can be overwritten using the clearKey() method, the salt (pepper)
+ * can be overwritten using the clearSalt() method.
+ *
+ * @param key A key up to 64 bytes or null
+ * @param digestLength from 1 up to 64 bytes
+ * @param salt 16 bytes or null
+ * @param personalization 16 bytes or null
+ */
+ public Blake2bDigest(byte[] key, int digestLength, byte[] salt, byte[] personalization)
+ {
+ if (digestLength < 1 || digestLength > 64)
+ throw new ArgumentException("Invalid digest length (required: 1 - 64)");
+
+ this.digestLength = digestLength;
+ this.buffer = new byte[BLOCK_LENGTH_BYTES];
+
+ if (salt != null)
+ {
+ if (salt.Length != 16)
+ throw new ArgumentException("salt length must be exactly 16 bytes");
+
+ this.salt = new byte[16];
+ Array.Copy(salt, 0, this.salt, 0, salt.Length);
+ }
+ if (personalization != null)
+ {
+ if (personalization.Length != 16)
+ throw new ArgumentException("personalization length must be exactly 16 bytes");
+
+ this.personalization = new byte[16];
+ Array.Copy(personalization, 0, this.personalization, 0, personalization.Length);
+ }
+ if (key != null)
+ {
+ if (key.Length > 64)
+ throw new ArgumentException("Keys > 64 are not supported");
+
+ this.key = new byte[key.Length];
+ Array.Copy(key, 0, this.key, 0, key.Length);
+
+ keyLength = key.Length;
+ Array.Copy(key, 0, buffer, 0, key.Length);
+ bufferPos = BLOCK_LENGTH_BYTES; // zero padding
+ }
+ Init();
+ }
+
+ // initialize chainValue
+ private void Init()
+ {
+ if (chainValue == null)
+ {
+ chainValue = new ulong[8];
+
+ chainValue[0] = blake2b_IV[0] ^ (ulong)(digestLength | (keyLength << 8) | 0x1010000);
+
+ // 0x1010000 = ((fanout << 16) | (depth << 24) | (leafLength <<
+ // 32));
+ // with fanout = 1; depth = 0; leafLength = 0;
+ chainValue[1] = blake2b_IV[1];// ^ nodeOffset; with nodeOffset = 0;
+ chainValue[2] = blake2b_IV[2];// ^ ( nodeDepth | (innerHashLength << 8) );
+ // with nodeDepth = 0; innerHashLength = 0;
+
+ chainValue[3] = blake2b_IV[3];
+
+ chainValue[4] = blake2b_IV[4];
+ chainValue[5] = blake2b_IV[5];
+ if (salt != null)
+ {
+ chainValue[4] ^= Pack.LE_To_UInt64(salt, 0);
+ chainValue[5] ^= Pack.LE_To_UInt64(salt, 8);
+ }
+
+ chainValue[6] = blake2b_IV[6];
+ chainValue[7] = blake2b_IV[7];
+ if (personalization != null)
+ {
+ chainValue[6] ^= Pack.LE_To_UInt64(personalization, 0);
+ chainValue[7] ^= Pack.LE_To_UInt64(personalization, 8);
+ }
+ }
+ }
+
+ private void InitializeInternalState()
+ {
+ // initialize v:
+ Array.Copy(chainValue, 0, internalState, 0, chainValue.Length);
+ Array.Copy(blake2b_IV, 0, internalState, chainValue.Length, 4);
+ internalState[12] = t0 ^ blake2b_IV[4];
+ internalState[13] = t1 ^ blake2b_IV[5];
+ internalState[14] = f0 ^ blake2b_IV[6];
+ internalState[15] = blake2b_IV[7];// ^ f1 with f1 = 0
+ }
+
+ /**
+ * update the message digest with a single byte.
+ *
+ * @param b the input byte to be entered.
+ */
+ public virtual void Update(byte b)
+ {
+ int remainingLength = 0; // left bytes of buffer
+
+ // process the buffer if full else add to buffer:
+ remainingLength = BLOCK_LENGTH_BYTES - bufferPos;
+ if (remainingLength == 0)
+ { // full buffer
+ t0 += BLOCK_LENGTH_BYTES;
+ if (t0 == 0)
+ { // if message > 2^64
+ t1++;
+ }
+ Compress(buffer, 0);
+ Array.Clear(buffer, 0, buffer.Length);// clear buffer
+ buffer[0] = b;
+ bufferPos = 1;
+ }
+ else
+ {
+ buffer[bufferPos] = b;
+ bufferPos++;
+ return;
+ }
+ }
+
+ /**
+ * update the message digest with a block of bytes.
+ *
+ * @param message the byte array containing the data.
+ * @param offset the offset into the byte array where the data starts.
+ * @param len the length of the data.
+ */
+ public virtual void BlockUpdate(byte[] message, int offset, int len)
+ {
+ if (message == null || len == 0)
+ return;
+
+ int remainingLength = 0; // left bytes of buffer
+
+ if (bufferPos != 0)
+ { // commenced, incomplete buffer
+
+ // complete the buffer:
+ remainingLength = BLOCK_LENGTH_BYTES - bufferPos;
+ if (remainingLength < len)
+ { // full buffer + at least 1 byte
+ Array.Copy(message, offset, buffer, bufferPos,
+ remainingLength);
+ t0 += BLOCK_LENGTH_BYTES;
+ if (t0 == 0)
+ { // if message > 2^64
+ t1++;
+ }
+ Compress(buffer, 0);
+ bufferPos = 0;
+ Array.Clear(buffer, 0, buffer.Length);// clear buffer
+ }
+ else
+ {
+ Array.Copy(message, offset, buffer, bufferPos, len);
+ bufferPos += len;
+ return;
+ }
+ }
+
+ // process blocks except last block (also if last block is full)
+ int messagePos;
+ int blockWiseLastPos = offset + len - BLOCK_LENGTH_BYTES;
+ for (messagePos = offset + remainingLength; messagePos < blockWiseLastPos; messagePos += BLOCK_LENGTH_BYTES)
+ { // block wise 128 bytes
+ // without buffer:
+ t0 += BLOCK_LENGTH_BYTES;
+ if (t0 == 0)
+ {
+ t1++;
+ }
+ Compress(message, messagePos);
+ }
+
+ // fill the buffer with left bytes, this might be a full block
+ Array.Copy(message, messagePos, buffer, 0, offset + len
+ - messagePos);
+ bufferPos += offset + len - messagePos;
+ }
+
+ /**
+ * close the digest, producing the final digest value. The doFinal
+ * call leaves the digest reset.
+ * Key, salt and personal string remain.
+ *
+ * @param out the array the digest is to be copied into.
+ * @param outOffset the offset into the out array the digest is to start at.
+ */
+ public virtual int DoFinal(byte[] output, int outOffset)
+ {
+ f0 = 0xFFFFFFFFFFFFFFFFUL;
+ t0 += (ulong)bufferPos;
+ if (bufferPos > 0 && t0 == 0)
+ {
+ t1++;
+ }
+ Compress(buffer, 0);
+ Array.Clear(buffer, 0, buffer.Length);// Holds eventually the key if input is null
+ Array.Clear(internalState, 0, internalState.Length);
+
+ for (int i = 0; i < chainValue.Length && (i * 8 < digestLength); i++)
+ {
+ byte[] bytes = Pack.UInt64_To_LE(chainValue[i]);
+
+ if (i * 8 < digestLength - 8)
+ {
+ Array.Copy(bytes, 0, output, outOffset + i * 8, 8);
+ }
+ else
+ {
+ Array.Copy(bytes, 0, output, outOffset + i * 8, digestLength - (i * 8));
+ }
+ }
+
+ Array.Clear(chainValue, 0, chainValue.Length);
+
+ Reset();
+
+ return digestLength;
+ }
+
+ /**
+ * Reset the digest back to it's initial state.
+ * The key, the salt and the personal string will
+ * remain for further computations.
+ */
+ public virtual void Reset()
+ {
+ bufferPos = 0;
+ f0 = 0L;
+ t0 = 0L;
+ t1 = 0L;
+ chainValue = null;
+ Array.Clear(buffer, 0, buffer.Length);
+ if (key != null)
+ {
+ Array.Copy(key, 0, buffer, 0, key.Length);
+ bufferPos = BLOCK_LENGTH_BYTES; // zero padding
+ }
+ Init();
+ }
+
+ private void Compress(byte[] message, int messagePos)
+ {
+ InitializeInternalState();
+
+ ulong[] m = new ulong[16];
+ for (int j = 0; j < 16; j++)
+ {
+ m[j] = Pack.LE_To_UInt64(message, messagePos + j * 8);
+ }
+
+ for (int round = 0; round < ROUNDS; round++)
+ {
+ // G apply to columns of internalState:m[blake2b_sigma[round][2 * blockPos]] /+1
+ G(m[blake2b_sigma[round,0]], m[blake2b_sigma[round,1]], 0, 4, 8, 12);
+ G(m[blake2b_sigma[round,2]], m[blake2b_sigma[round,3]], 1, 5, 9, 13);
+ G(m[blake2b_sigma[round,4]], m[blake2b_sigma[round,5]], 2, 6, 10, 14);
+ G(m[blake2b_sigma[round,6]], m[blake2b_sigma[round,7]], 3, 7, 11, 15);
+ // G apply to diagonals of internalState:
+ G(m[blake2b_sigma[round,8]], m[blake2b_sigma[round,9]], 0, 5, 10, 15);
+ G(m[blake2b_sigma[round,10]], m[blake2b_sigma[round,11]], 1, 6, 11, 12);
+ G(m[blake2b_sigma[round,12]], m[blake2b_sigma[round,13]], 2, 7, 8, 13);
+ G(m[blake2b_sigma[round,14]], m[blake2b_sigma[round,15]], 3, 4, 9, 14);
+ }
+
+ // update chain values:
+ for (int offset = 0; offset < chainValue.Length; offset++)
+ {
+ chainValue[offset] = chainValue[offset] ^ internalState[offset] ^ internalState[offset + 8];
+ }
+ }
+
+ private void G(ulong m1, ulong m2, int posA, int posB, int posC, int posD)
+ {
+ internalState[posA] = internalState[posA] + internalState[posB] + m1;
+ internalState[posD] = Rotr64(internalState[posD] ^ internalState[posA], 32);
+ internalState[posC] = internalState[posC] + internalState[posD];
+ internalState[posB] = Rotr64(internalState[posB] ^ internalState[posC], 24); // replaces 25 of BLAKE
+ internalState[posA] = internalState[posA] + internalState[posB] + m2;
+ internalState[posD] = Rotr64(internalState[posD] ^ internalState[posA], 16);
+ internalState[posC] = internalState[posC] + internalState[posD];
+ internalState[posB] = Rotr64(internalState[posB] ^ internalState[posC], 63); // replaces 11 of BLAKE
+ }
+
+ private static ulong Rotr64(ulong x, int rot)
+ {
+ return x >> rot | x << -rot;
+ }
+
+ /**
+ * return the algorithm name
+ *
+ * @return the algorithm name
+ */
+ public virtual string AlgorithmName
+ {
+ get { return "BLAKE2b"; }
+ }
+
+ /**
+ * return the size, in bytes, of the digest produced by this message digest.
+ *
+ * @return the size, in bytes, of the digest produced by this message digest.
+ */
+ public virtual int GetDigestSize()
+ {
+ return digestLength;
+ }
+
+ /**
+ * Return the size in bytes of the internal buffer the digest applies it's compression
+ * function to.
+ *
+ * @return byte length of the digests internal buffer.
+ */
+ public virtual int GetByteLength()
+ {
+ return BLOCK_LENGTH_BYTES;
+ }
+
+ /**
+ * Overwrite the key
+ * if it is no longer used (zeroization)
+ */
+ public virtual void ClearKey()
+ {
+ if (key != null)
+ {
+ Array.Clear(key, 0, key.Length);
+ Array.Clear(buffer, 0, buffer.Length);
+ }
+ }
+
+ /**
+ * Overwrite the salt (pepper) if it
+ * is secret and no longer used (zeroization)
+ */
+ public virtual void ClearSalt()
+ {
+ if (salt != null)
+ {
+ Array.Clear(salt, 0, salt.Length);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/digests/Blake2bDigest.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/digests/Blake2bDigest.cs.meta
new file mode 100644
index 00000000..d6d97211
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/digests/Blake2bDigest.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a1380ac762da4394197da48540465160
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/digests/Blake2sDigest.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/digests/Blake2sDigest.cs
new file mode 100644
index 00000000..fb94488d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/digests/Blake2sDigest.cs
@@ -0,0 +1,555 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests
+{
+ /*
+ The BLAKE2 cryptographic hash function was designed by Jean-
+ Philippe Aumasson, Samuel Neves, Zooko Wilcox-O'Hearn, and Christian
+ Winnerlein.
+
+ Reference Implementation and Description can be found at: https://blake2.net/
+ RFC: https://tools.ietf.org/html/rfc7693
+
+ This implementation does not support the Tree Hashing Mode.
+
+ For unkeyed hashing, developers adapting BLAKE2 to ASN.1 - based
+ message formats SHOULD use the OID tree at x = 1.3.6.1.4.1.1722.12.2.
+
+ Algorithm | Target | Collision | Hash | Hash ASN.1 |
+ Identifier | Arch | Security | nn | OID Suffix |
+ ---------------+--------+-----------+------+------------+
+ id-blake2s128 | 32-bit | 2**64 | 16 | x.2.4 |
+ id-blake2s160 | 32-bit | 2**80 | 20 | x.2.5 |
+ id-blake2s224 | 32-bit | 2**112 | 28 | x.2.7 |
+ id-blake2s256 | 32-bit | 2**128 | 32 | x.2.8 |
+ ---------------+--------+-----------+------+------------+
+ */
+
+ /**
+ * Implementation of the cryptographic hash function BLAKE2s.
+ *
+ * The static property is checked during construction of the encoding object, it is set to
+ * true by default.
+ *
+ */
+ public static bool StrictLengthEnabled
+ {
+ get { return strictLengthEnabled[0]; }
+ set { strictLengthEnabled[0] = value; }
+ }
+
+ private static readonly bool[] strictLengthEnabled;
+
+ static Pkcs1Encoding()
+ {
+ string strictProperty = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetEnvironmentVariable(StrictLengthEnabledProperty);
+
+ strictLengthEnabled = new bool[]{ strictProperty == null || strictProperty.Equals("true")};
+ }
+
+
+ private SecureRandom random;
+ private IAsymmetricBlockCipher engine;
+ private bool forEncryption;
+ private bool forPrivateKey;
+ private bool useStrictLength;
+ private int pLen = -1;
+ private byte[] fallback = null;
+ private byte[] blockBuffer = null;
+
+ /**
+ * Basic constructor.
+ *
+ * @param cipher
+ */
+ public Pkcs1Encoding(
+ IAsymmetricBlockCipher cipher)
+ {
+ this.engine = cipher;
+ this.useStrictLength = StrictLengthEnabled;
+ }
+
+ /**
+ * Constructor for decryption with a fixed plaintext length.
+ *
+ * @param cipher The cipher to use for cryptographic operation.
+ * @param pLen Length of the expected plaintext.
+ */
+ public Pkcs1Encoding(IAsymmetricBlockCipher cipher, int pLen)
+ {
+ this.engine = cipher;
+ this.useStrictLength = StrictLengthEnabled;
+ this.pLen = pLen;
+ }
+
+ /**
+ * Constructor for decryption with a fixed plaintext length and a fallback
+ * value that is returned, if the padding is incorrect.
+ *
+ * @param cipher
+ * The cipher to use for cryptographic operation.
+ * @param fallback
+ * The fallback value, we don't to a arraycopy here.
+ */
+ public Pkcs1Encoding(IAsymmetricBlockCipher cipher, byte[] fallback)
+ {
+ this.engine = cipher;
+ this.useStrictLength = StrictLengthEnabled;
+ this.fallback = fallback;
+ this.pLen = fallback.Length;
+ }
+
+ public IAsymmetricBlockCipher GetUnderlyingCipher()
+ {
+ return engine;
+ }
+
+ public string AlgorithmName
+ {
+ get { return engine.AlgorithmName + "/PKCS1Padding"; }
+ }
+
+ public void Init(bool forEncryption, ICipherParameters parameters)
+ {
+ AsymmetricKeyParameter kParam;
+ if (parameters is ParametersWithRandom)
+ {
+ ParametersWithRandom rParam = (ParametersWithRandom)parameters;
+
+ this.random = rParam.Random;
+ kParam = (AsymmetricKeyParameter)rParam.Parameters;
+ }
+ else
+ {
+ this.random = new SecureRandom();
+ kParam = (AsymmetricKeyParameter)parameters;
+ }
+
+ engine.Init(forEncryption, parameters);
+
+ this.forPrivateKey = kParam.IsPrivate;
+ this.forEncryption = forEncryption;
+ this.blockBuffer = new byte[engine.GetOutputBlockSize()];
+
+ if (pLen > 0 && fallback == null && random == null)
+ throw new ArgumentException("encoder requires random");
+ }
+
+ public int GetInputBlockSize()
+ {
+ int baseBlockSize = engine.GetInputBlockSize();
+
+ return forEncryption
+ ? baseBlockSize - HeaderLength
+ : baseBlockSize;
+ }
+
+ public int GetOutputBlockSize()
+ {
+ int baseBlockSize = engine.GetOutputBlockSize();
+
+ return forEncryption
+ ? baseBlockSize
+ : baseBlockSize - HeaderLength;
+ }
+
+ public byte[] ProcessBlock(
+ byte[] input,
+ int inOff,
+ int length)
+ {
+ return forEncryption
+ ? EncodeBlock(input, inOff, length)
+ : DecodeBlock(input, inOff, length);
+ }
+
+ private byte[] EncodeBlock(
+ byte[] input,
+ int inOff,
+ int inLen)
+ {
+ if (inLen > GetInputBlockSize())
+ throw new ArgumentException("input data too large", "inLen");
+
+ byte[] block = new byte[engine.GetInputBlockSize()];
+
+ if (forPrivateKey)
+ {
+ block[0] = 0x01; // type code 1
+
+ for (int i = 1; i != block.Length - inLen - 1; i++)
+ {
+ block[i] = (byte)0xFF;
+ }
+ }
+ else
+ {
+ random.NextBytes(block); // random fill
+
+ block[0] = 0x02; // type code 2
+
+ //
+ // a zero byte marks the end of the padding, so all
+ // the pad bytes must be non-zero.
+ //
+ for (int i = 1; i != block.Length - inLen - 1; i++)
+ {
+ while (block[i] == 0)
+ {
+ block[i] = (byte)random.NextInt();
+ }
+ }
+ }
+
+ block[block.Length - inLen - 1] = 0x00; // mark the end of the padding
+ Array.Copy(input, inOff, block, block.Length - inLen, inLen);
+
+ return engine.ProcessBlock(block, 0, block.Length);
+ }
+
+ /**
+ * Checks if the argument is a correctly PKCS#1.5 encoded Plaintext
+ * for encryption.
+ *
+ * @param encoded The Plaintext.
+ * @param pLen Expected length of the plaintext.
+ * @return Either 0, if the encoding is correct, or -1, if it is incorrect.
+ */
+ private static int CheckPkcs1Encoding(byte[] encoded, int pLen)
+ {
+ int correct = 0;
+ /*
+ * Check if the first two bytes are 0 2
+ */
+ correct |= (encoded[0] ^ 2);
+
+ /*
+ * Now the padding check, check for no 0 byte in the padding
+ */
+ int plen = encoded.Length - (
+ pLen /* Lenght of the PMS */
+ + 1 /* Final 0-byte before PMS */
+ );
+
+ for (int i = 1; i < plen; i++)
+ {
+ int tmp = encoded[i];
+ tmp |= tmp >> 1;
+ tmp |= tmp >> 2;
+ tmp |= tmp >> 4;
+ correct |= (tmp & 1) - 1;
+ }
+
+ /*
+ * Make sure the padding ends with a 0 byte.
+ */
+ correct |= encoded[encoded.Length - (pLen + 1)];
+
+ /*
+ * Return 0 or 1, depending on the result.
+ */
+ correct |= correct >> 1;
+ correct |= correct >> 2;
+ correct |= correct >> 4;
+ return ~((correct & 1) - 1);
+ }
+
+ /**
+ * Decode PKCS#1.5 encoding, and return a random value if the padding is not correct.
+ *
+ * @param in The encrypted block.
+ * @param inOff Offset in the encrypted block.
+ * @param inLen Length of the encrypted block.
+ * @param pLen Length of the desired output.
+ * @return The plaintext without padding, or a random value if the padding was incorrect.
+ * @throws InvalidCipherTextException
+ */
+ private byte[] DecodeBlockOrRandom(byte[] input, int inOff, int inLen)
+ {
+ if (!forPrivateKey)
+ throw new InvalidCipherTextException("sorry, this method is only for decryption, not for signing");
+
+ byte[] block = engine.ProcessBlock(input, inOff, inLen);
+ byte[] random;
+ if (this.fallback == null)
+ {
+ random = new byte[this.pLen];
+ this.random.NextBytes(random);
+ }
+ else
+ {
+ random = fallback;
+ }
+
+ byte[] data = (useStrictLength & (block.Length != engine.GetOutputBlockSize())) ? blockBuffer : block;
+
+ /*
+ * Check the padding.
+ */
+ int correct = CheckPkcs1Encoding(data, this.pLen);
+
+ /*
+ * Now, to a constant time constant memory copy of the decrypted value
+ * or the random value, depending on the validity of the padding.
+ */
+ byte[] result = new byte[this.pLen];
+ for (int i = 0; i < this.pLen; i++)
+ {
+ result[i] = (byte)((data[i + (data.Length - pLen)] & (~correct)) | (random[i] & correct));
+ }
+
+ Arrays.Fill(data, 0);
+
+ return result;
+ }
+
+ /**
+ * @exception InvalidCipherTextException if the decrypted block is not in Pkcs1 format.
+ */
+ private byte[] DecodeBlock(
+ byte[] input,
+ int inOff,
+ int inLen)
+ {
+ /*
+ * If the length of the expected plaintext is known, we use a constant-time decryption.
+ * If the decryption fails, we return a random value.
+ */
+ if (this.pLen != -1)
+ {
+ return this.DecodeBlockOrRandom(input, inOff, inLen);
+ }
+
+ byte[] block = engine.ProcessBlock(input, inOff, inLen);
+ bool incorrectLength = (useStrictLength & (block.Length != engine.GetOutputBlockSize()));
+
+ byte[] data;
+ if (block.Length < GetOutputBlockSize())
+ {
+ data = blockBuffer;
+ }
+ else
+ {
+ data = block;
+ }
+
+ byte expectedType = (byte)(forPrivateKey ? 2 : 1);
+ byte type = data[0];
+
+ bool badType = (type != expectedType);
+
+ //
+ // find and extract the message block.
+ //
+ int start = FindStart(type, data);
+
+ start++; // data should start at the next byte
+
+ if (badType | (start < HeaderLength))
+ {
+ Arrays.Fill(data, 0);
+ throw new InvalidCipherTextException("block incorrect");
+ }
+
+ // if we get this far, it's likely to be a genuine encoding error
+ if (incorrectLength)
+ {
+ Arrays.Fill(data, 0);
+ throw new InvalidCipherTextException("block incorrect size");
+ }
+
+ byte[] result = new byte[data.Length - start];
+
+ Array.Copy(data, start, result, 0, result.Length);
+
+ return result;
+ }
+
+ private int FindStart(byte type, byte[] block)
+ {
+ int start = -1;
+ bool padErr = false;
+
+ for (int i = 1; i != block.Length; i++)
+ {
+ byte pad = block[i];
+
+ if (pad == 0 & start < 0)
+ {
+ start = i;
+ }
+ padErr |= ((type == 1) & (start < 0) & (pad != (byte)0xff));
+ }
+
+ return padErr ? -1 : start;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/encodings/Pkcs1Encoding.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/encodings/Pkcs1Encoding.cs.meta
new file mode 100644
index 00000000..17ace7b4
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/encodings/Pkcs1Encoding.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 5b1316d7c7c9dbc42b6ed758a5b1e70e
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines.meta
new file mode 100644
index 00000000..88ed5db0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 7b265757931cf134392d9b1ab2925c86
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/AesEngine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/AesEngine.cs
new file mode 100644
index 00000000..0fbcb21c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/AesEngine.cs
@@ -0,0 +1,614 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Diagnostics;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ /**
+ * an implementation of the AES (Rijndael), from FIPS-197.
+ *
+ * For further details see: http://csrc.nist.gov/encryption/aes/.
+ *
+ * This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at
+ * http://fp.gladman.plus.com/cryptography_technology/rijndael/
+ *
+ * There are three levels of tradeoff of speed vs memory
+ * Because java has no preprocessor, they are written as three separate classes from which to choose
+ *
+ * The fastest uses 8Kbytes of static tables to precompute round calculations, 4 256 word tables for encryption
+ * and 4 for decryption.
+ *
+ * The middle performance version uses only one 256 word table for each, for a total of 2Kbytes,
+ * adding 12 rotate operations per round to compute the values contained in the other tables from
+ * the contents of the first.
+ *
+ * The slowest version uses no static tables at all and computes the values in each round.
+ *
+ *
+ * This file contains the middle performance version with 2Kbytes of static tables for round precomputation.
+ *
+ * For further details see: http://csrc.nist.gov/encryption/aes/.
+ *
+ * This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at
+ * http://fp.gladman.plus.com/cryptography_technology/rijndael/
+ *
+ * There are three levels of tradeoff of speed vs memory
+ * Because java has no preprocessor), they are written as three separate classes from which to choose
+ *
+ * The fastest uses 8Kbytes of static tables to precompute round calculations), 4 256 word tables for encryption
+ * and 4 for decryption.
+ *
+ * The middle performance version uses only one 256 word table for each), for a total of 2Kbytes),
+ * adding 12 rotate operations per round to compute the values contained in the other tables from
+ * the contents of the first
+ *
+ * The slowest version uses no static tables at all and computes the values in each round
+ *
+ *
+ * This file contains the fast version with 8Kbytes of static tables for round precomputation
+ *
+ * For further details see: http://csrc.nist.gov/encryption/aes/.
+ *
+ * This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at
+ * http://fp.gladman.plus.com/cryptography_technology/rijndael/
+ *
+ * There are three levels of tradeoff of speed vs memory
+ * Because java has no preprocessor, they are written as three separate classes from which to choose
+ *
+ * The fastest uses 8Kbytes of static tables to precompute round calculations, 4 256 word tables for encryption
+ * and 4 for decryption.
+ *
+ * The middle performance version uses only one 256 word table for each, for a total of 2Kbytes,
+ * adding 12 rotate operations per round to compute the values contained in the other tables from
+ * the contents of the first
+ *
+ * The slowest version uses no static tables at all and computes the values
+ * in each round.
+ *
+ *
+ * This file contains the slowest performance version with no static tables
+ * for round precomputation, but it has the smallest foot print.
+ *
this is based on a draft, and as such is subject to change - don't use this class for anything requiring long term storage.
+ *
if you are using this to wrap triple-des keys you need to set the
+ * parity bits on the key and, if it's a two-key triple-des key, pad it
+ * yourself.
+ * It is a third phase candidate in the eStream contest, and is patent-free.
+ * No attacks are known as of today (April 2007). See
+ *
+ * http://www.ecrypt.eu.org/stream/hcp3.html
+ *
+ */
+ public class HC128Engine
+ : IStreamCipher
+ {
+ private uint[] p = new uint[512];
+ private uint[] q = new uint[512];
+ private uint cnt = 0;
+
+ private static uint F1(uint x)
+ {
+ return RotateRight(x, 7) ^ RotateRight(x, 18) ^ (x >> 3);
+ }
+
+ private static uint F2(uint x)
+ {
+ return RotateRight(x, 17) ^ RotateRight(x, 19) ^ (x >> 10);
+ }
+
+ private uint G1(uint x, uint y, uint z)
+ {
+ return (RotateRight(x, 10) ^ RotateRight(z, 23)) + RotateRight(y, 8);
+ }
+
+ private uint G2(uint x, uint y, uint z)
+ {
+ return (RotateLeft(x, 10) ^ RotateLeft(z, 23)) + RotateLeft(y, 8);
+ }
+
+ private static uint RotateLeft(uint x, int bits)
+ {
+ return (x << bits) | (x >> -bits);
+ }
+
+ private static uint RotateRight(uint x, int bits)
+ {
+ return (x >> bits) | (x << -bits);
+ }
+
+ private uint H1(uint x)
+ {
+ return q[x & 0xFF] + q[((x >> 16) & 0xFF) + 256];
+ }
+
+ private uint H2(uint x)
+ {
+ return p[x & 0xFF] + p[((x >> 16) & 0xFF) + 256];
+ }
+
+ private static uint Mod1024(uint x)
+ {
+ return x & 0x3FF;
+ }
+
+ private static uint Mod512(uint x)
+ {
+ return x & 0x1FF;
+ }
+
+ private static uint Dim(uint x, uint y)
+ {
+ return Mod512(x - y);
+ }
+
+ private uint Step()
+ {
+ uint j = Mod512(cnt);
+ uint ret;
+ if (cnt < 512)
+ {
+ p[j] += G1(p[Dim(j, 3)], p[Dim(j, 10)], p[Dim(j, 511)]);
+ ret = H1(p[Dim(j, 12)]) ^ p[j];
+ }
+ else
+ {
+ q[j] += G2(q[Dim(j, 3)], q[Dim(j, 10)], q[Dim(j, 511)]);
+ ret = H2(q[Dim(j, 12)]) ^ q[j];
+ }
+ cnt = Mod1024(cnt + 1);
+ return ret;
+ }
+
+ private byte[] key, iv;
+ private bool initialised;
+
+ private void Init()
+ {
+ if (key.Length != 16)
+ throw new ArgumentException("The key must be 128 bits long");
+
+ idx = 0;
+ cnt = 0;
+
+ uint[] w = new uint[1280];
+
+ for (int i = 0; i < 16; i++)
+ {
+ w[i >> 2] |= ((uint)key[i] << (8 * (i & 0x3)));
+ }
+ Array.Copy(w, 0, w, 4, 4);
+
+ for (int i = 0; i < iv.Length && i < 16; i++)
+ {
+ w[(i >> 2) + 8] |= ((uint)iv[i] << (8 * (i & 0x3)));
+ }
+ Array.Copy(w, 8, w, 12, 4);
+
+ for (uint i = 16; i < 1280; i++)
+ {
+ w[i] = F2(w[i - 2]) + w[i - 7] + F1(w[i - 15]) + w[i - 16] + i;
+ }
+
+ Array.Copy(w, 256, p, 0, 512);
+ Array.Copy(w, 768, q, 0, 512);
+
+ for (int i = 0; i < 512; i++)
+ {
+ p[i] = Step();
+ }
+ for (int i = 0; i < 512; i++)
+ {
+ q[i] = Step();
+ }
+
+ cnt = 0;
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "HC-128"; }
+ }
+
+ /**
+ * Initialise a HC-128 cipher.
+ *
+ * @param forEncryption whether or not we are for encryption. Irrelevant, as
+ * encryption and decryption are the same.
+ * @param params the parameters required to set up the cipher.
+ * @throws ArgumentException if the params argument is
+ * inappropriate (ie. the key is not 128 bit long).
+ */
+ public virtual void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ ICipherParameters keyParam = parameters;
+
+ if (parameters is ParametersWithIV)
+ {
+ iv = ((ParametersWithIV)parameters).GetIV();
+ keyParam = ((ParametersWithIV)parameters).Parameters;
+ }
+ else
+ {
+ iv = new byte[0];
+ }
+
+ if (keyParam is KeyParameter)
+ {
+ key = ((KeyParameter)keyParam).GetKey();
+ Init();
+ }
+ else
+ {
+ throw new ArgumentException(
+ "Invalid parameter passed to HC128 init - " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters),
+ "parameters");
+ }
+
+ initialised = true;
+ }
+
+ private byte[] buf = new byte[4];
+ private int idx = 0;
+
+ private byte GetByte()
+ {
+ if (idx == 0)
+ {
+ Pack.UInt32_To_LE(Step(), buf);
+ }
+ byte ret = buf[idx];
+ idx = idx + 1 & 0x3;
+ return ret;
+ }
+
+ public virtual void ProcessBytes(
+ byte[] input,
+ int inOff,
+ int len,
+ byte[] output,
+ int outOff)
+ {
+ if (!initialised)
+ throw new InvalidOperationException(AlgorithmName + " not initialised");
+
+ Check.DataLength(input, inOff, len, "input buffer too short");
+ Check.OutputLength(output, outOff, len, "output buffer too short");
+
+ for (int i = 0; i < len; i++)
+ {
+ output[outOff + i] = (byte)(input[inOff + i] ^ GetByte());
+ }
+ }
+
+ public virtual void Reset()
+ {
+ Init();
+ }
+
+ public virtual byte ReturnByte(byte input)
+ {
+ return (byte)(input ^ GetByte());
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/HC128Engine.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/HC128Engine.cs.meta
new file mode 100644
index 00000000..0bdf95a6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/HC128Engine.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 181b21bf264bc414aa9f03db25c3431d
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/HC256Engine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/HC256Engine.cs
new file mode 100644
index 00000000..bd709732
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/HC256Engine.cs
@@ -0,0 +1,228 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ /**
+ * HC-256 is a software-efficient stream cipher created by Hongjun Wu. It
+ * generates keystream from a 256-bit secret key and a 256-bit initialization
+ * vector.
+ *
+ * Its brother, HC-128, is a third phase candidate in the eStream contest.
+ * The algorithm is patent-free. No attacks are known as of today (April 2007).
+ * See
+ *
+ * http://www.ecrypt.eu.org/stream/hcp3.html
+ *
+ */
+ public class HC256Engine
+ : IStreamCipher
+ {
+ private uint[] p = new uint[1024];
+ private uint[] q = new uint[1024];
+ private uint cnt = 0;
+
+ private uint Step()
+ {
+ uint j = cnt & 0x3FF;
+ uint ret;
+ if (cnt < 1024)
+ {
+ uint x = p[(j - 3 & 0x3FF)];
+ uint y = p[(j - 1023 & 0x3FF)];
+ p[j] += p[(j - 10 & 0x3FF)]
+ + (RotateRight(x, 10) ^ RotateRight(y, 23))
+ + q[((x ^ y) & 0x3FF)];
+
+ x = p[(j - 12 & 0x3FF)];
+ ret = (q[x & 0xFF] + q[((x >> 8) & 0xFF) + 256]
+ + q[((x >> 16) & 0xFF) + 512] + q[((x >> 24) & 0xFF) + 768])
+ ^ p[j];
+ }
+ else
+ {
+ uint x = q[(j - 3 & 0x3FF)];
+ uint y = q[(j - 1023 & 0x3FF)];
+ q[j] += q[(j - 10 & 0x3FF)]
+ + (RotateRight(x, 10) ^ RotateRight(y, 23))
+ + p[((x ^ y) & 0x3FF)];
+
+ x = q[(j - 12 & 0x3FF)];
+ ret = (p[x & 0xFF] + p[((x >> 8) & 0xFF) + 256]
+ + p[((x >> 16) & 0xFF) + 512] + p[((x >> 24) & 0xFF) + 768])
+ ^ q[j];
+ }
+ cnt = cnt + 1 & 0x7FF;
+ return ret;
+ }
+
+ private byte[] key, iv;
+ private bool initialised;
+
+ private void Init()
+ {
+ if (key.Length != 32 && key.Length != 16)
+ throw new ArgumentException("The key must be 128/256 bits long");
+
+ if (iv.Length < 16)
+ throw new ArgumentException("The IV must be at least 128 bits long");
+
+ if (key.Length != 32)
+ {
+ byte[] k = new byte[32];
+
+ Array.Copy(key, 0, k, 0, key.Length);
+ Array.Copy(key, 0, k, 16, key.Length);
+
+ key = k;
+ }
+
+ if (iv.Length < 32)
+ {
+ byte[] newIV = new byte[32];
+
+ Array.Copy(iv, 0, newIV, 0, iv.Length);
+ Array.Copy(iv, 0, newIV, iv.Length, newIV.Length - iv.Length);
+
+ iv = newIV;
+ }
+
+ idx = 0;
+ cnt = 0;
+
+ uint[] w = new uint[2560];
+
+ for (int i = 0; i < 32; i++)
+ {
+ w[i >> 2] |= ((uint)key[i] << (8 * (i & 0x3)));
+ }
+
+ for (int i = 0; i < 32; i++)
+ {
+ w[(i >> 2) + 8] |= ((uint)iv[i] << (8 * (i & 0x3)));
+ }
+
+ for (uint i = 16; i < 2560; i++)
+ {
+ uint x = w[i - 2];
+ uint y = w[i - 15];
+ w[i] = (RotateRight(x, 17) ^ RotateRight(x, 19) ^ (x >> 10))
+ + w[i - 7]
+ + (RotateRight(y, 7) ^ RotateRight(y, 18) ^ (y >> 3))
+ + w[i - 16] + i;
+ }
+
+ Array.Copy(w, 512, p, 0, 1024);
+ Array.Copy(w, 1536, q, 0, 1024);
+
+ for (int i = 0; i < 4096; i++)
+ {
+ Step();
+ }
+
+ cnt = 0;
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "HC-256"; }
+ }
+
+ /**
+ * Initialise a HC-256 cipher.
+ *
+ * @param forEncryption whether or not we are for encryption. Irrelevant, as
+ * encryption and decryption are the same.
+ * @param params the parameters required to set up the cipher.
+ * @throws ArgumentException if the params argument is
+ * inappropriate (ie. the key is not 256 bit long).
+ */
+ public virtual void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ ICipherParameters keyParam = parameters;
+
+ if (parameters is ParametersWithIV)
+ {
+ iv = ((ParametersWithIV)parameters).GetIV();
+ keyParam = ((ParametersWithIV)parameters).Parameters;
+ }
+ else
+ {
+ iv = new byte[0];
+ }
+
+ if (keyParam is KeyParameter)
+ {
+ key = ((KeyParameter)keyParam).GetKey();
+ Init();
+ }
+ else
+ {
+ throw new ArgumentException(
+ "Invalid parameter passed to HC256 init - " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters),
+ "parameters");
+ }
+
+ initialised = true;
+ }
+
+ private byte[] buf = new byte[4];
+ private int idx = 0;
+
+ private byte GetByte()
+ {
+ if (idx == 0)
+ {
+ Pack.UInt32_To_LE(Step(), buf);
+ }
+ byte ret = buf[idx];
+ idx = idx + 1 & 0x3;
+ return ret;
+ }
+
+ public virtual void ProcessBytes(
+ byte[] input,
+ int inOff,
+ int len,
+ byte[] output,
+ int outOff)
+ {
+ if (!initialised)
+ throw new InvalidOperationException(AlgorithmName + " not initialised");
+
+ Check.DataLength(input, inOff, len, "input buffer too short");
+ Check.OutputLength(output, outOff, len, "output buffer too short");
+
+ for (int i = 0; i < len; i++)
+ {
+ output[outOff + i] = (byte)(input[inOff + i] ^ GetByte());
+ }
+ }
+
+ public virtual void Reset()
+ {
+ Init();
+ }
+
+ public virtual byte ReturnByte(byte input)
+ {
+ return (byte)(input ^ GetByte());
+ }
+
+ private static uint RotateRight(uint x, int bits)
+ {
+ return (x >> bits) | (x << -bits);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/HC256Engine.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/HC256Engine.cs.meta
new file mode 100644
index 00000000..68bee56a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/HC256Engine.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a97c4e05480602c42b965ee80fd861b8
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/ISAACEngine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/ISAACEngine.cs
new file mode 100644
index 00000000..261318fb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/ISAACEngine.cs
@@ -0,0 +1,216 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ /**
+ * Implementation of Bob Jenkin's ISAAC (Indirection Shift Accumulate Add and Count).
+ * see: http://www.burtleburtle.net/bob/rand/isaacafa.html
+ */
+ public class IsaacEngine
+ : IStreamCipher
+ {
+ // Constants
+ private static readonly int sizeL = 8,
+ stateArraySize = sizeL<<5; // 256
+
+ // Cipher's internal state
+ private uint[] engineState = null, // mm
+ results = null; // randrsl
+ private uint a = 0, b = 0, c = 0;
+
+ // Engine state
+ private int index = 0;
+ private byte[] keyStream = new byte[stateArraySize<<2], // results expanded into bytes
+ workingKey = null;
+ private bool initialised = false;
+
+ /**
+ * initialise an ISAAC cipher.
+ *
+ * @param forEncryption whether or not we are for encryption.
+ * @param params the parameters required to set up the cipher.
+ * @exception ArgumentException if the params argument is
+ * inappropriate.
+ */
+ public virtual void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ if (!(parameters is KeyParameter))
+ throw new ArgumentException(
+ "invalid parameter passed to ISAAC Init - " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters),
+ "parameters");
+
+ /*
+ * ISAAC encryption and decryption is completely
+ * symmetrical, so the 'forEncryption' is
+ * irrelevant.
+ */
+ KeyParameter p = (KeyParameter) parameters;
+ setKey(p.GetKey());
+ }
+
+ public virtual byte ReturnByte(
+ byte input)
+ {
+ if (index == 0)
+ {
+ isaac();
+ keyStream = Pack.UInt32_To_BE(results);
+ }
+
+ byte output = (byte)(keyStream[index]^input);
+ index = (index + 1) & 1023;
+
+ return output;
+ }
+
+ public virtual void ProcessBytes(
+ byte[] input,
+ int inOff,
+ int len,
+ byte[] output,
+ int outOff)
+ {
+ if (!initialised)
+ throw new InvalidOperationException(AlgorithmName + " not initialised");
+
+ Check.DataLength(input, inOff, len, "input buffer too short");
+ Check.OutputLength(output, outOff, len, "output buffer too short");
+
+ for (int i = 0; i < len; i++)
+ {
+ if (index == 0)
+ {
+ isaac();
+ keyStream = Pack.UInt32_To_BE(results);
+ }
+ output[i+outOff] = (byte)(keyStream[index]^input[i+inOff]);
+ index = (index + 1) & 1023;
+ }
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "ISAAC"; }
+ }
+
+ public virtual void Reset()
+ {
+ setKey(workingKey);
+ }
+
+ // Private implementation
+ private void setKey(
+ byte[] keyBytes)
+ {
+ workingKey = keyBytes;
+
+ if (engineState == null)
+ {
+ engineState = new uint[stateArraySize];
+ }
+
+ if (results == null)
+ {
+ results = new uint[stateArraySize];
+ }
+
+ int i, j, k;
+
+ // Reset state
+ for (i = 0; i < stateArraySize; i++)
+ {
+ engineState[i] = results[i] = 0;
+ }
+ a = b = c = 0;
+
+ // Reset index counter for output
+ index = 0;
+
+ // Convert the key bytes to ints and put them into results[] for initialization
+ byte[] t = new byte[keyBytes.Length + (keyBytes.Length & 3)];
+ Array.Copy(keyBytes, 0, t, 0, keyBytes.Length);
+ for (i = 0; i < t.Length; i+=4)
+ {
+ results[i >> 2] = Pack.LE_To_UInt32(t, i);
+ }
+
+ // It has begun?
+ uint[] abcdefgh = new uint[sizeL];
+
+ for (i = 0; i < sizeL; i++)
+ {
+ abcdefgh[i] = 0x9e3779b9; // Phi (golden ratio)
+ }
+
+ for (i = 0; i < 4; i++)
+ {
+ mix(abcdefgh);
+ }
+
+ for (i = 0; i < 2; i++)
+ {
+ for (j = 0; j < stateArraySize; j+=sizeL)
+ {
+ for (k = 0; k < sizeL; k++)
+ {
+ abcdefgh[k] += (i<1) ? results[j+k] : engineState[j+k];
+ }
+
+ mix(abcdefgh);
+
+ for (k = 0; k < sizeL; k++)
+ {
+ engineState[j+k] = abcdefgh[k];
+ }
+ }
+ }
+
+ isaac();
+
+ initialised = true;
+ }
+
+ private void isaac()
+ {
+ uint x, y;
+
+ b += ++c;
+ for (int i = 0; i < stateArraySize; i++)
+ {
+ x = engineState[i];
+ switch (i & 3)
+ {
+ case 0: a ^= (a << 13); break;
+ case 1: a ^= (a >> 6); break;
+ case 2: a ^= (a << 2); break;
+ case 3: a ^= (a >> 16); break;
+ }
+ a += engineState[(i+128) & 0xFF];
+ engineState[i] = y = engineState[(int)((uint)x >> 2) & 0xFF] + a + b;
+ results[i] = b = engineState[(int)((uint)y >> 10) & 0xFF] + x;
+ }
+ }
+
+ private void mix(uint[] x)
+ {
+ x[0]^=x[1]<< 11; x[3]+=x[0]; x[1]+=x[2];
+ x[1]^=x[2]>> 2; x[4]+=x[1]; x[2]+=x[3];
+ x[2]^=x[3]<< 8; x[5]+=x[2]; x[3]+=x[4];
+ x[3]^=x[4]>> 16; x[6]+=x[3]; x[4]+=x[5];
+ x[4]^=x[5]<< 10; x[7]+=x[4]; x[5]+=x[6];
+ x[5]^=x[6]>> 4; x[0]+=x[5]; x[6]+=x[7];
+ x[6]^=x[7]<< 8; x[1]+=x[6]; x[7]+=x[0];
+ x[7]^=x[0]>> 9; x[2]+=x[7]; x[0]+=x[1];
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/ISAACEngine.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/ISAACEngine.cs.meta
new file mode 100644
index 00000000..4190ef6b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/ISAACEngine.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 7564107a47479e74b800f239f1636fad
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/IdeaEngine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/IdeaEngine.cs
new file mode 100644
index 00000000..1cf97080
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/IdeaEngine.cs
@@ -0,0 +1,326 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ /**
+ * A class that provides a basic International Data Encryption Algorithm (IDEA) engine.
+ *
+ * This implementation is based on the "HOWTO: INTERNATIONAL DATA ENCRYPTION ALGORITHM"
+ * implementation summary by Fauzan Mirza (F.U.Mirza@sheffield.ac.uk). (barring 1 typo at the
+ * end of the MulInv function!).
+ *
+ *
+ * It can be found at ftp://ftp.funet.fi/pub/crypt/cryptography/symmetric/idea/
+ *
+ *
+ * Note: This algorithm was patented in the USA, Japan and Europe. These patents expired in 2011/2012.
+ *
+ */
+ public class IdeaEngine
+ : IBlockCipher
+ {
+ private const int BLOCK_SIZE = 8;
+ private int[] workingKey;
+ /**
+ * standard constructor.
+ */
+ public IdeaEngine()
+ {
+ }
+ /**
+ * initialise an IDEA cipher.
+ *
+ * @param forEncryption whether or not we are for encryption.
+ * @param parameters the parameters required to set up the cipher.
+ * @exception ArgumentException if the parameters argument is
+ * inappropriate.
+ */
+ public virtual void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ if (!(parameters is KeyParameter))
+ throw new ArgumentException("invalid parameter passed to IDEA init - " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters));
+
+ workingKey = GenerateWorkingKey(forEncryption,
+ ((KeyParameter)parameters).GetKey());
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "IDEA"; }
+ }
+
+ public virtual bool IsPartialBlockOkay
+ {
+ get { return false; }
+ }
+
+ public virtual int GetBlockSize()
+ {
+ return BLOCK_SIZE;
+ }
+
+ public virtual int ProcessBlock(
+ byte[] input,
+ int inOff,
+ byte[] output,
+ int outOff)
+ {
+ if (workingKey == null)
+ throw new InvalidOperationException("IDEA engine not initialised");
+
+ Check.DataLength(input, inOff, BLOCK_SIZE, "input buffer too short");
+ Check.OutputLength(output, outOff, BLOCK_SIZE, "output buffer too short");
+
+ IdeaFunc(workingKey, input, inOff, output, outOff);
+ return BLOCK_SIZE;
+ }
+ public virtual void Reset()
+ {
+ }
+ private static readonly int MASK = 0xffff;
+ private static readonly int BASE = 0x10001;
+ private int BytesToWord(
+ byte[] input,
+ int inOff)
+ {
+ return ((input[inOff] << 8) & 0xff00) + (input[inOff + 1] & 0xff);
+ }
+ private void WordToBytes(
+ int word,
+ byte[] outBytes,
+ int outOff)
+ {
+ outBytes[outOff] = (byte)((uint) word >> 8);
+ outBytes[outOff + 1] = (byte)word;
+ }
+ /**
+ * return x = x * y where the multiplication is done modulo
+ * 65537 (0x10001) (as defined in the IDEA specification) and
+ * a zero input is taken to be 65536 (0x10000).
+ *
+ * @param x the x value
+ * @param y the y value
+ * @return x = x * y
+ */
+ private int Mul(
+ int x,
+ int y)
+ {
+ if (x == 0)
+ {
+ x = (BASE - y);
+ }
+ else if (y == 0)
+ {
+ x = (BASE - x);
+ }
+ else
+ {
+ int p = x * y;
+ y = p & MASK;
+ x = (int) ((uint) p >> 16);
+ x = y - x + ((y < x) ? 1 : 0);
+ }
+ return x & MASK;
+ }
+ private void IdeaFunc(
+ int[] workingKey,
+ byte[] input,
+ int inOff,
+ byte[] outBytes,
+ int outOff)
+ {
+ int x0, x1, x2, x3, t0, t1;
+ int keyOff = 0;
+ x0 = BytesToWord(input, inOff);
+ x1 = BytesToWord(input, inOff + 2);
+ x2 = BytesToWord(input, inOff + 4);
+ x3 = BytesToWord(input, inOff + 6);
+ for (int round = 0; round < 8; round++)
+ {
+ x0 = Mul(x0, workingKey[keyOff++]);
+ x1 += workingKey[keyOff++];
+ x1 &= MASK;
+ x2 += workingKey[keyOff++];
+ x2 &= MASK;
+ x3 = Mul(x3, workingKey[keyOff++]);
+ t0 = x1;
+ t1 = x2;
+ x2 ^= x0;
+ x1 ^= x3;
+ x2 = Mul(x2, workingKey[keyOff++]);
+ x1 += x2;
+ x1 &= MASK;
+ x1 = Mul(x1, workingKey[keyOff++]);
+ x2 += x1;
+ x2 &= MASK;
+ x0 ^= x1;
+ x3 ^= x2;
+ x1 ^= t1;
+ x2 ^= t0;
+ }
+ WordToBytes(Mul(x0, workingKey[keyOff++]), outBytes, outOff);
+ WordToBytes(x2 + workingKey[keyOff++], outBytes, outOff + 2); /* NB: Order */
+ WordToBytes(x1 + workingKey[keyOff++], outBytes, outOff + 4);
+ WordToBytes(Mul(x3, workingKey[keyOff]), outBytes, outOff + 6);
+ }
+ /**
+ * The following function is used to expand the user key to the encryption
+ * subkey. The first 16 bytes are the user key, and the rest of the subkey
+ * is calculated by rotating the previous 16 bytes by 25 bits to the left,
+ * and so on until the subkey is completed.
+ */
+ private int[] ExpandKey(
+ byte[] uKey)
+ {
+ int[] key = new int[52];
+ if (uKey.Length < 16)
+ {
+ byte[] tmp = new byte[16];
+ Array.Copy(uKey, 0, tmp, tmp.Length - uKey.Length, uKey.Length);
+ uKey = tmp;
+ }
+ for (int i = 0; i < 8; i++)
+ {
+ key[i] = BytesToWord(uKey, i * 2);
+ }
+ for (int i = 8; i < 52; i++)
+ {
+ if ((i & 7) < 6)
+ {
+ key[i] = ((key[i - 7] & 127) << 9 | key[i - 6] >> 7) & MASK;
+ }
+ else if ((i & 7) == 6)
+ {
+ key[i] = ((key[i - 7] & 127) << 9 | key[i - 14] >> 7) & MASK;
+ }
+ else
+ {
+ key[i] = ((key[i - 15] & 127) << 9 | key[i - 14] >> 7) & MASK;
+ }
+ }
+ return key;
+ }
+ /**
+ * This function computes multiplicative inverse using Euclid's Greatest
+ * Common Divisor algorithm. Zero and one are self inverse.
+ *
+ * i.e. x * MulInv(x) == 1 (modulo BASE)
+ *
+ */
+ private int MulInv(
+ int x)
+ {
+ int t0, t1, q, y;
+
+ if (x < 2)
+ {
+ return x;
+ }
+ t0 = 1;
+ t1 = BASE / x;
+ y = BASE % x;
+ while (y != 1)
+ {
+ q = x / y;
+ x = x % y;
+ t0 = (t0 + (t1 * q)) & MASK;
+ if (x == 1)
+ {
+ return t0;
+ }
+ q = y / x;
+ y = y % x;
+ t1 = (t1 + (t0 * q)) & MASK;
+ }
+ return (1 - t1) & MASK;
+ }
+ /**
+ * Return the additive inverse of x.
+ *
+ * i.e. x + AddInv(x) == 0
+ *
+ */
+ int AddInv(
+ int x)
+ {
+ return (0 - x) & MASK;
+ }
+
+ /**
+ * The function to invert the encryption subkey to the decryption subkey.
+ * It also involves the multiplicative inverse and the additive inverse functions.
+ */
+ private int[] InvertKey(
+ int[] inKey)
+ {
+ int t1, t2, t3, t4;
+ int p = 52; /* We work backwards */
+ int[] key = new int[52];
+ int inOff = 0;
+
+ t1 = MulInv(inKey[inOff++]);
+ t2 = AddInv(inKey[inOff++]);
+ t3 = AddInv(inKey[inOff++]);
+ t4 = MulInv(inKey[inOff++]);
+ key[--p] = t4;
+ key[--p] = t3;
+ key[--p] = t2;
+ key[--p] = t1;
+
+ for (int round = 1; round < 8; round++)
+ {
+ t1 = inKey[inOff++];
+ t2 = inKey[inOff++];
+ key[--p] = t2;
+ key[--p] = t1;
+
+ t1 = MulInv(inKey[inOff++]);
+ t2 = AddInv(inKey[inOff++]);
+ t3 = AddInv(inKey[inOff++]);
+ t4 = MulInv(inKey[inOff++]);
+ key[--p] = t4;
+ key[--p] = t2; /* NB: Order */
+ key[--p] = t3;
+ key[--p] = t1;
+ }
+ t1 = inKey[inOff++];
+ t2 = inKey[inOff++];
+ key[--p] = t2;
+ key[--p] = t1;
+
+ t1 = MulInv(inKey[inOff++]);
+ t2 = AddInv(inKey[inOff++]);
+ t3 = AddInv(inKey[inOff++]);
+ t4 = MulInv(inKey[inOff]);
+ key[--p] = t4;
+ key[--p] = t3;
+ key[--p] = t2;
+ key[--p] = t1;
+ return key;
+ }
+
+ private int[] GenerateWorkingKey(
+ bool forEncryption,
+ byte[] userKey)
+ {
+ if (forEncryption)
+ {
+ return ExpandKey(userKey);
+ }
+ else
+ {
+ return InvertKey(ExpandKey(userKey));
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/IdeaEngine.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/IdeaEngine.cs.meta
new file mode 100644
index 00000000..0b1f20b8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/IdeaEngine.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 4803aa4dab7fb004db3a42672bcbb85a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/IesEngine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/IesEngine.cs
new file mode 100644
index 00000000..2b4c9045
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/IesEngine.cs
@@ -0,0 +1,247 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ /**
+ * support class for constructing intergrated encryption ciphers
+ * for doing basic message exchanges on top of key agreement ciphers
+ */
+ public class IesEngine
+ {
+ private readonly IBasicAgreement agree;
+ private readonly IDerivationFunction kdf;
+ private readonly IMac mac;
+ private readonly BufferedBlockCipher cipher;
+ private readonly byte[] macBuf;
+
+ private bool forEncryption;
+ private ICipherParameters privParam, pubParam;
+ private IesParameters param;
+
+ /**
+ * set up for use with stream mode, where the key derivation function
+ * is used to provide a stream of bytes to xor with the message.
+ *
+ * @param agree the key agreement used as the basis for the encryption
+ * @param kdf the key derivation function used for byte generation
+ * @param mac the message authentication code generator for the message
+ */
+ public IesEngine(
+ IBasicAgreement agree,
+ IDerivationFunction kdf,
+ IMac mac)
+ {
+ this.agree = agree;
+ this.kdf = kdf;
+ this.mac = mac;
+ this.macBuf = new byte[mac.GetMacSize()];
+// this.cipher = null;
+ }
+
+ /**
+ * set up for use in conjunction with a block cipher to handle the
+ * message.
+ *
+ * @param agree the key agreement used as the basis for the encryption
+ * @param kdf the key derivation function used for byte generation
+ * @param mac the message authentication code generator for the message
+ * @param cipher the cipher to used for encrypting the message
+ */
+ public IesEngine(
+ IBasicAgreement agree,
+ IDerivationFunction kdf,
+ IMac mac,
+ BufferedBlockCipher cipher)
+ {
+ this.agree = agree;
+ this.kdf = kdf;
+ this.mac = mac;
+ this.macBuf = new byte[mac.GetMacSize()];
+ this.cipher = cipher;
+ }
+
+ /**
+ * Initialise the encryptor.
+ *
+ * @param forEncryption whether or not this is encryption/decryption.
+ * @param privParam our private key parameters
+ * @param pubParam the recipient's/sender's public key parameters
+ * @param param encoding and derivation parameters.
+ */
+ public virtual void Init(
+ bool forEncryption,
+ ICipherParameters privParameters,
+ ICipherParameters pubParameters,
+ ICipherParameters iesParameters)
+ {
+ this.forEncryption = forEncryption;
+ this.privParam = privParameters;
+ this.pubParam = pubParameters;
+ this.param = (IesParameters)iesParameters;
+ }
+
+ private byte[] DecryptBlock(
+ byte[] in_enc,
+ int inOff,
+ int inLen,
+ byte[] z)
+ {
+ byte[] M = null;
+ KeyParameter macKey = null;
+ KdfParameters kParam = new KdfParameters(z, param.GetDerivationV());
+ int macKeySize = param.MacKeySize;
+
+ kdf.Init(kParam);
+
+ // Ensure that the length of the input is greater than the MAC in bytes
+ if (inLen < mac.GetMacSize())
+ throw new InvalidCipherTextException("Length of input must be greater than the MAC");
+
+ inLen -= mac.GetMacSize();
+
+ if (cipher == null) // stream mode
+ {
+ byte[] Buffer = GenerateKdfBytes(kParam, inLen + (macKeySize / 8));
+
+ M = new byte[inLen];
+
+ for (int i = 0; i != inLen; i++)
+ {
+ M[i] = (byte)(in_enc[inOff + i] ^ Buffer[i]);
+ }
+
+ macKey = new KeyParameter(Buffer, inLen, (macKeySize / 8));
+ }
+ else
+ {
+ int cipherKeySize = ((IesWithCipherParameters)param).CipherKeySize;
+ byte[] Buffer = GenerateKdfBytes(kParam, (cipherKeySize / 8) + (macKeySize / 8));
+
+ cipher.Init(false, new KeyParameter(Buffer, 0, (cipherKeySize / 8)));
+
+ M = cipher.DoFinal(in_enc, inOff, inLen);
+
+ macKey = new KeyParameter(Buffer, (cipherKeySize / 8), (macKeySize / 8));
+ }
+
+ byte[] macIV = param.GetEncodingV();
+
+ mac.Init(macKey);
+ mac.BlockUpdate(in_enc, inOff, inLen);
+ mac.BlockUpdate(macIV, 0, macIV.Length);
+ mac.DoFinal(macBuf, 0);
+
+ inOff += inLen;
+
+ byte[] T1 = Arrays.CopyOfRange(in_enc, inOff, inOff + macBuf.Length);
+
+ if (!Arrays.ConstantTimeAreEqual(T1, macBuf))
+ throw (new InvalidCipherTextException("Invalid MAC."));
+
+ return M;
+ }
+
+ private byte[] EncryptBlock(
+ byte[] input,
+ int inOff,
+ int inLen,
+ byte[] z)
+ {
+ byte[] C = null;
+ KeyParameter macKey = null;
+ KdfParameters kParam = new KdfParameters(z, param.GetDerivationV());
+ int c_text_length = 0;
+ int macKeySize = param.MacKeySize;
+
+ if (cipher == null) // stream mode
+ {
+ byte[] Buffer = GenerateKdfBytes(kParam, inLen + (macKeySize / 8));
+
+ C = new byte[inLen + mac.GetMacSize()];
+ c_text_length = inLen;
+
+ for (int i = 0; i != inLen; i++)
+ {
+ C[i] = (byte)(input[inOff + i] ^ Buffer[i]);
+ }
+
+ macKey = new KeyParameter(Buffer, inLen, (macKeySize / 8));
+ }
+ else
+ {
+ int cipherKeySize = ((IesWithCipherParameters)param).CipherKeySize;
+ byte[] Buffer = GenerateKdfBytes(kParam, (cipherKeySize / 8) + (macKeySize / 8));
+
+ cipher.Init(true, new KeyParameter(Buffer, 0, (cipherKeySize / 8)));
+
+ c_text_length = cipher.GetOutputSize(inLen);
+ byte[] tmp = new byte[c_text_length];
+
+ int len = cipher.ProcessBytes(input, inOff, inLen, tmp, 0);
+ len += cipher.DoFinal(tmp, len);
+
+ C = new byte[len + mac.GetMacSize()];
+ c_text_length = len;
+
+ Array.Copy(tmp, 0, C, 0, len);
+
+ macKey = new KeyParameter(Buffer, (cipherKeySize / 8), (macKeySize / 8));
+ }
+
+ byte[] macIV = param.GetEncodingV();
+
+ mac.Init(macKey);
+ mac.BlockUpdate(C, 0, c_text_length);
+ mac.BlockUpdate(macIV, 0, macIV.Length);
+ //
+ // return the message and it's MAC
+ //
+ mac.DoFinal(C, c_text_length);
+ return C;
+ }
+
+ private byte[] GenerateKdfBytes(
+ KdfParameters kParam,
+ int length)
+ {
+ byte[] buf = new byte[length];
+
+ kdf.Init(kParam);
+
+ kdf.GenerateBytes(buf, 0, buf.Length);
+
+ return buf;
+ }
+
+ public virtual byte[] ProcessBlock(
+ byte[] input,
+ int inOff,
+ int inLen)
+ {
+ agree.Init(privParam);
+
+ BigInteger z = agree.CalculateAgreement(pubParam);
+
+ byte[] zBytes = BigIntegers.AsUnsignedByteArray(agree.GetFieldSize(), z);
+
+ try
+ {
+ return forEncryption
+ ? EncryptBlock(input, inOff, inLen, zBytes)
+ : DecryptBlock(input, inOff, inLen, zBytes);
+ }
+ finally
+ {
+ Array.Clear(zBytes, 0, zBytes.Length);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/IesEngine.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/IesEngine.cs.meta
new file mode 100644
index 00000000..5af747d0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/IesEngine.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 7cea1426e4f8131488b05c998910d4ac
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/NaccacheSternEngine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/NaccacheSternEngine.cs
new file mode 100644
index 00000000..77e739c4
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/NaccacheSternEngine.cs
@@ -0,0 +1,362 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ /**
+ * NaccacheStern Engine. For details on this cipher, please see
+ * http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf
+ */
+ public class NaccacheSternEngine
+ : IAsymmetricBlockCipher
+ {
+ private bool forEncryption;
+
+ private NaccacheSternKeyParameters key;
+
+ private IList[] lookup = null;
+
+ public string AlgorithmName
+ {
+ get { return "NaccacheStern"; }
+ }
+
+ /**
+ * Initializes this algorithm. Must be called before all other Functions.
+ *
+ * @see org.bouncycastle.crypto.AsymmetricBlockCipher#init(bool,
+ * org.bouncycastle.crypto.CipherParameters)
+ */
+ public virtual void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ this.forEncryption = forEncryption;
+
+ if (parameters is ParametersWithRandom)
+ {
+ parameters = ((ParametersWithRandom) parameters).Parameters;
+ }
+
+ key = (NaccacheSternKeyParameters)parameters;
+
+ // construct lookup table for faster decryption if necessary
+ if (!this.forEncryption)
+ {
+ NaccacheSternPrivateKeyParameters priv = (NaccacheSternPrivateKeyParameters)key;
+ IList primes = priv.SmallPrimesList;
+ lookup = new IList[primes.Count];
+ for (int i = 0; i < primes.Count; i++)
+ {
+ BigInteger actualPrime = (BigInteger) primes[i];
+ int actualPrimeValue = actualPrime.IntValue;
+
+ lookup[i] = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(actualPrimeValue);
+ lookup[i].Add(BigInteger.One);
+
+ BigInteger accJ = BigInteger.Zero;
+
+ for (int j = 1; j < actualPrimeValue; j++)
+ {
+// BigInteger bigJ = BigInteger.ValueOf(j);
+// accJ = priv.PhiN.Multiply(bigJ);
+ accJ = accJ.Add(priv.PhiN);
+ BigInteger comp = accJ.Divide(actualPrime);
+ lookup[i].Add(priv.G.ModPow(comp, priv.Modulus));
+ }
+ }
+ }
+ }
+
+ [Obsolete("Remove: no longer used")]
+ public virtual bool Debug
+ {
+ set {}
+ }
+
+ /**
+ * Returns the input block size of this algorithm.
+ *
+ * @see org.bouncycastle.crypto.AsymmetricBlockCipher#GetInputBlockSize()
+ */
+ public virtual int GetInputBlockSize()
+ {
+ if (forEncryption)
+ {
+ // We can only encrypt values up to lowerSigmaBound
+ return (key.LowerSigmaBound + 7) / 8 - 1;
+ }
+ else
+ {
+ // We pad to modulus-size bytes for easier decryption.
+// return key.Modulus.ToByteArray().Length;
+ return key.Modulus.BitLength / 8 + 1;
+ }
+ }
+
+ /**
+ * Returns the output block size of this algorithm.
+ *
+ * @see org.bouncycastle.crypto.AsymmetricBlockCipher#GetOutputBlockSize()
+ */
+ public virtual int GetOutputBlockSize()
+ {
+ if (forEncryption)
+ {
+ // encrypted Data is always padded up to modulus size
+// return key.Modulus.ToByteArray().Length;
+ return key.Modulus.BitLength / 8 + 1;
+ }
+ else
+ {
+ // decrypted Data has upper limit lowerSigmaBound
+ return (key.LowerSigmaBound + 7) / 8 - 1;
+ }
+ }
+
+ /**
+ * Process a single Block using the Naccache-Stern algorithm.
+ *
+ * @see org.bouncycastle.crypto.AsymmetricBlockCipher#ProcessBlock(byte[],
+ * int, int)
+ */
+ public virtual byte[] ProcessBlock(
+ byte[] inBytes,
+ int inOff,
+ int length)
+ {
+ if (key == null)
+ throw new InvalidOperationException("NaccacheStern engine not initialised");
+ if (length > (GetInputBlockSize() + 1))
+ throw new DataLengthException("input too large for Naccache-Stern cipher.\n");
+
+ if (!forEncryption)
+ {
+ // At decryption make sure that we receive padded data blocks
+ if (length < GetInputBlockSize())
+ {
+ throw new InvalidCipherTextException("BlockLength does not match modulus for Naccache-Stern cipher.\n");
+ }
+ }
+
+ // transform input into BigInteger
+ BigInteger input = new BigInteger(1, inBytes, inOff, length);
+
+ byte[] output;
+ if (forEncryption)
+ {
+ output = Encrypt(input);
+ }
+ else
+ {
+ IList plain = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ NaccacheSternPrivateKeyParameters priv = (NaccacheSternPrivateKeyParameters)key;
+ IList primes = priv.SmallPrimesList;
+ // Get Chinese Remainders of CipherText
+ for (int i = 0; i < primes.Count; i++)
+ {
+ BigInteger exp = input.ModPow(priv.PhiN.Divide((BigInteger)primes[i]), priv.Modulus);
+ IList al = lookup[i];
+ if (lookup[i].Count != ((BigInteger)primes[i]).IntValue)
+ {
+ throw new InvalidCipherTextException("Error in lookup Array for "
+ + ((BigInteger)primes[i]).IntValue
+ + ": Size mismatch. Expected ArrayList with length "
+ + ((BigInteger)primes[i]).IntValue + " but found ArrayList of length "
+ + lookup[i].Count);
+ }
+ int lookedup = al.IndexOf(exp);
+
+ if (lookedup == -1)
+ {
+ throw new InvalidCipherTextException("Lookup failed");
+ }
+ plain.Add(BigInteger.ValueOf(lookedup));
+ }
+ BigInteger test = chineseRemainder(plain, primes);
+
+ // Should not be used as an oracle, so reencrypt output to see
+ // if it corresponds to input
+
+ // this breaks probabilisic encryption, so disable it. Anyway, we do
+ // use the first n primes for key generation, so it is pretty easy
+ // to guess them. But as stated in the paper, this is not a security
+ // breach. So we can just work with the correct sigma.
+
+ // if ((key.G.ModPow(test, key.Modulus)).Equals(input)) {
+ // output = test.ToByteArray();
+ // } else {
+ // output = null;
+ // }
+
+ output = test.ToByteArray();
+ }
+
+ return output;
+ }
+
+ /**
+ * Encrypts a BigInteger aka Plaintext with the public key.
+ *
+ * @param plain
+ * The BigInteger to encrypt
+ * @return The byte[] representation of the encrypted BigInteger (i.e.
+ * crypted.toByteArray())
+ */
+ public virtual byte[] Encrypt(
+ BigInteger plain)
+ {
+ // Always return modulus size values 0-padded at the beginning
+ // 0-padding at the beginning is correctly parsed by BigInteger :)
+// byte[] output = key.Modulus.ToByteArray();
+// Array.Clear(output, 0, output.Length);
+ byte[] output = new byte[key.Modulus.BitLength / 8 + 1];
+
+ byte[] tmp = key.G.ModPow(plain, key.Modulus).ToByteArray();
+ Array.Copy(tmp, 0, output, output.Length - tmp.Length, tmp.Length);
+ return output;
+ }
+
+ /**
+ * Adds the contents of two encrypted blocks mod sigma
+ *
+ * @param block1
+ * the first encrypted block
+ * @param block2
+ * the second encrypted block
+ * @return encrypt((block1 + block2) mod sigma)
+ * @throws InvalidCipherTextException
+ */
+ public virtual byte[] AddCryptedBlocks(
+ byte[] block1,
+ byte[] block2)
+ {
+ // check for correct blocksize
+ if (forEncryption)
+ {
+ if ((block1.Length > GetOutputBlockSize())
+ || (block2.Length > GetOutputBlockSize()))
+ {
+ throw new InvalidCipherTextException(
+ "BlockLength too large for simple addition.\n");
+ }
+ }
+ else
+ {
+ if ((block1.Length > GetInputBlockSize())
+ || (block2.Length > GetInputBlockSize()))
+ {
+ throw new InvalidCipherTextException(
+ "BlockLength too large for simple addition.\n");
+ }
+ }
+
+ // calculate resulting block
+ BigInteger m1Crypt = new BigInteger(1, block1);
+ BigInteger m2Crypt = new BigInteger(1, block2);
+ BigInteger m1m2Crypt = m1Crypt.Multiply(m2Crypt);
+ m1m2Crypt = m1m2Crypt.Mod(key.Modulus);
+
+ //byte[] output = key.Modulus.ToByteArray();
+ //Array.Clear(output, 0, output.Length);
+ byte[] output = new byte[key.Modulus.BitLength / 8 + 1];
+
+ byte[] m1m2CryptBytes = m1m2Crypt.ToByteArray();
+ Array.Copy(m1m2CryptBytes, 0, output,
+ output.Length - m1m2CryptBytes.Length, m1m2CryptBytes.Length);
+
+ return output;
+ }
+
+ /**
+ * Convenience Method for data exchange with the cipher.
+ *
+ * Determines blocksize and splits data to blocksize.
+ *
+ * @param data the data to be processed
+ * @return the data after it went through the NaccacheSternEngine.
+ * @throws InvalidCipherTextException
+ */
+ public virtual byte[] ProcessData(
+ byte[] data)
+ {
+ if (data.Length > GetInputBlockSize())
+ {
+ int inBlocksize = GetInputBlockSize();
+ int outBlocksize = GetOutputBlockSize();
+ int datapos = 0;
+ int retpos = 0;
+ byte[] retval = new byte[(data.Length / inBlocksize + 1) * outBlocksize];
+ while (datapos < data.Length)
+ {
+ byte[] tmp;
+ if (datapos + inBlocksize < data.Length)
+ {
+ tmp = ProcessBlock(data, datapos, inBlocksize);
+ datapos += inBlocksize;
+ }
+ else
+ {
+ tmp = ProcessBlock(data, datapos, data.Length - datapos);
+ datapos += data.Length - datapos;
+ }
+ if (tmp != null)
+ {
+ tmp.CopyTo(retval, retpos);
+ retpos += tmp.Length;
+ }
+ else
+ {
+ throw new InvalidCipherTextException("cipher returned null");
+ }
+ }
+ byte[] ret = new byte[retpos];
+ Array.Copy(retval, 0, ret, 0, retpos);
+ return ret;
+ }
+ else
+ {
+ return ProcessBlock(data, 0, data.Length);
+ }
+ }
+
+ /**
+ * Computes the integer x that is expressed through the given primes and the
+ * congruences with the chinese remainder theorem (CRT).
+ *
+ * @param congruences
+ * the congruences c_i
+ * @param primes
+ * the primes p_i
+ * @return an integer x for that x % p_i == c_i
+ */
+ private static BigInteger chineseRemainder(IList congruences, IList primes)
+ {
+ BigInteger retval = BigInteger.Zero;
+ BigInteger all = BigInteger.One;
+ for (int i = 0; i < primes.Count; i++)
+ {
+ all = all.Multiply((BigInteger)primes[i]);
+ }
+ for (int i = 0; i < primes.Count; i++)
+ {
+ BigInteger a = (BigInteger)primes[i];
+ BigInteger b = all.Divide(a);
+ BigInteger b2 = b.ModInverse(a);
+ BigInteger tmp = b.Multiply(b2);
+ tmp = tmp.Multiply((BigInteger)congruences[i]);
+ retval = retval.Add(tmp);
+ }
+
+ return retval.Mod(all);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/NaccacheSternEngine.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/NaccacheSternEngine.cs.meta
new file mode 100644
index 00000000..66c1df8b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/NaccacheSternEngine.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 4a7ab764450893347acda928f15fa396
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/NoekeonEngine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/NoekeonEngine.cs
new file mode 100644
index 00000000..a39d7140
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/NoekeonEngine.cs
@@ -0,0 +1,245 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ /**
+ * A Noekeon engine, using direct-key mode.
+ */
+ public class NoekeonEngine
+ : IBlockCipher
+ {
+ private const int GenericSize = 16; // Block and key size, as well as the amount of rounds.
+
+ private static readonly uint[] nullVector =
+ {
+ 0x00, 0x00, 0x00, 0x00 // Used in decryption
+ };
+
+ private static readonly uint[] roundConstants =
+ {
+ 0x80, 0x1b, 0x36, 0x6c,
+ 0xd8, 0xab, 0x4d, 0x9a,
+ 0x2f, 0x5e, 0xbc, 0x63,
+ 0xc6, 0x97, 0x35, 0x6a,
+ 0xd4
+ };
+
+ private uint[] state = new uint[4], // a
+ subKeys = new uint[4], // k
+ decryptKeys = new uint[4];
+
+ private bool _initialised, _forEncryption;
+
+ /**
+ * Create an instance of the Noekeon encryption algorithm
+ * and set some defaults
+ */
+ public NoekeonEngine()
+ {
+ _initialised = false;
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "Noekeon"; }
+ }
+
+ public virtual bool IsPartialBlockOkay
+ {
+ get { return false; }
+ }
+
+ public virtual int GetBlockSize()
+ {
+ return GenericSize;
+ }
+
+ /**
+ * initialise
+ *
+ * @param forEncryption whether or not we are for encryption.
+ * @param params the parameters required to set up the cipher.
+ * @exception ArgumentException if the params argument is
+ * inappropriate.
+ */
+ public virtual void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ if (!(parameters is KeyParameter))
+ throw new ArgumentException("Invalid parameters passed to Noekeon init - "
+ + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters), "parameters");
+
+ _forEncryption = forEncryption;
+ _initialised = true;
+
+ KeyParameter p = (KeyParameter) parameters;
+
+ setKey(p.GetKey());
+ }
+
+ public virtual int ProcessBlock(
+ byte[] input,
+ int inOff,
+ byte[] output,
+ int outOff)
+ {
+ if (!_initialised)
+ throw new InvalidOperationException(AlgorithmName + " not initialised");
+
+ Check.DataLength(input, inOff, GenericSize, "input buffer too short");
+ Check.OutputLength(output, outOff, GenericSize, "output buffer too short");
+
+ return _forEncryption
+ ? encryptBlock(input, inOff, output, outOff)
+ : decryptBlock(input, inOff, output, outOff);
+ }
+
+ public virtual void Reset()
+ {
+ // TODO This should do something in case the encryption is aborted
+ }
+
+ /**
+ * Re-key the cipher.
+ *
+ * @param key the key to be used
+ */
+ private void setKey(byte[] key)
+ {
+ subKeys[0] = Pack.BE_To_UInt32(key, 0);
+ subKeys[1] = Pack.BE_To_UInt32(key, 4);
+ subKeys[2] = Pack.BE_To_UInt32(key, 8);
+ subKeys[3] = Pack.BE_To_UInt32(key, 12);
+ }
+
+ private int encryptBlock(
+ byte[] input,
+ int inOff,
+ byte[] output,
+ int outOff)
+ {
+ state[0] = Pack.BE_To_UInt32(input, inOff);
+ state[1] = Pack.BE_To_UInt32(input, inOff+4);
+ state[2] = Pack.BE_To_UInt32(input, inOff+8);
+ state[3] = Pack.BE_To_UInt32(input, inOff+12);
+
+ int i;
+ for (i = 0; i < GenericSize; i++)
+ {
+ state[0] ^= roundConstants[i];
+ theta(state, subKeys);
+ pi1(state);
+ gamma(state);
+ pi2(state);
+ }
+
+ state[0] ^= roundConstants[i];
+ theta(state, subKeys);
+
+ Pack.UInt32_To_BE(state[0], output, outOff);
+ Pack.UInt32_To_BE(state[1], output, outOff+4);
+ Pack.UInt32_To_BE(state[2], output, outOff+8);
+ Pack.UInt32_To_BE(state[3], output, outOff+12);
+
+ return GenericSize;
+ }
+
+ private int decryptBlock(
+ byte[] input,
+ int inOff,
+ byte[] output,
+ int outOff)
+ {
+ state[0] = Pack.BE_To_UInt32(input, inOff);
+ state[1] = Pack.BE_To_UInt32(input, inOff+4);
+ state[2] = Pack.BE_To_UInt32(input, inOff+8);
+ state[3] = Pack.BE_To_UInt32(input, inOff+12);
+
+ Array.Copy(subKeys, 0, decryptKeys, 0, subKeys.Length);
+ theta(decryptKeys, nullVector);
+
+ int i;
+ for (i = GenericSize; i > 0; i--)
+ {
+ theta(state, decryptKeys);
+ state[0] ^= roundConstants[i];
+ pi1(state);
+ gamma(state);
+ pi2(state);
+ }
+
+ theta(state, decryptKeys);
+ state[0] ^= roundConstants[i];
+
+ Pack.UInt32_To_BE(state[0], output, outOff);
+ Pack.UInt32_To_BE(state[1], output, outOff+4);
+ Pack.UInt32_To_BE(state[2], output, outOff+8);
+ Pack.UInt32_To_BE(state[3], output, outOff+12);
+
+ return GenericSize;
+ }
+
+ private void gamma(uint[] a)
+ {
+ a[1] ^= ~a[3] & ~a[2];
+ a[0] ^= a[2] & a[1];
+
+ uint tmp = a[3];
+ a[3] = a[0];
+ a[0] = tmp;
+ a[2] ^= a[0]^a[1]^a[3];
+
+ a[1] ^= ~a[3] & ~a[2];
+ a[0] ^= a[2] & a[1];
+ }
+
+ private void theta(uint[] a, uint[] k)
+ {
+ uint tmp;
+ tmp = a[0]^a[2];
+ tmp ^= rotl(tmp,8)^rotl(tmp,24);
+ a[1] ^= tmp;
+ a[3] ^= tmp;
+
+ for (int i = 0; i < 4; i++)
+ {
+ a[i] ^= k[i];
+ }
+
+ tmp = a[1]^a[3];
+ tmp ^= rotl(tmp,8)^rotl(tmp,24);
+ a[0] ^= tmp;
+ a[2] ^= tmp;
+ }
+
+ private void pi1(uint[] a)
+ {
+ a[1] = rotl(a[1], 1);
+ a[2] = rotl(a[2], 5);
+ a[3] = rotl(a[3], 2);
+ }
+
+ private void pi2(uint[] a)
+ {
+ a[1] = rotl(a[1], 31);
+ a[2] = rotl(a[2], 27);
+ a[3] = rotl(a[3], 30);
+ }
+
+ // Helpers
+
+ private uint rotl(uint x, int y)
+ {
+ return (x << y) | (x >> (32-y));
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/NoekeonEngine.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/NoekeonEngine.cs.meta
new file mode 100644
index 00000000..b3e41eb6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/NoekeonEngine.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 89978e6f457d6a546ac5b8c81fa0b9cb
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/NullEngine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/NullEngine.cs
new file mode 100644
index 00000000..8611c190
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/NullEngine.cs
@@ -0,0 +1,73 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ /**
+ * The no-op engine that just copies bytes through, irrespective of whether encrypting and decrypting.
+ * Provided for the sake of completeness.
+ */
+ public class NullEngine
+ : IBlockCipher
+ {
+ private bool initialised;
+ private const int BlockSize = 1;
+
+ public NullEngine()
+ {
+ }
+
+ public virtual void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ // we don't mind any parameters that may come in
+ initialised = true;
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "Null"; }
+ }
+
+ public virtual bool IsPartialBlockOkay
+ {
+ get { return true; }
+ }
+
+ public virtual int GetBlockSize()
+ {
+ return BlockSize;
+ }
+
+ public virtual int ProcessBlock(
+ byte[] input,
+ int inOff,
+ byte[] output,
+ int outOff)
+ {
+ if (!initialised)
+ throw new InvalidOperationException("Null engine not initialised");
+
+ Check.DataLength(input, inOff, BlockSize, "input buffer too short");
+ Check.OutputLength(output, outOff, BlockSize, "output buffer too short");
+
+ for (int i = 0; i < BlockSize; ++i)
+ {
+ output[outOff + i] = input[inOff + i];
+ }
+
+ return BlockSize;
+ }
+
+ public virtual void Reset()
+ {
+ // nothing needs to be done
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/NullEngine.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/NullEngine.cs.meta
new file mode 100644
index 00000000..82f177c8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/NullEngine.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: e8ef7c09573c15a4aa37a145bd617daf
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC2Engine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC2Engine.cs
new file mode 100644
index 00000000..19b850ea
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC2Engine.cs
@@ -0,0 +1,315 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ /**
+ * an implementation of RC2 as described in RFC 2268
+ * "A Description of the RC2(r) Encryption Algorithm" R. Rivest.
+ */
+ public class RC2Engine
+ : IBlockCipher
+ {
+ //
+ // the values we use for key expansion (based on the digits of PI)
+ //
+ private static readonly byte[] piTable =
+ {
+ (byte)0xd9, (byte)0x78, (byte)0xf9, (byte)0xc4, (byte)0x19, (byte)0xdd, (byte)0xb5, (byte)0xed,
+ (byte)0x28, (byte)0xe9, (byte)0xfd, (byte)0x79, (byte)0x4a, (byte)0xa0, (byte)0xd8, (byte)0x9d,
+ (byte)0xc6, (byte)0x7e, (byte)0x37, (byte)0x83, (byte)0x2b, (byte)0x76, (byte)0x53, (byte)0x8e,
+ (byte)0x62, (byte)0x4c, (byte)0x64, (byte)0x88, (byte)0x44, (byte)0x8b, (byte)0xfb, (byte)0xa2,
+ (byte)0x17, (byte)0x9a, (byte)0x59, (byte)0xf5, (byte)0x87, (byte)0xb3, (byte)0x4f, (byte)0x13,
+ (byte)0x61, (byte)0x45, (byte)0x6d, (byte)0x8d, (byte)0x9, (byte)0x81, (byte)0x7d, (byte)0x32,
+ (byte)0xbd, (byte)0x8f, (byte)0x40, (byte)0xeb, (byte)0x86, (byte)0xb7, (byte)0x7b, (byte)0xb,
+ (byte)0xf0, (byte)0x95, (byte)0x21, (byte)0x22, (byte)0x5c, (byte)0x6b, (byte)0x4e, (byte)0x82,
+ (byte)0x54, (byte)0xd6, (byte)0x65, (byte)0x93, (byte)0xce, (byte)0x60, (byte)0xb2, (byte)0x1c,
+ (byte)0x73, (byte)0x56, (byte)0xc0, (byte)0x14, (byte)0xa7, (byte)0x8c, (byte)0xf1, (byte)0xdc,
+ (byte)0x12, (byte)0x75, (byte)0xca, (byte)0x1f, (byte)0x3b, (byte)0xbe, (byte)0xe4, (byte)0xd1,
+ (byte)0x42, (byte)0x3d, (byte)0xd4, (byte)0x30, (byte)0xa3, (byte)0x3c, (byte)0xb6, (byte)0x26,
+ (byte)0x6f, (byte)0xbf, (byte)0xe, (byte)0xda, (byte)0x46, (byte)0x69, (byte)0x7, (byte)0x57,
+ (byte)0x27, (byte)0xf2, (byte)0x1d, (byte)0x9b, (byte)0xbc, (byte)0x94, (byte)0x43, (byte)0x3,
+ (byte)0xf8, (byte)0x11, (byte)0xc7, (byte)0xf6, (byte)0x90, (byte)0xef, (byte)0x3e, (byte)0xe7,
+ (byte)0x6, (byte)0xc3, (byte)0xd5, (byte)0x2f, (byte)0xc8, (byte)0x66, (byte)0x1e, (byte)0xd7,
+ (byte)0x8, (byte)0xe8, (byte)0xea, (byte)0xde, (byte)0x80, (byte)0x52, (byte)0xee, (byte)0xf7,
+ (byte)0x84, (byte)0xaa, (byte)0x72, (byte)0xac, (byte)0x35, (byte)0x4d, (byte)0x6a, (byte)0x2a,
+ (byte)0x96, (byte)0x1a, (byte)0xd2, (byte)0x71, (byte)0x5a, (byte)0x15, (byte)0x49, (byte)0x74,
+ (byte)0x4b, (byte)0x9f, (byte)0xd0, (byte)0x5e, (byte)0x4, (byte)0x18, (byte)0xa4, (byte)0xec,
+ (byte)0xc2, (byte)0xe0, (byte)0x41, (byte)0x6e, (byte)0xf, (byte)0x51, (byte)0xcb, (byte)0xcc,
+ (byte)0x24, (byte)0x91, (byte)0xaf, (byte)0x50, (byte)0xa1, (byte)0xf4, (byte)0x70, (byte)0x39,
+ (byte)0x99, (byte)0x7c, (byte)0x3a, (byte)0x85, (byte)0x23, (byte)0xb8, (byte)0xb4, (byte)0x7a,
+ (byte)0xfc, (byte)0x2, (byte)0x36, (byte)0x5b, (byte)0x25, (byte)0x55, (byte)0x97, (byte)0x31,
+ (byte)0x2d, (byte)0x5d, (byte)0xfa, (byte)0x98, (byte)0xe3, (byte)0x8a, (byte)0x92, (byte)0xae,
+ (byte)0x5, (byte)0xdf, (byte)0x29, (byte)0x10, (byte)0x67, (byte)0x6c, (byte)0xba, (byte)0xc9,
+ (byte)0xd3, (byte)0x0, (byte)0xe6, (byte)0xcf, (byte)0xe1, (byte)0x9e, (byte)0xa8, (byte)0x2c,
+ (byte)0x63, (byte)0x16, (byte)0x1, (byte)0x3f, (byte)0x58, (byte)0xe2, (byte)0x89, (byte)0xa9,
+ (byte)0xd, (byte)0x38, (byte)0x34, (byte)0x1b, (byte)0xab, (byte)0x33, (byte)0xff, (byte)0xb0,
+ (byte)0xbb, (byte)0x48, (byte)0xc, (byte)0x5f, (byte)0xb9, (byte)0xb1, (byte)0xcd, (byte)0x2e,
+ (byte)0xc5, (byte)0xf3, (byte)0xdb, (byte)0x47, (byte)0xe5, (byte)0xa5, (byte)0x9c, (byte)0x77,
+ (byte)0xa, (byte)0xa6, (byte)0x20, (byte)0x68, (byte)0xfe, (byte)0x7f, (byte)0xc1, (byte)0xad
+ };
+
+ private const int BLOCK_SIZE = 8;
+
+ private int[] workingKey;
+ private bool encrypting;
+
+ private int[] GenerateWorkingKey(
+ byte[] key,
+ int bits)
+ {
+ int x;
+ int[] xKey = new int[128];
+
+ for (int i = 0; i != key.Length; i++)
+ {
+ xKey[i] = key[i] & 0xff;
+ }
+
+ // Phase 1: Expand input key to 128 bytes
+ int len = key.Length;
+
+ if (len < 128)
+ {
+ int index = 0;
+
+ x = xKey[len - 1];
+
+ do
+ {
+ x = piTable[(x + xKey[index++]) & 255] & 0xff;
+ xKey[len++] = x;
+ }
+ while (len < 128);
+ }
+
+ // Phase 2 - reduce effective key size to "bits"
+ len = (bits + 7) >> 3;
+ x = piTable[xKey[128 - len] & (255 >> (7 & -bits))] & 0xff;
+ xKey[128 - len] = x;
+
+ for (int i = 128 - len - 1; i >= 0; i--)
+ {
+ x = piTable[x ^ xKey[i + len]] & 0xff;
+ xKey[i] = x;
+ }
+
+ // Phase 3 - copy to newKey in little-endian order
+ int[] newKey = new int[64];
+
+ for (int i = 0; i != newKey.Length; i++)
+ {
+ newKey[i] = (xKey[2 * i] + (xKey[2 * i + 1] << 8));
+ }
+
+ return newKey;
+ }
+
+ /**
+ * initialise a RC2 cipher.
+ *
+ * @param forEncryption whether or not we are for encryption.
+ * @param parameters the parameters required to set up the cipher.
+ * @exception ArgumentException if the parameters argument is
+ * inappropriate.
+ */
+ public virtual void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ this.encrypting = forEncryption;
+
+ if (parameters is RC2Parameters)
+ {
+ RC2Parameters param = (RC2Parameters) parameters;
+
+ workingKey = GenerateWorkingKey(param.GetKey(), param.EffectiveKeyBits);
+ }
+ else if (parameters is KeyParameter)
+ {
+ KeyParameter param = (KeyParameter) parameters;
+ byte[] key = param.GetKey();
+
+ workingKey = GenerateWorkingKey(key, key.Length * 8);
+ }
+ else
+ {
+ throw new ArgumentException("invalid parameter passed to RC2 init - " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters));
+ }
+ }
+
+ public virtual void Reset()
+ {
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "RC2"; }
+ }
+
+ public virtual bool IsPartialBlockOkay
+ {
+ get { return false; }
+ }
+
+ public virtual int GetBlockSize()
+ {
+ return BLOCK_SIZE;
+ }
+
+ public virtual int ProcessBlock(
+ byte[] input,
+ int inOff,
+ byte[] output,
+ int outOff)
+ {
+ if (workingKey == null)
+ throw new InvalidOperationException("RC2 engine not initialised");
+
+ Check.DataLength(input, inOff, BLOCK_SIZE, "input buffer too short");
+ Check.OutputLength(output, outOff, BLOCK_SIZE, "output buffer too short");
+
+ if (encrypting)
+ {
+ EncryptBlock(input, inOff, output, outOff);
+ }
+ else
+ {
+ DecryptBlock(input, inOff, output, outOff);
+ }
+
+ return BLOCK_SIZE;
+ }
+
+ /**
+ * return the result rotating the 16 bit number in x left by y
+ */
+ private int RotateWordLeft(
+ int x,
+ int y)
+ {
+ x &= 0xffff;
+ return (x << y) | (x >> (16 - y));
+ }
+
+ private void EncryptBlock(
+ byte[] input,
+ int inOff,
+ byte[] outBytes,
+ int outOff)
+ {
+ int x76, x54, x32, x10;
+
+ x76 = ((input[inOff + 7] & 0xff) << 8) + (input[inOff + 6] & 0xff);
+ x54 = ((input[inOff + 5] & 0xff) << 8) + (input[inOff + 4] & 0xff);
+ x32 = ((input[inOff + 3] & 0xff) << 8) + (input[inOff + 2] & 0xff);
+ x10 = ((input[inOff + 1] & 0xff) << 8) + (input[inOff + 0] & 0xff);
+
+ for (int i = 0; i <= 16; i += 4)
+ {
+ x10 = RotateWordLeft(x10 + (x32 & ~x76) + (x54 & x76) + workingKey[i ], 1);
+ x32 = RotateWordLeft(x32 + (x54 & ~x10) + (x76 & x10) + workingKey[i+1], 2);
+ x54 = RotateWordLeft(x54 + (x76 & ~x32) + (x10 & x32) + workingKey[i+2], 3);
+ x76 = RotateWordLeft(x76 + (x10 & ~x54) + (x32 & x54) + workingKey[i+3], 5);
+ }
+
+ x10 += workingKey[x76 & 63];
+ x32 += workingKey[x10 & 63];
+ x54 += workingKey[x32 & 63];
+ x76 += workingKey[x54 & 63];
+
+ for (int i = 20; i <= 40; i += 4)
+ {
+ x10 = RotateWordLeft(x10 + (x32 & ~x76) + (x54 & x76) + workingKey[i ], 1);
+ x32 = RotateWordLeft(x32 + (x54 & ~x10) + (x76 & x10) + workingKey[i+1], 2);
+ x54 = RotateWordLeft(x54 + (x76 & ~x32) + (x10 & x32) + workingKey[i+2], 3);
+ x76 = RotateWordLeft(x76 + (x10 & ~x54) + (x32 & x54) + workingKey[i+3], 5);
+ }
+
+ x10 += workingKey[x76 & 63];
+ x32 += workingKey[x10 & 63];
+ x54 += workingKey[x32 & 63];
+ x76 += workingKey[x54 & 63];
+
+ for (int i = 44; i < 64; i += 4)
+ {
+ x10 = RotateWordLeft(x10 + (x32 & ~x76) + (x54 & x76) + workingKey[i ], 1);
+ x32 = RotateWordLeft(x32 + (x54 & ~x10) + (x76 & x10) + workingKey[i+1], 2);
+ x54 = RotateWordLeft(x54 + (x76 & ~x32) + (x10 & x32) + workingKey[i+2], 3);
+ x76 = RotateWordLeft(x76 + (x10 & ~x54) + (x32 & x54) + workingKey[i+3], 5);
+ }
+
+ outBytes[outOff + 0] = (byte)x10;
+ outBytes[outOff + 1] = (byte)(x10 >> 8);
+ outBytes[outOff + 2] = (byte)x32;
+ outBytes[outOff + 3] = (byte)(x32 >> 8);
+ outBytes[outOff + 4] = (byte)x54;
+ outBytes[outOff + 5] = (byte)(x54 >> 8);
+ outBytes[outOff + 6] = (byte)x76;
+ outBytes[outOff + 7] = (byte)(x76 >> 8);
+ }
+
+ private void DecryptBlock(
+ byte[] input,
+ int inOff,
+ byte[] outBytes,
+ int outOff)
+ {
+ int x76, x54, x32, x10;
+
+ x76 = ((input[inOff + 7] & 0xff) << 8) + (input[inOff + 6] & 0xff);
+ x54 = ((input[inOff + 5] & 0xff) << 8) + (input[inOff + 4] & 0xff);
+ x32 = ((input[inOff + 3] & 0xff) << 8) + (input[inOff + 2] & 0xff);
+ x10 = ((input[inOff + 1] & 0xff) << 8) + (input[inOff + 0] & 0xff);
+
+ for (int i = 60; i >= 44; i -= 4)
+ {
+ x76 = RotateWordLeft(x76, 11) - ((x10 & ~x54) + (x32 & x54) + workingKey[i+3]);
+ x54 = RotateWordLeft(x54, 13) - ((x76 & ~x32) + (x10 & x32) + workingKey[i+2]);
+ x32 = RotateWordLeft(x32, 14) - ((x54 & ~x10) + (x76 & x10) + workingKey[i+1]);
+ x10 = RotateWordLeft(x10, 15) - ((x32 & ~x76) + (x54 & x76) + workingKey[i ]);
+ }
+
+ x76 -= workingKey[x54 & 63];
+ x54 -= workingKey[x32 & 63];
+ x32 -= workingKey[x10 & 63];
+ x10 -= workingKey[x76 & 63];
+
+ for (int i = 40; i >= 20; i -= 4)
+ {
+ x76 = RotateWordLeft(x76, 11) - ((x10 & ~x54) + (x32 & x54) + workingKey[i+3]);
+ x54 = RotateWordLeft(x54, 13) - ((x76 & ~x32) + (x10 & x32) + workingKey[i+2]);
+ x32 = RotateWordLeft(x32, 14) - ((x54 & ~x10) + (x76 & x10) + workingKey[i+1]);
+ x10 = RotateWordLeft(x10, 15) - ((x32 & ~x76) + (x54 & x76) + workingKey[i ]);
+ }
+
+ x76 -= workingKey[x54 & 63];
+ x54 -= workingKey[x32 & 63];
+ x32 -= workingKey[x10 & 63];
+ x10 -= workingKey[x76 & 63];
+
+ for (int i = 16; i >= 0; i -= 4)
+ {
+ x76 = RotateWordLeft(x76, 11) - ((x10 & ~x54) + (x32 & x54) + workingKey[i+3]);
+ x54 = RotateWordLeft(x54, 13) - ((x76 & ~x32) + (x10 & x32) + workingKey[i+2]);
+ x32 = RotateWordLeft(x32, 14) - ((x54 & ~x10) + (x76 & x10) + workingKey[i+1]);
+ x10 = RotateWordLeft(x10, 15) - ((x32 & ~x76) + (x54 & x76) + workingKey[i ]);
+ }
+
+ outBytes[outOff + 0] = (byte)x10;
+ outBytes[outOff + 1] = (byte)(x10 >> 8);
+ outBytes[outOff + 2] = (byte)x32;
+ outBytes[outOff + 3] = (byte)(x32 >> 8);
+ outBytes[outOff + 4] = (byte)x54;
+ outBytes[outOff + 5] = (byte)(x54 >> 8);
+ outBytes[outOff + 6] = (byte)x76;
+ outBytes[outOff + 7] = (byte)(x76 >> 8);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC2Engine.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC2Engine.cs.meta
new file mode 100644
index 00000000..a5e43817
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC2Engine.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 9e2908df73e25da4690be4d9c34ba50c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC2WrapEngine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC2WrapEngine.cs
new file mode 100644
index 00000000..ad9ddf3e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC2WrapEngine.cs
@@ -0,0 +1,374 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ /**
+ * Wrap keys according to RFC 3217 - RC2 mechanism
+ */
+ public class RC2WrapEngine
+ : IWrapper
+ {
+ /** Field engine */
+ private CbcBlockCipher engine;
+
+ /** Field param */
+ private ICipherParameters parameters;
+
+ /** Field paramPlusIV */
+ private ParametersWithIV paramPlusIV;
+
+ /** Field iv */
+ private byte[] iv;
+
+ /** Field forWrapping */
+ private bool forWrapping;
+
+ private SecureRandom sr;
+
+ /** Field IV2 */
+ private static readonly byte[] IV2 =
+ {
+ (byte) 0x4a, (byte) 0xdd, (byte) 0xa2,
+ (byte) 0x2c, (byte) 0x79, (byte) 0xe8,
+ (byte) 0x21, (byte) 0x05
+ };
+
+ //
+ // checksum digest
+ //
+ IDigest sha1 = new Sha1Digest();
+ byte[] digest = new byte[20];
+
+ /**
+ * Method init
+ *
+ * @param forWrapping
+ * @param param
+ */
+ public virtual void Init(
+ bool forWrapping,
+ ICipherParameters parameters)
+ {
+ this.forWrapping = forWrapping;
+ this.engine = new CbcBlockCipher(new RC2Engine());
+
+ if (parameters is ParametersWithRandom)
+ {
+ ParametersWithRandom pWithR = (ParametersWithRandom)parameters;
+ sr = pWithR.Random;
+ parameters = pWithR.Parameters;
+ }
+ else
+ {
+ sr = new SecureRandom();
+ }
+
+ if (parameters is ParametersWithIV)
+ {
+ if (!forWrapping)
+ throw new ArgumentException("You should not supply an IV for unwrapping");
+
+ this.paramPlusIV = (ParametersWithIV)parameters;
+ this.iv = this.paramPlusIV.GetIV();
+ this.parameters = this.paramPlusIV.Parameters;
+
+ if (this.iv.Length != 8)
+ throw new ArgumentException("IV is not 8 octets");
+ }
+ else
+ {
+ this.parameters = parameters;
+
+ if (this.forWrapping)
+ {
+ // Hm, we have no IV but we want to wrap ?!?
+ // well, then we have to create our own IV.
+ this.iv = new byte[8];
+ sr.NextBytes(iv);
+ this.paramPlusIV = new ParametersWithIV(this.parameters, this.iv);
+ }
+ }
+ }
+
+ /**
+ * Method GetAlgorithmName
+ *
+ * @return
+ */
+ public virtual string AlgorithmName
+ {
+ get { return "RC2"; }
+ }
+
+ /**
+ * Method wrap
+ *
+ * @param in
+ * @param inOff
+ * @param inLen
+ * @return
+ */
+ public virtual byte[] Wrap(
+ byte[] input,
+ int inOff,
+ int length)
+ {
+ if (!forWrapping)
+ {
+ throw new InvalidOperationException("Not initialized for wrapping");
+ }
+
+ int len = length + 1;
+ if ((len % 8) != 0)
+ {
+ len += 8 - (len % 8);
+ }
+
+ byte [] keyToBeWrapped = new byte[len];
+
+ keyToBeWrapped[0] = (byte)length;
+ Array.Copy(input, inOff, keyToBeWrapped, 1, length);
+
+ byte[] pad = new byte[keyToBeWrapped.Length - length - 1];
+
+ if (pad.Length > 0)
+ {
+ sr.NextBytes(pad);
+ Array.Copy(pad, 0, keyToBeWrapped, length + 1, pad.Length);
+ }
+
+ // Compute the CMS Key Checksum, (section 5.6.1), call this CKS.
+ byte[] CKS = CalculateCmsKeyChecksum(keyToBeWrapped);
+
+ // Let WKCKS = WK || CKS where || is concatenation.
+ byte[] WKCKS = new byte[keyToBeWrapped.Length + CKS.Length];
+
+ Array.Copy(keyToBeWrapped, 0, WKCKS, 0, keyToBeWrapped.Length);
+ Array.Copy(CKS, 0, WKCKS, keyToBeWrapped.Length, CKS.Length);
+
+ // Encrypt WKCKS in CBC mode using KEK as the key and IV as the
+ // initialization vector. Call the results TEMP1.
+ byte [] TEMP1 = new byte[WKCKS.Length];
+
+ Array.Copy(WKCKS, 0, TEMP1, 0, WKCKS.Length);
+
+ int noOfBlocks = WKCKS.Length / engine.GetBlockSize();
+ int extraBytes = WKCKS.Length % engine.GetBlockSize();
+
+ if (extraBytes != 0)
+ {
+ throw new InvalidOperationException("Not multiple of block length");
+ }
+
+ engine.Init(true, paramPlusIV);
+
+ for (int i = 0; i < noOfBlocks; i++)
+ {
+ int currentBytePos = i * engine.GetBlockSize();
+
+ engine.ProcessBlock(TEMP1, currentBytePos, TEMP1, currentBytePos);
+ }
+
+ // Left TEMP2 = IV || TEMP1.
+ byte[] TEMP2 = new byte[this.iv.Length + TEMP1.Length];
+
+ Array.Copy(this.iv, 0, TEMP2, 0, this.iv.Length);
+ Array.Copy(TEMP1, 0, TEMP2, this.iv.Length, TEMP1.Length);
+
+ // Reverse the order of the octets in TEMP2 and call the result TEMP3.
+ byte[] TEMP3 = new byte[TEMP2.Length];
+
+ for (int i = 0; i < TEMP2.Length; i++)
+ {
+ TEMP3[i] = TEMP2[TEMP2.Length - (i + 1)];
+ }
+
+ // Encrypt TEMP3 in CBC mode using the KEK and an initialization vector
+ // of 0x 4a dd a2 2c 79 e8 21 05. The resulting cipher text is the desired
+ // result. It is 40 octets long if a 168 bit key is being wrapped.
+ ParametersWithIV param2 = new ParametersWithIV(this.parameters, IV2);
+
+ this.engine.Init(true, param2);
+
+ for (int i = 0; i < noOfBlocks + 1; i++)
+ {
+ int currentBytePos = i * engine.GetBlockSize();
+
+ engine.ProcessBlock(TEMP3, currentBytePos, TEMP3, currentBytePos);
+ }
+
+ return TEMP3;
+ }
+
+ /**
+ * Method unwrap
+ *
+ * @param in
+ * @param inOff
+ * @param inLen
+ * @return
+ * @throws InvalidCipherTextException
+ */
+ public virtual byte[] Unwrap(
+ byte[] input,
+ int inOff,
+ int length)
+ {
+ if (forWrapping)
+ {
+ throw new InvalidOperationException("Not set for unwrapping");
+ }
+
+ if (input == null)
+ {
+ throw new InvalidCipherTextException("Null pointer as ciphertext");
+ }
+
+ if (length % engine.GetBlockSize() != 0)
+ {
+ throw new InvalidCipherTextException("Ciphertext not multiple of "
+ + engine.GetBlockSize());
+ }
+
+ /*
+ // Check if the length of the cipher text is reasonable given the key
+ // type. It must be 40 bytes for a 168 bit key and either 32, 40, or
+ // 48 bytes for a 128, 192, or 256 bit key. If the length is not supported
+ // or inconsistent with the algorithm for which the key is intended,
+ // return error.
+ //
+ // we do not accept 168 bit keys. it has to be 192 bit.
+ int lengthA = (estimatedKeyLengthInBit / 8) + 16;
+ int lengthB = estimatedKeyLengthInBit % 8;
+
+ if ((lengthA != keyToBeUnwrapped.Length) || (lengthB != 0)) {
+ throw new XMLSecurityException("empty");
+ }
+ */
+
+ // Decrypt the cipher text with TRIPLedeS in CBC mode using the KEK
+ // and an initialization vector (IV) of 0x4adda22c79e82105. Call the output TEMP3.
+ ParametersWithIV param2 = new ParametersWithIV(this.parameters, IV2);
+
+ this.engine.Init(false, param2);
+
+ byte [] TEMP3 = new byte[length];
+
+ Array.Copy(input, inOff, TEMP3, 0, length);
+
+ for (int i = 0; i < (TEMP3.Length / engine.GetBlockSize()); i++)
+ {
+ int currentBytePos = i * engine.GetBlockSize();
+
+ engine.ProcessBlock(TEMP3, currentBytePos, TEMP3, currentBytePos);
+ }
+
+ // Reverse the order of the octets in TEMP3 and call the result TEMP2.
+ byte[] TEMP2 = new byte[TEMP3.Length];
+
+ for (int i = 0; i < TEMP3.Length; i++)
+ {
+ TEMP2[i] = TEMP3[TEMP3.Length - (i + 1)];
+ }
+
+ // Decompose TEMP2 into IV, the first 8 octets, and TEMP1, the remaining octets.
+ this.iv = new byte[8];
+
+ byte[] TEMP1 = new byte[TEMP2.Length - 8];
+
+ Array.Copy(TEMP2, 0, this.iv, 0, 8);
+ Array.Copy(TEMP2, 8, TEMP1, 0, TEMP2.Length - 8);
+
+ // Decrypt TEMP1 using TRIPLedeS in CBC mode using the KEK and the IV
+ // found in the previous step. Call the result WKCKS.
+ this.paramPlusIV = new ParametersWithIV(this.parameters, this.iv);
+
+ this.engine.Init(false, this.paramPlusIV);
+
+ byte[] LCEKPADICV = new byte[TEMP1.Length];
+
+ Array.Copy(TEMP1, 0, LCEKPADICV, 0, TEMP1.Length);
+
+ for (int i = 0; i < (LCEKPADICV.Length / engine.GetBlockSize()); i++)
+ {
+ int currentBytePos = i * engine.GetBlockSize();
+
+ engine.ProcessBlock(LCEKPADICV, currentBytePos, LCEKPADICV, currentBytePos);
+ }
+
+ // Decompose LCEKPADICV. CKS is the last 8 octets and WK, the wrapped key, are
+ // those octets before the CKS.
+ byte[] result = new byte[LCEKPADICV.Length - 8];
+ byte[] CKStoBeVerified = new byte[8];
+
+ Array.Copy(LCEKPADICV, 0, result, 0, LCEKPADICV.Length - 8);
+ Array.Copy(LCEKPADICV, LCEKPADICV.Length - 8, CKStoBeVerified, 0, 8);
+
+ // Calculate a CMS Key Checksum, (section 5.6.1), over the WK and compare
+ // with the CKS extracted in the above step. If they are not equal, return error.
+ if (!CheckCmsKeyChecksum(result, CKStoBeVerified))
+ {
+ throw new InvalidCipherTextException(
+ "Checksum inside ciphertext is corrupted");
+ }
+
+ if ((result.Length - ((result[0] & 0xff) + 1)) > 7)
+ {
+ throw new InvalidCipherTextException(
+ "too many pad bytes (" + (result.Length - ((result[0] & 0xff) + 1)) + ")");
+ }
+
+ // CEK is the wrapped key, now extracted for use in data decryption.
+ byte[] CEK = new byte[result[0]];
+ Array.Copy(result, 1, CEK, 0, CEK.Length);
+ return CEK;
+ }
+
+ /**
+ * Some key wrap algorithms make use of the Key Checksum defined
+ * in CMS [CMS-Algorithms]. This is used to provide an integrity
+ * check value for the key being wrapped. The algorithm is
+ *
+ * - Compute the 20 octet SHA-1 hash on the key being wrapped.
+ * - Use the first 8 octets of this hash as the checksum value.
+ *
+ * @param key
+ * @return
+ * @throws Exception
+ * @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum
+ */
+ private byte[] CalculateCmsKeyChecksum(
+ byte[] key)
+ {
+ sha1.BlockUpdate(key, 0, key.Length);
+ sha1.DoFinal(digest, 0);
+
+ byte[] result = new byte[8];
+ Array.Copy(digest, 0, result, 0, 8);
+ return result;
+ }
+
+ /**
+ * @param key
+ * @param checksum
+ * @return
+ * @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum
+ */
+ private bool CheckCmsKeyChecksum(
+ byte[] key,
+ byte[] checksum)
+ {
+ return Arrays.ConstantTimeAreEqual(CalculateCmsKeyChecksum(key), checksum);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC2WrapEngine.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC2WrapEngine.cs.meta
new file mode 100644
index 00000000..ece1f929
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC2WrapEngine.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0c68dd7b320ee974c9bf521cec0159e5
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC4Engine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC4Engine.cs
new file mode 100644
index 00000000..8f6214a8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC4Engine.cs
@@ -0,0 +1,143 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ public class RC4Engine
+ : IStreamCipher
+ {
+ private readonly static int STATE_LENGTH = 256;
+
+ /*
+ * variables to hold the state of the RC4 engine
+ * during encryption and decryption
+ */
+
+ private byte[] engineState;
+ private int x;
+ private int y;
+ private byte[] workingKey;
+
+ /**
+ * initialise a RC4 cipher.
+ *
+ * @param forEncryption whether or not we are for encryption.
+ * @param parameters the parameters required to set up the cipher.
+ * @exception ArgumentException if the parameters argument is
+ * inappropriate.
+ */
+ public virtual void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ if (parameters is KeyParameter)
+ {
+ /*
+ * RC4 encryption and decryption is completely
+ * symmetrical, so the 'forEncryption' is
+ * irrelevant.
+ */
+ workingKey = ((KeyParameter)parameters).GetKey();
+ SetKey(workingKey);
+
+ return;
+ }
+
+ throw new ArgumentException("invalid parameter passed to RC4 init - " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters));
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "RC4"; }
+ }
+
+ public virtual byte ReturnByte(
+ byte input)
+ {
+ x = (x + 1) & 0xff;
+ y = (engineState[x] + y) & 0xff;
+
+ // swap
+ byte tmp = engineState[x];
+ engineState[x] = engineState[y];
+ engineState[y] = tmp;
+
+ // xor
+ return (byte)(input ^ engineState[(engineState[x] + engineState[y]) & 0xff]);
+ }
+
+ public virtual void ProcessBytes(
+ byte[] input,
+ int inOff,
+ int length,
+ byte[] output,
+ int outOff)
+ {
+ Check.DataLength(input, inOff, length, "input buffer too short");
+ Check.OutputLength(output, outOff, length, "output buffer too short");
+
+ for (int i = 0; i < length ; i++)
+ {
+ x = (x + 1) & 0xff;
+ y = (engineState[x] + y) & 0xff;
+
+ // swap
+ byte tmp = engineState[x];
+ engineState[x] = engineState[y];
+ engineState[y] = tmp;
+
+ // xor
+ output[i+outOff] = (byte)(input[i + inOff]
+ ^ engineState[(engineState[x] + engineState[y]) & 0xff]);
+ }
+ }
+
+ public virtual void Reset()
+ {
+ SetKey(workingKey);
+ }
+
+ // Private implementation
+
+ private void SetKey(
+ byte[] keyBytes)
+ {
+ workingKey = keyBytes;
+
+ // System.out.println("the key length is ; "+ workingKey.Length);
+
+ x = 0;
+ y = 0;
+
+ if (engineState == null)
+ {
+ engineState = new byte[STATE_LENGTH];
+ }
+
+ // reset the state of the engine
+ for (int i=0; i < STATE_LENGTH; i++)
+ {
+ engineState[i] = (byte)i;
+ }
+
+ int i1 = 0;
+ int i2 = 0;
+
+ for (int i=0; i < STATE_LENGTH; i++)
+ {
+ i2 = ((keyBytes[i1] & 0xff) + engineState[i] + i2) & 0xff;
+ // do the byte-swap inline
+ byte tmp = engineState[i];
+ engineState[i] = engineState[i2];
+ engineState[i2] = tmp;
+ i1 = (i1+1) % keyBytes.Length;
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC4Engine.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC4Engine.cs.meta
new file mode 100644
index 00000000..f0922824
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC4Engine.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 068d5429f72b08f45a6b2ecde0991212
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC532Engine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC532Engine.cs
new file mode 100644
index 00000000..b0882407
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC532Engine.cs
@@ -0,0 +1,301 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+#if UNITY_WSA && !UNITY_EDITOR && !ENABLE_IL2CPP
+using System.TypeFix;
+#endif
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ /**
+ * The specification for RC5 came from the RC5 Encryption Algorithm
+ * publication in RSA CryptoBytes, Spring of 1995.
+ * http://www.rsasecurity.com/rsalabs/cryptobytes.
+ *
+ * This implementation has a word size of 32 bits.
+ */
+ public class RC532Engine
+ : IBlockCipher
+ {
+ /*
+ * the number of rounds to perform
+ */
+ private int _noRounds;
+
+ /*
+ * the expanded key array of size 2*(rounds + 1)
+ */
+ private int [] _S;
+
+ /*
+ * our "magic constants" for 32 32
+ *
+ * Pw = Odd((e-2) * 2^wordsize)
+ * Qw = Odd((o-2) * 2^wordsize)
+ *
+ * where e is the base of natural logarithms (2.718281828...)
+ * and o is the golden ratio (1.61803398...)
+ */
+ private static readonly int P32 = unchecked((int) 0xb7e15163);
+ private static readonly int Q32 = unchecked((int) 0x9e3779b9);
+
+ private bool forEncryption;
+
+ /**
+ * Create an instance of the RC5 encryption algorithm
+ * and set some defaults
+ */
+ public RC532Engine()
+ {
+ _noRounds = 12; // the default
+// _S = null;
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "RC5-32"; }
+ }
+
+ public virtual bool IsPartialBlockOkay
+ {
+ get { return false; }
+ }
+
+ public virtual int GetBlockSize()
+ {
+ return 2 * 4;
+ }
+
+ /**
+ * initialise a RC5-32 cipher.
+ *
+ * @param forEncryption whether or not we are for encryption.
+ * @param parameters the parameters required to set up the cipher.
+ * @exception ArgumentException if the parameters argument is
+ * inappropriate.
+ */
+ public virtual void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ if (typeof(RC5Parameters).IsInstanceOfType(parameters))
+ {
+ RC5Parameters p = (RC5Parameters)parameters;
+
+ _noRounds = p.Rounds;
+
+ SetKey(p.GetKey());
+ }
+ else if (typeof(KeyParameter).IsInstanceOfType(parameters))
+ {
+ KeyParameter p = (KeyParameter)parameters;
+
+ SetKey(p.GetKey());
+ }
+ else
+ {
+ throw new ArgumentException("invalid parameter passed to RC532 init - " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters));
+ }
+
+ this.forEncryption = forEncryption;
+ }
+
+ public virtual int ProcessBlock(
+ byte[] input,
+ int inOff,
+ byte[] output,
+ int outOff)
+ {
+ return (forEncryption)
+ ? EncryptBlock(input, inOff, output, outOff)
+ : DecryptBlock(input, inOff, output, outOff);
+ }
+
+ public virtual void Reset()
+ {
+ }
+
+ /**
+ * Re-key the cipher.
+ *
+ * @param key the key to be used
+ */
+ private void SetKey(
+ byte[] key)
+ {
+ //
+ // KEY EXPANSION:
+ //
+ // There are 3 phases to the key expansion.
+ //
+ // Phase 1:
+ // Copy the secret key K[0...b-1] into an array L[0..c-1] of
+ // c = ceil(b/u), where u = 32/8 in little-endian order.
+ // In other words, we fill up L using u consecutive key bytes
+ // of K. Any unfilled byte positions in L are zeroed. In the
+ // case that b = c = 0, set c = 1 and L[0] = 0.
+ //
+ int[] L = new int[(key.Length + (4 - 1)) / 4];
+
+ for (int i = 0; i != key.Length; i++)
+ {
+ L[i / 4] += (key[i] & 0xff) << (8 * (i % 4));
+ }
+
+ //
+ // Phase 2:
+ // Initialize S to a particular fixed pseudo-random bit pattern
+ // using an arithmetic progression modulo 2^wordsize determined
+ // by the magic numbers, Pw & Qw.
+ //
+ _S = new int[2*(_noRounds + 1)];
+
+ _S[0] = P32;
+ for (int i=1; i < _S.Length; i++)
+ {
+ _S[i] = (_S[i-1] + Q32);
+ }
+
+ //
+ // Phase 3:
+ // Mix in the user's secret key in 3 passes over the arrays S & L.
+ // The max of the arrays sizes is used as the loop control
+ //
+ int iter;
+
+ if (L.Length > _S.Length)
+ {
+ iter = 3 * L.Length;
+ }
+ else
+ {
+ iter = 3 * _S.Length;
+ }
+
+ int A = 0, B = 0;
+ int ii = 0, jj = 0;
+
+ for (int k = 0; k < iter; k++)
+ {
+ A = _S[ii] = RotateLeft(_S[ii] + A + B, 3);
+ B = L[jj] = RotateLeft( L[jj] + A + B, A+B);
+ ii = (ii+1) % _S.Length;
+ jj = (jj+1) % L.Length;
+ }
+ }
+
+ /**
+ * Encrypt the given block starting at the given offset and place
+ * the result in the provided buffer starting at the given offset.
+ *
+ * @param in in byte buffer containing data to encrypt
+ * @param inOff offset into src buffer
+ * @param out out buffer where encrypted data is written
+ * @param outOff offset into out buffer
+ */
+ private int EncryptBlock(
+ byte[] input,
+ int inOff,
+ byte[] outBytes,
+ int outOff)
+ {
+ int A = BytesToWord(input, inOff) + _S[0];
+ int B = BytesToWord(input, inOff + 4) + _S[1];
+
+ for (int i = 1; i <= _noRounds; i++)
+ {
+ A = RotateLeft(A ^ B, B) + _S[2*i];
+ B = RotateLeft(B ^ A, A) + _S[2*i+1];
+ }
+
+ WordToBytes(A, outBytes, outOff);
+ WordToBytes(B, outBytes, outOff + 4);
+
+ return 2 * 4;
+ }
+
+ private int DecryptBlock(
+ byte[] input,
+ int inOff,
+ byte[] outBytes,
+ int outOff)
+ {
+ int A = BytesToWord(input, inOff);
+ int B = BytesToWord(input, inOff + 4);
+
+ for (int i = _noRounds; i >= 1; i--)
+ {
+ B = RotateRight(B - _S[2*i+1], A) ^ A;
+ A = RotateRight(A - _S[2*i], B) ^ B;
+ }
+
+ WordToBytes(A - _S[0], outBytes, outOff);
+ WordToBytes(B - _S[1], outBytes, outOff + 4);
+
+ return 2 * 4;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+ //
+ // PRIVATE Helper Methods
+ //
+ //////////////////////////////////////////////////////////////
+
+ /**
+ * Perform a left "spin" of the word. The rotation of the given
+ * word x is rotated left by y bits.
+ * Only the lg(32) low-order bits of y
+ * are used to determine the rotation amount. Here it is
+ * assumed that the wordsize used is a power of 2.
+ *
+ * @param x word to rotate
+ * @param y number of bits to rotate % 32
+ */
+ private int RotateLeft(int x, int y) {
+ return ((int) ( (uint) (x << (y & (32-1))) |
+ ((uint) x >> (32 - (y & (32-1)))) )
+ );
+ }
+
+ /**
+ * Perform a right "spin" of the word. The rotation of the given
+ * word x is rotated left by y bits.
+ * Only the lg(32) low-order bits of y
+ * are used to determine the rotation amount. Here it is
+ * assumed that the wordsize used is a power of 2.
+ *
+ * @param x word to rotate
+ * @param y number of bits to rotate % 32
+ */
+ private int RotateRight(int x, int y) {
+ return ((int) ( ((uint) x >> (y & (32-1))) |
+ (uint) (x << (32 - (y & (32-1)))) )
+ );
+ }
+
+ private int BytesToWord(
+ byte[] src,
+ int srcOff)
+ {
+ return (src[srcOff] & 0xff) | ((src[srcOff + 1] & 0xff) << 8)
+ | ((src[srcOff + 2] & 0xff) << 16) | ((src[srcOff + 3] & 0xff) << 24);
+ }
+
+ private void WordToBytes(
+ int word,
+ byte[] dst,
+ int dstOff)
+ {
+ dst[dstOff] = (byte)word;
+ dst[dstOff + 1] = (byte)(word >> 8);
+ dst[dstOff + 2] = (byte)(word >> 16);
+ dst[dstOff + 3] = (byte)(word >> 24);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC532Engine.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC532Engine.cs.meta
new file mode 100644
index 00000000..4017d637
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC532Engine.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 715d03447094f77489e130fd0ae50f48
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC564Engine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC564Engine.cs
new file mode 100644
index 00000000..66e7379b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC564Engine.cs
@@ -0,0 +1,302 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+#if UNITY_WSA && !UNITY_EDITOR && !ENABLE_IL2CPP
+using System.TypeFix;
+#endif
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ /**
+ * The specification for RC5 came from the RC5 Encryption Algorithm
+ * publication in RSA CryptoBytes, Spring of 1995.
+ * http://www.rsasecurity.com/rsalabs/cryptobytes.
+ *
+ * This implementation is set to work with a 64 bit word size.
+ */
+ public class RC564Engine
+ : IBlockCipher
+ {
+ private static readonly int wordSize = 64;
+ private static readonly int bytesPerWord = wordSize / 8;
+
+ /*
+ * the number of rounds to perform
+ */
+ private int _noRounds;
+
+ /*
+ * the expanded key array of size 2*(rounds + 1)
+ */
+ private long [] _S;
+
+ /*
+ * our "magic constants" for wordSize 62
+ *
+ * Pw = Odd((e-2) * 2^wordsize)
+ * Qw = Odd((o-2) * 2^wordsize)
+ *
+ * where e is the base of natural logarithms (2.718281828...)
+ * and o is the golden ratio (1.61803398...)
+ */
+ private static readonly long P64 = unchecked( (long) 0xb7e151628aed2a6bL);
+ private static readonly long Q64 = unchecked( (long) 0x9e3779b97f4a7c15L);
+
+ private bool forEncryption;
+
+ /**
+ * Create an instance of the RC5 encryption algorithm
+ * and set some defaults
+ */
+ public RC564Engine()
+ {
+ _noRounds = 12;
+// _S = null;
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "RC5-64"; }
+ }
+
+ public virtual bool IsPartialBlockOkay
+ {
+ get { return false; }
+ }
+
+ public virtual int GetBlockSize()
+ {
+ return 2 * bytesPerWord;
+ }
+
+ /**
+ * initialise a RC5-64 cipher.
+ *
+ * @param forEncryption whether or not we are for encryption.
+ * @param parameters the parameters required to set up the cipher.
+ * @exception ArgumentException if the parameters argument is
+ * inappropriate.
+ */
+ public virtual void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ if (!(typeof(RC5Parameters).IsInstanceOfType(parameters)))
+ {
+ throw new ArgumentException("invalid parameter passed to RC564 init - " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters));
+ }
+
+ RC5Parameters p = (RC5Parameters)parameters;
+
+ this.forEncryption = forEncryption;
+
+ _noRounds = p.Rounds;
+
+ SetKey(p.GetKey());
+ }
+
+ public virtual int ProcessBlock(
+ byte[] input,
+ int inOff,
+ byte[] output,
+ int outOff)
+ {
+ return (forEncryption) ? EncryptBlock(input, inOff, output, outOff)
+ : DecryptBlock(input, inOff, output, outOff);
+ }
+
+ public virtual void Reset()
+ {
+ }
+
+ /**
+ * Re-key the cipher.
+ *
+ * @param key the key to be used
+ */
+ private void SetKey(
+ byte[] key)
+ {
+ //
+ // KEY EXPANSION:
+ //
+ // There are 3 phases to the key expansion.
+ //
+ // Phase 1:
+ // Copy the secret key K[0...b-1] into an array L[0..c-1] of
+ // c = ceil(b/u), where u = wordSize/8 in little-endian order.
+ // In other words, we fill up L using u consecutive key bytes
+ // of K. Any unfilled byte positions in L are zeroed. In the
+ // case that b = c = 0, set c = 1 and L[0] = 0.
+ //
+ long[] L = new long[(key.Length + (bytesPerWord - 1)) / bytesPerWord];
+
+ for (int i = 0; i != key.Length; i++)
+ {
+ L[i / bytesPerWord] += (long)(key[i] & 0xff) << (8 * (i % bytesPerWord));
+ }
+
+ //
+ // Phase 2:
+ // Initialize S to a particular fixed pseudo-random bit pattern
+ // using an arithmetic progression modulo 2^wordsize determined
+ // by the magic numbers, Pw & Qw.
+ //
+ _S = new long[2*(_noRounds + 1)];
+
+ _S[0] = P64;
+ for (int i=1; i < _S.Length; i++)
+ {
+ _S[i] = (_S[i-1] + Q64);
+ }
+
+ //
+ // Phase 3:
+ // Mix in the user's secret key in 3 passes over the arrays S & L.
+ // The max of the arrays sizes is used as the loop control
+ //
+ int iter;
+
+ if (L.Length > _S.Length)
+ {
+ iter = 3 * L.Length;
+ }
+ else
+ {
+ iter = 3 * _S.Length;
+ }
+
+ long A = 0, B = 0;
+ int ii = 0, jj = 0;
+
+ for (int k = 0; k < iter; k++)
+ {
+ A = _S[ii] = RotateLeft(_S[ii] + A + B, 3);
+ B = L[jj] = RotateLeft( L[jj] + A + B, A+B);
+ ii = (ii+1) % _S.Length;
+ jj = (jj+1) % L.Length;
+ }
+ }
+
+ /**
+ * Encrypt the given block starting at the given offset and place
+ * the result in the provided buffer starting at the given offset.
+ *
+ * @param in in byte buffer containing data to encrypt
+ * @param inOff offset into src buffer
+ * @param out out buffer where encrypted data is written
+ * @param outOff offset into out buffer
+ */
+ private int EncryptBlock(
+ byte[] input,
+ int inOff,
+ byte[] outBytes,
+ int outOff)
+ {
+ long A = BytesToWord(input, inOff) + _S[0];
+ long B = BytesToWord(input, inOff + bytesPerWord) + _S[1];
+
+ for (int i = 1; i <= _noRounds; i++)
+ {
+ A = RotateLeft(A ^ B, B) + _S[2*i];
+ B = RotateLeft(B ^ A, A) + _S[2*i+1];
+ }
+
+ WordToBytes(A, outBytes, outOff);
+ WordToBytes(B, outBytes, outOff + bytesPerWord);
+
+ return 2 * bytesPerWord;
+ }
+
+ private int DecryptBlock(
+ byte[] input,
+ int inOff,
+ byte[] outBytes,
+ int outOff)
+ {
+ long A = BytesToWord(input, inOff);
+ long B = BytesToWord(input, inOff + bytesPerWord);
+
+ for (int i = _noRounds; i >= 1; i--)
+ {
+ B = RotateRight(B - _S[2*i+1], A) ^ A;
+ A = RotateRight(A - _S[2*i], B) ^ B;
+ }
+
+ WordToBytes(A - _S[0], outBytes, outOff);
+ WordToBytes(B - _S[1], outBytes, outOff + bytesPerWord);
+
+ return 2 * bytesPerWord;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+ //
+ // PRIVATE Helper Methods
+ //
+ //////////////////////////////////////////////////////////////
+
+ /**
+ * Perform a left "spin" of the word. The rotation of the given
+ * word x is rotated left by y bits.
+ * Only the lg(wordSize) low-order bits of y
+ * are used to determine the rotation amount. Here it is
+ * assumed that the wordsize used is a power of 2.
+ *
+ * @param x word to rotate
+ * @param y number of bits to rotate % wordSize
+ */
+ private long RotateLeft(long x, long y) {
+ return ((long) ( (ulong) (x << (int) (y & (wordSize-1))) |
+ ((ulong) x >> (int) (wordSize - (y & (wordSize-1)))))
+ );
+ }
+
+ /**
+ * Perform a right "spin" of the word. The rotation of the given
+ * word x is rotated left by y bits.
+ * Only the lg(wordSize) low-order bits of y
+ * are used to determine the rotation amount. Here it is
+ * assumed that the wordsize used is a power of 2.
+ *
+ * @param x word to rotate
+ * @param y number of bits to rotate % wordSize
+ */
+ private long RotateRight(long x, long y) {
+ return ((long) ( ((ulong) x >> (int) (y & (wordSize-1))) |
+ (ulong) (x << (int) (wordSize - (y & (wordSize-1)))))
+ );
+ }
+
+ private long BytesToWord(
+ byte[] src,
+ int srcOff)
+ {
+ long word = 0;
+
+ for (int i = bytesPerWord - 1; i >= 0; i--)
+ {
+ word = (word << 8) + (src[i + srcOff] & 0xff);
+ }
+
+ return word;
+ }
+
+ private void WordToBytes(
+ long word,
+ byte[] dst,
+ int dstOff)
+ {
+ for (int i = 0; i < bytesPerWord; i++)
+ {
+ dst[i + dstOff] = (byte)word;
+ word = (long) ((ulong) word >> 8);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC564Engine.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC564Engine.cs.meta
new file mode 100644
index 00000000..d106eb92
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC564Engine.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: e794bc4a420f67d47924b24a7d3e9fd0
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC6Engine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC6Engine.cs
new file mode 100644
index 00000000..e1ca2d70
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC6Engine.cs
@@ -0,0 +1,365 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ /**
+ * An RC6 engine.
+ */
+ public class RC6Engine
+ : IBlockCipher
+ {
+ private static readonly int wordSize = 32;
+ private static readonly int bytesPerWord = wordSize / 8;
+
+ /*
+ * the number of rounds to perform
+ */
+ private static readonly int _noRounds = 20;
+
+ /*
+ * the expanded key array of size 2*(rounds + 1)
+ */
+ private int [] _S;
+
+ /*
+ * our "magic constants" for wordSize 32
+ *
+ * Pw = Odd((e-2) * 2^wordsize)
+ * Qw = Odd((o-2) * 2^wordsize)
+ *
+ * where e is the base of natural logarithms (2.718281828...)
+ * and o is the golden ratio (1.61803398...)
+ */
+ private static readonly int P32 = unchecked((int) 0xb7e15163);
+ private static readonly int Q32 = unchecked((int) 0x9e3779b9);
+
+ private static readonly int LGW = 5; // log2(32)
+
+ private bool forEncryption;
+
+ /**
+ * Create an instance of the RC6 encryption algorithm
+ * and set some defaults
+ */
+ public RC6Engine()
+ {
+// _S = null;
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "RC6"; }
+ }
+
+ public virtual bool IsPartialBlockOkay
+ {
+ get { return false; }
+ }
+
+ public virtual int GetBlockSize()
+ {
+ return 4 * bytesPerWord;
+ }
+
+ /**
+ * initialise a RC5-32 cipher.
+ *
+ * @param forEncryption whether or not we are for encryption.
+ * @param parameters the parameters required to set up the cipher.
+ * @exception ArgumentException if the parameters argument is
+ * inappropriate.
+ */
+ public virtual void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ if (!(parameters is KeyParameter))
+ throw new ArgumentException("invalid parameter passed to RC6 init - " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters));
+
+ this.forEncryption = forEncryption;
+
+ KeyParameter p = (KeyParameter)parameters;
+ SetKey(p.GetKey());
+ }
+
+ public virtual int ProcessBlock(
+ byte[] input,
+ int inOff,
+ byte[] output,
+ int outOff)
+ {
+ int blockSize = GetBlockSize();
+ if (_S == null)
+ throw new InvalidOperationException("RC6 engine not initialised");
+
+ Check.DataLength(input, inOff, blockSize, "input buffer too short");
+ Check.OutputLength(output, outOff, blockSize, "output buffer too short");
+
+ return (forEncryption)
+ ? EncryptBlock(input, inOff, output, outOff)
+ : DecryptBlock(input, inOff, output, outOff);
+ }
+
+ public virtual void Reset()
+ {
+ }
+
+ /**
+ * Re-key the cipher.
+ *
+ * @param inKey the key to be used
+ */
+ private void SetKey(
+ byte[] key)
+ {
+ //
+ // KEY EXPANSION:
+ //
+ // There are 3 phases to the key expansion.
+ //
+ // Phase 1:
+ // Copy the secret key K[0...b-1] into an array L[0..c-1] of
+ // c = ceil(b/u), where u = wordSize/8 in little-endian order.
+ // In other words, we fill up L using u consecutive key bytes
+ // of K. Any unfilled byte positions in L are zeroed. In the
+ // case that b = c = 0, set c = 1 and L[0] = 0.
+ //
+ // compute number of dwords
+ int c = (key.Length + (bytesPerWord - 1)) / bytesPerWord;
+ if (c == 0)
+ {
+ c = 1;
+ }
+ int[] L = new int[(key.Length + bytesPerWord - 1) / bytesPerWord];
+
+ // load all key bytes into array of key dwords
+ for (int i = key.Length - 1; i >= 0; i--)
+ {
+ L[i / bytesPerWord] = (L[i / bytesPerWord] << 8) + (key[i] & 0xff);
+ }
+
+ //
+ // Phase 2:
+ // Key schedule is placed in a array of 2+2*ROUNDS+2 = 44 dwords.
+ // Initialize S to a particular fixed pseudo-random bit pattern
+ // using an arithmetic progression modulo 2^wordsize determined
+ // by the magic numbers, Pw & Qw.
+ //
+ _S = new int[2+2*_noRounds+2];
+
+ _S[0] = P32;
+ for (int i=1; i < _S.Length; i++)
+ {
+ _S[i] = (_S[i-1] + Q32);
+ }
+
+ //
+ // Phase 3:
+ // Mix in the user's secret key in 3 passes over the arrays S & L.
+ // The max of the arrays sizes is used as the loop control
+ //
+ int iter;
+
+ if (L.Length > _S.Length)
+ {
+ iter = 3 * L.Length;
+ }
+ else
+ {
+ iter = 3 * _S.Length;
+ }
+
+ int A = 0;
+ int B = 0;
+ int ii = 0, jj = 0;
+
+ for (int k = 0; k < iter; k++)
+ {
+ A = _S[ii] = RotateLeft(_S[ii] + A + B, 3);
+ B = L[jj] = RotateLeft( L[jj] + A + B, A+B);
+ ii = (ii+1) % _S.Length;
+ jj = (jj+1) % L.Length;
+ }
+ }
+
+ private int EncryptBlock(
+ byte[] input,
+ int inOff,
+ byte[] outBytes,
+ int outOff)
+ {
+ // load A,B,C and D registers from in.
+ int A = BytesToWord(input, inOff);
+ int B = BytesToWord(input, inOff + bytesPerWord);
+ int C = BytesToWord(input, inOff + bytesPerWord*2);
+ int D = BytesToWord(input, inOff + bytesPerWord*3);
+
+ // Do pseudo-round #0: pre-whitening of B and D
+ B += _S[0];
+ D += _S[1];
+
+ // perform round #1,#2 ... #ROUNDS of encryption
+ for (int i = 1; i <= _noRounds; i++)
+ {
+ int t = 0,u = 0;
+
+ t = B*(2*B+1);
+ t = RotateLeft(t,5);
+
+ u = D*(2*D+1);
+ u = RotateLeft(u,5);
+
+ A ^= t;
+ A = RotateLeft(A,u);
+ A += _S[2*i];
+
+ C ^= u;
+ C = RotateLeft(C,t);
+ C += _S[2*i+1];
+
+ int temp = A;
+ A = B;
+ B = C;
+ C = D;
+ D = temp;
+ }
+ // do pseudo-round #(ROUNDS+1) : post-whitening of A and C
+ A += _S[2*_noRounds+2];
+ C += _S[2*_noRounds+3];
+
+ // store A, B, C and D registers to out
+ WordToBytes(A, outBytes, outOff);
+ WordToBytes(B, outBytes, outOff + bytesPerWord);
+ WordToBytes(C, outBytes, outOff + bytesPerWord*2);
+ WordToBytes(D, outBytes, outOff + bytesPerWord*3);
+
+ return 4 * bytesPerWord;
+ }
+
+ private int DecryptBlock(
+ byte[] input,
+ int inOff,
+ byte[] outBytes,
+ int outOff)
+ {
+ // load A,B,C and D registers from out.
+ int A = BytesToWord(input, inOff);
+ int B = BytesToWord(input, inOff + bytesPerWord);
+ int C = BytesToWord(input, inOff + bytesPerWord*2);
+ int D = BytesToWord(input, inOff + bytesPerWord*3);
+
+ // Undo pseudo-round #(ROUNDS+1) : post whitening of A and C
+ C -= _S[2*_noRounds+3];
+ A -= _S[2*_noRounds+2];
+
+ // Undo round #ROUNDS, .., #2,#1 of encryption
+ for (int i = _noRounds; i >= 1; i--)
+ {
+ int t=0,u = 0;
+
+ int temp = D;
+ D = C;
+ C = B;
+ B = A;
+ A = temp;
+
+ t = B*(2*B+1);
+ t = RotateLeft(t, LGW);
+
+ u = D*(2*D+1);
+ u = RotateLeft(u, LGW);
+
+ C -= _S[2*i+1];
+ C = RotateRight(C,t);
+ C ^= u;
+
+ A -= _S[2*i];
+ A = RotateRight(A,u);
+ A ^= t;
+
+ }
+ // Undo pseudo-round #0: pre-whitening of B and D
+ D -= _S[1];
+ B -= _S[0];
+
+ WordToBytes(A, outBytes, outOff);
+ WordToBytes(B, outBytes, outOff + bytesPerWord);
+ WordToBytes(C, outBytes, outOff + bytesPerWord*2);
+ WordToBytes(D, outBytes, outOff + bytesPerWord*3);
+
+ return 4 * bytesPerWord;
+ }
+
+
+ //////////////////////////////////////////////////////////////
+ //
+ // PRIVATE Helper Methods
+ //
+ //////////////////////////////////////////////////////////////
+
+ /**
+ * Perform a left "spin" of the word. The rotation of the given
+ * word x is rotated left by y bits.
+ * Only the lg(wordSize) low-order bits of y
+ * are used to determine the rotation amount. Here it is
+ * assumed that the wordsize used is a power of 2.
+ *
+ * @param x word to rotate
+ * @param y number of bits to rotate % wordSize
+ */
+ private int RotateLeft(int x, int y)
+ {
+ return ((int)((uint)(x << (y & (wordSize-1)))
+ | ((uint) x >> (wordSize - (y & (wordSize-1))))));
+ }
+
+ /**
+ * Perform a right "spin" of the word. The rotation of the given
+ * word x is rotated left by y bits.
+ * Only the lg(wordSize) low-order bits of y
+ * are used to determine the rotation amount. Here it is
+ * assumed that the wordsize used is a power of 2.
+ *
+ * @param x word to rotate
+ * @param y number of bits to rotate % wordSize
+ */
+ private int RotateRight(int x, int y)
+ {
+ return ((int)(((uint) x >> (y & (wordSize-1)))
+ | (uint)(x << (wordSize - (y & (wordSize-1))))));
+ }
+
+ private int BytesToWord(
+ byte[] src,
+ int srcOff)
+ {
+ int word = 0;
+
+ for (int i = bytesPerWord - 1; i >= 0; i--)
+ {
+ word = (word << 8) + (src[i + srcOff] & 0xff);
+ }
+
+ return word;
+ }
+
+ private void WordToBytes(
+ int word,
+ byte[] dst,
+ int dstOff)
+ {
+ for (int i = 0; i < bytesPerWord; i++)
+ {
+ dst[i + dstOff] = (byte)word;
+ word = (int) ((uint) word >> 8);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC6Engine.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC6Engine.cs.meta
new file mode 100644
index 00000000..33490c07
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RC6Engine.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 2b7585edcc7be3146a7550caa7c8678b
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RFC3211WrapEngine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RFC3211WrapEngine.cs
new file mode 100644
index 00000000..69bf4e64
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RFC3211WrapEngine.cs
@@ -0,0 +1,183 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ /**
+ * an implementation of the RFC 3211 Key Wrap
+ * Specification.
+ */
+ public class Rfc3211WrapEngine
+ : IWrapper
+ {
+ private CbcBlockCipher engine;
+ private ParametersWithIV param;
+ private bool forWrapping;
+ private SecureRandom rand;
+
+ public Rfc3211WrapEngine(
+ IBlockCipher engine)
+ {
+ this.engine = new CbcBlockCipher(engine);
+ }
+
+ public virtual void Init(
+ bool forWrapping,
+ ICipherParameters param)
+ {
+ this.forWrapping = forWrapping;
+
+ if (param is ParametersWithRandom)
+ {
+ ParametersWithRandom p = (ParametersWithRandom)param;
+
+ this.rand = p.Random;
+ this.param = p.Parameters as ParametersWithIV;
+ }
+ else
+ {
+ if (forWrapping)
+ {
+ rand = new SecureRandom();
+ }
+
+ this.param = param as ParametersWithIV;
+ }
+
+ if (null == this.param)
+ throw new ArgumentException("RFC3211Wrap requires an IV", "param");
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return engine.GetUnderlyingCipher().AlgorithmName + "/RFC3211Wrap"; }
+ }
+
+ public virtual byte[] Wrap(
+ byte[] inBytes,
+ int inOff,
+ int inLen)
+ {
+ if (!forWrapping)
+ throw new InvalidOperationException("not set for wrapping");
+ if (inLen > 255 || inLen < 0)
+ throw new ArgumentException("input must be from 0 to 255 bytes", "inLen");
+
+ engine.Init(true, param);
+
+ int blockSize = engine.GetBlockSize();
+ byte[] cekBlock;
+
+ if (inLen + 4 < blockSize * 2)
+ {
+ cekBlock = new byte[blockSize * 2];
+ }
+ else
+ {
+ cekBlock = new byte[(inLen + 4) % blockSize == 0 ? inLen + 4 : ((inLen + 4) / blockSize + 1) * blockSize];
+ }
+
+ cekBlock[0] = (byte)inLen;
+
+ Array.Copy(inBytes, inOff, cekBlock, 4, inLen);
+
+ rand.NextBytes(cekBlock, inLen + 4, cekBlock.Length - inLen - 4);
+
+ cekBlock[1] = (byte)~cekBlock[4];
+ cekBlock[2] = (byte)~cekBlock[4 + 1];
+ cekBlock[3] = (byte)~cekBlock[4 + 2];
+
+ for (int i = 0; i < cekBlock.Length; i += blockSize)
+ {
+ engine.ProcessBlock(cekBlock, i, cekBlock, i);
+ }
+
+ for (int i = 0; i < cekBlock.Length; i += blockSize)
+ {
+ engine.ProcessBlock(cekBlock, i, cekBlock, i);
+ }
+
+ return cekBlock;
+ }
+
+ public virtual byte[] Unwrap(
+ byte[] inBytes,
+ int inOff,
+ int inLen)
+ {
+ if (forWrapping)
+ {
+ throw new InvalidOperationException("not set for unwrapping");
+ }
+
+ int blockSize = engine.GetBlockSize();
+
+ if (inLen < 2 * blockSize)
+ {
+ throw new InvalidCipherTextException("input too short");
+ }
+
+ byte[] cekBlock = new byte[inLen];
+ byte[] iv = new byte[blockSize];
+
+ Array.Copy(inBytes, inOff, cekBlock, 0, inLen);
+ Array.Copy(inBytes, inOff, iv, 0, iv.Length);
+
+ engine.Init(false, new ParametersWithIV(param.Parameters, iv));
+
+ for (int i = blockSize; i < cekBlock.Length; i += blockSize)
+ {
+ engine.ProcessBlock(cekBlock, i, cekBlock, i);
+ }
+
+ Array.Copy(cekBlock, cekBlock.Length - iv.Length, iv, 0, iv.Length);
+
+ engine.Init(false, new ParametersWithIV(param.Parameters, iv));
+
+ engine.ProcessBlock(cekBlock, 0, cekBlock, 0);
+
+ engine.Init(false, param);
+
+ for (int i = 0; i < cekBlock.Length; i += blockSize)
+ {
+ engine.ProcessBlock(cekBlock, i, cekBlock, i);
+ }
+
+ bool invalidLength = (int)cekBlock[0] > (cekBlock.Length - 4);
+
+ byte[] key;
+ if (invalidLength)
+ {
+ key = new byte[cekBlock.Length - 4];
+ }
+ else
+ {
+ key = new byte[cekBlock[0]];
+ }
+
+ Array.Copy(cekBlock, 4, key, 0, key.Length);
+
+ // Note: Using constant time comparison
+ int nonEqual = 0;
+ for (int i = 0; i != 3; i++)
+ {
+ byte check = (byte)~cekBlock[1 + i];
+ nonEqual |= (check ^ cekBlock[4 + i]);
+ }
+
+ Array.Clear(cekBlock, 0, cekBlock.Length);
+
+ if (nonEqual != 0 | invalidLength)
+ throw new InvalidCipherTextException("wrapped key corrupted");
+
+ return key;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RFC3211WrapEngine.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RFC3211WrapEngine.cs.meta
new file mode 100644
index 00000000..c182dc04
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RFC3211WrapEngine.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: e6aba8788322b964490eefbb8c3d6208
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RFC3394WrapEngine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RFC3394WrapEngine.cs
new file mode 100644
index 00000000..34a55448
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RFC3394WrapEngine.cs
@@ -0,0 +1,182 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ ///
+ /// An implementation of the AES Key Wrapper from the NIST Key Wrap
+ /// Specification as described in RFC 3394.
+ ///
+ /// For further details see: http://www.ietf.org/rfc/rfc3394.txt
+ /// and http://csrc.nist.gov/encryption/kms/key-wrap.pdf.
+ ///
+ public class Rfc3394WrapEngine
+ : IWrapper
+ {
+ private readonly IBlockCipher engine;
+
+ private KeyParameter param;
+ private bool forWrapping;
+
+ private byte[] iv =
+ {
+ 0xa6, 0xa6, 0xa6, 0xa6,
+ 0xa6, 0xa6, 0xa6, 0xa6
+ };
+
+ public Rfc3394WrapEngine(
+ IBlockCipher engine)
+ {
+ this.engine = engine;
+ }
+
+ public virtual void Init(
+ bool forWrapping,
+ ICipherParameters parameters)
+ {
+ this.forWrapping = forWrapping;
+
+ if (parameters is ParametersWithRandom)
+ {
+ parameters = ((ParametersWithRandom) parameters).Parameters;
+ }
+
+ if (parameters is KeyParameter)
+ {
+ this.param = (KeyParameter) parameters;
+ }
+ else if (parameters is ParametersWithIV)
+ {
+ ParametersWithIV pIV = (ParametersWithIV) parameters;
+ byte[] iv = pIV.GetIV();
+
+ if (iv.Length != 8)
+ throw new ArgumentException("IV length not equal to 8", "parameters");
+
+ this.iv = iv;
+ this.param = (KeyParameter) pIV.Parameters;
+ }
+ else
+ {
+ // TODO Throw an exception for bad parameters?
+ }
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return engine.AlgorithmName; }
+ }
+
+ public virtual byte[] Wrap(
+ byte[] input,
+ int inOff,
+ int inLen)
+ {
+ if (!forWrapping)
+ {
+ throw new InvalidOperationException("not set for wrapping");
+ }
+
+ int n = inLen / 8;
+
+ if ((n * 8) != inLen)
+ {
+ throw new DataLengthException("wrap data must be a multiple of 8 bytes");
+ }
+
+ byte[] block = new byte[inLen + iv.Length];
+ byte[] buf = new byte[8 + iv.Length];
+
+ Array.Copy(iv, 0, block, 0, iv.Length);
+ Array.Copy(input, inOff, block, iv.Length, inLen);
+
+ engine.Init(true, param);
+
+ for (int j = 0; j != 6; j++)
+ {
+ for (int i = 1; i <= n; i++)
+ {
+ Array.Copy(block, 0, buf, 0, iv.Length);
+ Array.Copy(block, 8 * i, buf, iv.Length, 8);
+ engine.ProcessBlock(buf, 0, buf, 0);
+
+ int t = n * j + i;
+ for (int k = 1; t != 0; k++)
+ {
+ byte v = (byte)t;
+
+ buf[iv.Length - k] ^= v;
+ t = (int) ((uint)t >> 8);
+ }
+
+ Array.Copy(buf, 0, block, 0, 8);
+ Array.Copy(buf, 8, block, 8 * i, 8);
+ }
+ }
+
+ return block;
+ }
+
+ public virtual byte[] Unwrap(
+ byte[] input,
+ int inOff,
+ int inLen)
+ {
+ if (forWrapping)
+ {
+ throw new InvalidOperationException("not set for unwrapping");
+ }
+
+ int n = inLen / 8;
+
+ if ((n * 8) != inLen)
+ {
+ throw new InvalidCipherTextException("unwrap data must be a multiple of 8 bytes");
+ }
+
+ byte[] block = new byte[inLen - iv.Length];
+ byte[] a = new byte[iv.Length];
+ byte[] buf = new byte[8 + iv.Length];
+
+ Array.Copy(input, inOff, a, 0, iv.Length);
+ Array.Copy(input, inOff + iv.Length, block, 0, inLen - iv.Length);
+
+ engine.Init(false, param);
+
+ n = n - 1;
+
+ for (int j = 5; j >= 0; j--)
+ {
+ for (int i = n; i >= 1; i--)
+ {
+ Array.Copy(a, 0, buf, 0, iv.Length);
+ Array.Copy(block, 8 * (i - 1), buf, iv.Length, 8);
+
+ int t = n * j + i;
+ for (int k = 1; t != 0; k++)
+ {
+ byte v = (byte)t;
+
+ buf[iv.Length - k] ^= v;
+ t = (int) ((uint)t >> 8);
+ }
+
+ engine.ProcessBlock(buf, 0, buf, 0);
+ Array.Copy(buf, 0, a, 0, 8);
+ Array.Copy(buf, 8, block, 8 * (i - 1), 8);
+ }
+ }
+
+ if (!Arrays.ConstantTimeAreEqual(a, iv))
+ throw new InvalidCipherTextException("checksum failed");
+
+ return block;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RFC3394WrapEngine.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RFC3394WrapEngine.cs.meta
new file mode 100644
index 00000000..b6a42f0a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RFC3394WrapEngine.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 7e321866e73515648bfd4569ca4b8573
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RSABlindedEngine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RSABlindedEngine.cs
new file mode 100644
index 00000000..db1a0edb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RSABlindedEngine.cs
@@ -0,0 +1,143 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ /**
+ * this does your basic RSA algorithm with blinding
+ */
+ public class RsaBlindedEngine
+ : IAsymmetricBlockCipher
+ {
+ private readonly IRsa core;
+
+ private RsaKeyParameters key;
+ private SecureRandom random;
+
+ public RsaBlindedEngine()
+ : this(new RsaCoreEngine())
+ {
+ }
+
+ public RsaBlindedEngine(IRsa rsa)
+ {
+ this.core = rsa;
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "RSA"; }
+ }
+
+ /**
+ * initialise the RSA engine.
+ *
+ * @param forEncryption true if we are encrypting, false otherwise.
+ * @param param the necessary RSA key parameters.
+ */
+ public virtual void Init(
+ bool forEncryption,
+ ICipherParameters param)
+ {
+ core.Init(forEncryption, param);
+
+ if (param is ParametersWithRandom)
+ {
+ ParametersWithRandom rParam = (ParametersWithRandom)param;
+
+ key = (RsaKeyParameters)rParam.Parameters;
+ random = rParam.Random;
+ }
+ else
+ {
+ key = (RsaKeyParameters)param;
+ random = new SecureRandom();
+ }
+ }
+
+ /**
+ * Return the maximum size for an input block to this engine.
+ * For RSA this is always one byte less than the key size on
+ * encryption, and the same length as the key size on decryption.
+ *
+ * @return maximum size for an input block.
+ */
+ public virtual int GetInputBlockSize()
+ {
+ return core.GetInputBlockSize();
+ }
+
+ /**
+ * Return the maximum size for an output block to this engine.
+ * For RSA this is always one byte less than the key size on
+ * decryption, and the same length as the key size on encryption.
+ *
+ * @return maximum size for an output block.
+ */
+ public virtual int GetOutputBlockSize()
+ {
+ return core.GetOutputBlockSize();
+ }
+
+ /**
+ * Process a single block using the basic RSA algorithm.
+ *
+ * @param inBuf the input array.
+ * @param inOff the offset into the input buffer where the data starts.
+ * @param inLen the length of the data to be processed.
+ * @return the result of the RSA process.
+ * @exception DataLengthException the input block is too large.
+ */
+ public virtual byte[] ProcessBlock(
+ byte[] inBuf,
+ int inOff,
+ int inLen)
+ {
+ if (key == null)
+ throw new InvalidOperationException("RSA engine not initialised");
+
+ BigInteger input = core.ConvertInput(inBuf, inOff, inLen);
+
+ BigInteger result;
+ if (key is RsaPrivateCrtKeyParameters)
+ {
+ RsaPrivateCrtKeyParameters k = (RsaPrivateCrtKeyParameters)key;
+ BigInteger e = k.PublicExponent;
+ if (e != null) // can't do blinding without a public exponent
+ {
+ BigInteger m = k.Modulus;
+ BigInteger r = BigIntegers.CreateRandomInRange(
+ BigInteger.One, m.Subtract(BigInteger.One), random);
+
+ BigInteger blindedInput = r.ModPow(e, m).Multiply(input).Mod(m);
+ BigInteger blindedResult = core.ProcessBlock(blindedInput);
+
+ BigInteger rInv = r.ModInverse(m);
+ result = blindedResult.Multiply(rInv).Mod(m);
+
+ // defence against Arjen Lenstra�s CRT attack
+ if (!input.Equals(result.ModPow(e, m)))
+ throw new InvalidOperationException("RSA engine faulty decryption/signing detected");
+ }
+ else
+ {
+ result = core.ProcessBlock(input);
+ }
+ }
+ else
+ {
+ result = core.ProcessBlock(input);
+ }
+
+ return core.ConvertOutput(result);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RSABlindedEngine.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RSABlindedEngine.cs.meta
new file mode 100644
index 00000000..3c7983a7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RSABlindedEngine.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 85f59d14d3e55564aa1645a62950ed19
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RSABlindingEngine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RSABlindingEngine.cs
new file mode 100644
index 00000000..80a09682
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RSABlindingEngine.cs
@@ -0,0 +1,153 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ /**
+ * This does your basic RSA Chaum's blinding and unblinding as outlined in
+ * "Handbook of Applied Cryptography", page 475. You need to use this if you are
+ * trying to get another party to generate signatures without them being aware
+ * of the message they are signing.
+ */
+ public class RsaBlindingEngine
+ : IAsymmetricBlockCipher
+ {
+ private readonly IRsa core;
+
+ private RsaKeyParameters key;
+ private BigInteger blindingFactor;
+
+ private bool forEncryption;
+
+ public RsaBlindingEngine()
+ : this(new RsaCoreEngine())
+ {
+ }
+
+ public RsaBlindingEngine(IRsa rsa)
+ {
+ this.core = rsa;
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "RSA"; }
+ }
+
+ /**
+ * Initialise the blinding engine.
+ *
+ * @param forEncryption true if we are encrypting (blinding), false otherwise.
+ * @param param the necessary RSA key parameters.
+ */
+ public virtual void Init(
+ bool forEncryption,
+ ICipherParameters param)
+ {
+ RsaBlindingParameters p;
+
+ if (param is ParametersWithRandom)
+ {
+ ParametersWithRandom rParam = (ParametersWithRandom)param;
+
+ p = (RsaBlindingParameters)rParam.Parameters;
+ }
+ else
+ {
+ p = (RsaBlindingParameters)param;
+ }
+
+ core.Init(forEncryption, p.PublicKey);
+
+ this.forEncryption = forEncryption;
+ this.key = p.PublicKey;
+ this.blindingFactor = p.BlindingFactor;
+ }
+
+ /**
+ * Return the maximum size for an input block to this engine.
+ * For RSA this is always one byte less than the key size on
+ * encryption, and the same length as the key size on decryption.
+ *
+ * @return maximum size for an input block.
+ */
+ public virtual int GetInputBlockSize()
+ {
+ return core.GetInputBlockSize();
+ }
+
+ /**
+ * Return the maximum size for an output block to this engine.
+ * For RSA this is always one byte less than the key size on
+ * decryption, and the same length as the key size on encryption.
+ *
+ * @return maximum size for an output block.
+ */
+ public virtual int GetOutputBlockSize()
+ {
+ return core.GetOutputBlockSize();
+ }
+
+ /**
+ * Process a single block using the RSA blinding algorithm.
+ *
+ * @param in the input array.
+ * @param inOff the offset into the input buffer where the data starts.
+ * @param inLen the length of the data to be processed.
+ * @return the result of the RSA process.
+ * @throws DataLengthException the input block is too large.
+ */
+ public virtual byte[] ProcessBlock(
+ byte[] inBuf,
+ int inOff,
+ int inLen)
+ {
+ BigInteger msg = core.ConvertInput(inBuf, inOff, inLen);
+
+ if (forEncryption)
+ {
+ msg = BlindMessage(msg);
+ }
+ else
+ {
+ msg = UnblindMessage(msg);
+ }
+
+ return core.ConvertOutput(msg);
+ }
+
+ /*
+ * Blind message with the blind factor.
+ */
+ private BigInteger BlindMessage(
+ BigInteger msg)
+ {
+ BigInteger blindMsg = blindingFactor;
+ blindMsg = msg.Multiply(blindMsg.ModPow(key.Exponent, key.Modulus));
+ blindMsg = blindMsg.Mod(key.Modulus);
+
+ return blindMsg;
+ }
+
+ /*
+ * Unblind the message blinded with the blind factor.
+ */
+ private BigInteger UnblindMessage(
+ BigInteger blindedMsg)
+ {
+ BigInteger m = key.Modulus;
+ BigInteger msg = blindedMsg;
+ BigInteger blindFactorInverse = blindingFactor.ModInverse(m);
+ msg = msg.Multiply(blindFactorInverse);
+ msg = msg.Mod(m);
+
+ return msg;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RSABlindingEngine.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RSABlindingEngine.cs.meta
new file mode 100644
index 00000000..316a751c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RSABlindingEngine.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a223950200657314d88493a524185ba2
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RSACoreEngine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RSACoreEngine.cs
new file mode 100644
index 00000000..112536b7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RSACoreEngine.cs
@@ -0,0 +1,177 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ /**
+ * this does your basic RSA algorithm.
+ */
+ public class RsaCoreEngine
+ : IRsa
+ {
+ private RsaKeyParameters key;
+ private bool forEncryption;
+ private int bitSize;
+
+ private void CheckInitialised()
+ {
+ if (key == null)
+ throw new InvalidOperationException("RSA engine not initialised");
+ }
+
+ /**
+ * initialise the RSA engine.
+ *
+ * @param forEncryption true if we are encrypting, false otherwise.
+ * @param param the necessary RSA key parameters.
+ */
+ public virtual void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ if (parameters is ParametersWithRandom)
+ {
+ parameters = ((ParametersWithRandom) parameters).Parameters;
+ }
+
+ if (!(parameters is RsaKeyParameters))
+ throw new InvalidKeyException("Not an RSA key");
+
+ this.key = (RsaKeyParameters) parameters;
+ this.forEncryption = forEncryption;
+ this.bitSize = key.Modulus.BitLength;
+ }
+
+ /**
+ * Return the maximum size for an input block to this engine.
+ * For RSA this is always one byte less than the key size on
+ * encryption, and the same length as the key size on decryption.
+ *
+ * @return maximum size for an input block.
+ */
+ public virtual int GetInputBlockSize()
+ {
+ CheckInitialised();
+
+ if (forEncryption)
+ {
+ return (bitSize - 1) / 8;
+ }
+
+ return (bitSize + 7) / 8;
+ }
+
+ /**
+ * Return the maximum size for an output block to this engine.
+ * For RSA this is always one byte less than the key size on
+ * decryption, and the same length as the key size on encryption.
+ *
+ * @return maximum size for an output block.
+ */
+ public virtual int GetOutputBlockSize()
+ {
+ CheckInitialised();
+
+ if (forEncryption)
+ {
+ return (bitSize + 7) / 8;
+ }
+
+ return (bitSize - 1) / 8;
+ }
+
+ public virtual BigInteger ConvertInput(
+ byte[] inBuf,
+ int inOff,
+ int inLen)
+ {
+ CheckInitialised();
+
+ int maxLength = (bitSize + 7) / 8;
+
+ if (inLen > maxLength)
+ throw new DataLengthException("input too large for RSA cipher.");
+
+ BigInteger input = new BigInteger(1, inBuf, inOff, inLen);
+
+ if (input.CompareTo(key.Modulus) >= 0)
+ throw new DataLengthException("input too large for RSA cipher.");
+
+ return input;
+ }
+
+ public virtual byte[] ConvertOutput(
+ BigInteger result)
+ {
+ CheckInitialised();
+
+ byte[] output = result.ToByteArrayUnsigned();
+
+ if (forEncryption)
+ {
+ int outSize = GetOutputBlockSize();
+
+ // TODO To avoid this, create version of BigInteger.ToByteArray that
+ // writes to an existing array
+ if (output.Length < outSize) // have ended up with less bytes than normal, lengthen
+ {
+ byte[] tmp = new byte[outSize];
+ output.CopyTo(tmp, tmp.Length - output.Length);
+ output = tmp;
+ }
+ }
+
+ return output;
+ }
+
+ public virtual BigInteger ProcessBlock(
+ BigInteger input)
+ {
+ CheckInitialised();
+
+ if (key is RsaPrivateCrtKeyParameters)
+ {
+ //
+ // we have the extra factors, use the Chinese Remainder Theorem - the author
+ // wishes to express his thanks to Dirk Bonekaemper at rtsffm.com for
+ // advice regarding the expression of this.
+ //
+ RsaPrivateCrtKeyParameters crtKey = (RsaPrivateCrtKeyParameters)key;
+
+ BigInteger p = crtKey.P;
+ BigInteger q = crtKey.Q;
+ BigInteger dP = crtKey.DP;
+ BigInteger dQ = crtKey.DQ;
+ BigInteger qInv = crtKey.QInv;
+
+ BigInteger mP, mQ, h, m;
+
+ // mP = ((input Mod p) ^ dP)) Mod p
+ mP = (input.Remainder(p)).ModPow(dP, p);
+
+ // mQ = ((input Mod q) ^ dQ)) Mod q
+ mQ = (input.Remainder(q)).ModPow(dQ, q);
+
+ // h = qInv * (mP - mQ) Mod p
+ h = mP.Subtract(mQ);
+ h = h.Multiply(qInv);
+ h = h.Mod(p); // Mod (in Java) returns the positive residual
+
+ // m = h * q + mQ
+ m = h.Multiply(q);
+ m = m.Add(mQ);
+
+ return m;
+ }
+
+ return input.ModPow(key.Exponent, key.Modulus);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RSACoreEngine.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RSACoreEngine.cs.meta
new file mode 100644
index 00000000..94af5eb8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RSACoreEngine.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: e5746cae08e3e594fb68d786851c04ea
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RijndaelEngine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RijndaelEngine.cs
new file mode 100644
index 00000000..6153bc60
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/RijndaelEngine.cs
@@ -0,0 +1,745 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+#if UNITY_WSA && !UNITY_EDITOR && !ENABLE_IL2CPP
+using System.TypeFix;
+#endif
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ /**
+ * an implementation of Rijndael, based on the documentation and reference implementation
+ * by Paulo Barreto, Vincent Rijmen, for v2.0 August '99.
+ *
+ * Note: this implementation is based on information prior to readonly NIST publication.
+ *
+ * For further details see:
+ * http://fp.gladman.plus.com/cryptography_technology/serpent/
+ *
+ */
+
+ /* Partially optimised Serpent S Box boolean functions derived */
+ /* using a recursive descent analyser but without a full search */
+ /* of all subtrees. This set of S boxes is the result of work */
+ /* by Sam Simpson and Brian Gladman using the spare time on a */
+ /* cluster of high capacity servers to search for S boxes with */
+ /* this customised search engine. There are now an average of */
+ /* 15.375 terms per S box. */
+ /* */
+ /* Copyright: Dr B. R Gladman (gladman@seven77.demon.co.uk) */
+ /* and Sam Simpson (s.simpson@mia.co.uk) */
+ /* 17th December 1998 */
+ /* */
+ /* We hereby give permission for information in this file to be */
+ /* used freely subject only to acknowledgement of its origin. */
+
+ /*
+ * S0 - { 3, 8,15, 1,10, 6, 5,11,14,13, 4, 2, 7, 0, 9,12 } - 15 terms.
+ */
+ protected void Sb0(int a, int b, int c, int d)
+ {
+ int t1 = a ^ d;
+ int t3 = c ^ t1;
+ int t4 = b ^ t3;
+ X3 = (a & d) ^ t4;
+ int t7 = a ^ (b & t1);
+ X2 = t4 ^ (c | t7);
+ int t12 = X3 & (t3 ^ t7);
+ X1 = (~t3) ^ t12;
+ X0 = t12 ^ (~t7);
+ }
+
+ /**
+ * InvSO - {13, 3,11, 0,10, 6, 5,12, 1,14, 4, 7,15, 9, 8, 2 } - 15 terms.
+ */
+ protected void Ib0(int a, int b, int c, int d)
+ {
+ int t1 = ~a;
+ int t2 = a ^ b;
+ int t4 = d ^ (t1 | t2);
+ int t5 = c ^ t4;
+ X2 = t2 ^ t5;
+ int t8 = t1 ^ (d & t2);
+ X1 = t4 ^ (X2 & t8);
+ X3 = (a & t4) ^ (t5 | X1);
+ X0 = X3 ^ (t5 ^ t8);
+ }
+
+ /**
+ * S1 - {15,12, 2, 7, 9, 0, 5,10, 1,11,14, 8, 6,13, 3, 4 } - 14 terms.
+ */
+ protected void Sb1(int a, int b, int c, int d)
+ {
+ int t2 = b ^ (~a);
+ int t5 = c ^ (a | t2);
+ X2 = d ^ t5;
+ int t7 = b ^ (d | t2);
+ int t8 = t2 ^ X2;
+ X3 = t8 ^ (t5 & t7);
+ int t11 = t5 ^ t7;
+ X1 = X3 ^ t11;
+ X0 = t5 ^ (t8 & t11);
+ }
+
+ /**
+ * InvS1 - { 5, 8, 2,14,15, 6,12, 3,11, 4, 7, 9, 1,13,10, 0 } - 14 steps.
+ */
+ protected void Ib1(int a, int b, int c, int d)
+ {
+ int t1 = b ^ d;
+ int t3 = a ^ (b & t1);
+ int t4 = t1 ^ t3;
+ X3 = c ^ t4;
+ int t7 = b ^ (t1 & t3);
+ int t8 = X3 | t7;
+ X1 = t3 ^ t8;
+ int t10 = ~X1;
+ int t11 = X3 ^ t7;
+ X0 = t10 ^ t11;
+ X2 = t4 ^ (t10 | t11);
+ }
+
+ /**
+ * S2 - { 8, 6, 7, 9, 3,12,10,15,13, 1,14, 4, 0,11, 5, 2 } - 16 terms.
+ */
+ protected void Sb2(int a, int b, int c, int d)
+ {
+ int t1 = ~a;
+ int t2 = b ^ d;
+ int t3 = c & t1;
+ X0 = t2 ^ t3;
+ int t5 = c ^ t1;
+ int t6 = c ^ X0;
+ int t7 = b & t6;
+ X3 = t5 ^ t7;
+ X2 = a ^ ((d | t7) & (X0 | t5));
+ X1 = (t2 ^ X3) ^ (X2 ^ (d | t1));
+ }
+
+ /**
+ * InvS2 - {12, 9,15, 4,11,14, 1, 2, 0, 3, 6,13, 5, 8,10, 7 } - 16 steps.
+ */
+ protected void Ib2(int a, int b, int c, int d)
+ {
+ int t1 = b ^ d;
+ int t2 = ~t1;
+ int t3 = a ^ c;
+ int t4 = c ^ t1;
+ int t5 = b & t4;
+ X0 = t3 ^ t5;
+ int t7 = a | t2;
+ int t8 = d ^ t7;
+ int t9 = t3 | t8;
+ X3 = t1 ^ t9;
+ int t11 = ~t4;
+ int t12 = X0 | X3;
+ X1 = t11 ^ t12;
+ X2 = (d & t11) ^ (t3 ^ t12);
+ }
+
+ /**
+ * S3 - { 0,15,11, 8,12, 9, 6, 3,13, 1, 2, 4,10, 7, 5,14 } - 16 terms.
+ */
+ protected void Sb3(int a, int b, int c, int d)
+ {
+ int t1 = a ^ b;
+ int t2 = a & c;
+ int t3 = a | d;
+ int t4 = c ^ d;
+ int t5 = t1 & t3;
+ int t6 = t2 | t5;
+ X2 = t4 ^ t6;
+ int t8 = b ^ t3;
+ int t9 = t6 ^ t8;
+ int t10 = t4 & t9;
+ X0 = t1 ^ t10;
+ int t12 = X2 & X0;
+ X1 = t9 ^ t12;
+ X3 = (b | d) ^ (t4 ^ t12);
+ }
+
+ /**
+ * InvS3 - { 0, 9,10, 7,11,14, 6,13, 3, 5,12, 2, 4, 8,15, 1 } - 15 terms
+ */
+ protected void Ib3(int a, int b, int c, int d)
+ {
+ int t1 = a | b;
+ int t2 = b ^ c;
+ int t3 = b & t2;
+ int t4 = a ^ t3;
+ int t5 = c ^ t4;
+ int t6 = d | t4;
+ X0 = t2 ^ t6;
+ int t8 = t2 | t6;
+ int t9 = d ^ t8;
+ X2 = t5 ^ t9;
+ int t11 = t1 ^ t9;
+ int t12 = X0 & t11;
+ X3 = t4 ^ t12;
+ X1 = X3 ^ (X0 ^ t11);
+ }
+
+ /**
+ * S4 - { 1,15, 8, 3,12, 0,11, 6, 2, 5, 4,10, 9,14, 7,13 } - 15 terms.
+ */
+ protected void Sb4(int a, int b, int c, int d)
+ {
+ int t1 = a ^ d;
+ int t2 = d & t1;
+ int t3 = c ^ t2;
+ int t4 = b | t3;
+ X3 = t1 ^ t4;
+ int t6 = ~b;
+ int t7 = t1 | t6;
+ X0 = t3 ^ t7;
+ int t9 = a & X0;
+ int t10 = t1 ^ t6;
+ int t11 = t4 & t10;
+ X2 = t9 ^ t11;
+ X1 = (a ^ t3) ^ (t10 & X2);
+ }
+
+ /**
+ * InvS4 - { 5, 0, 8, 3,10, 9, 7,14, 2,12,11, 6, 4,15,13, 1 } - 15 terms.
+ */
+ protected void Ib4(int a, int b, int c, int d)
+ {
+ int t1 = c | d;
+ int t2 = a & t1;
+ int t3 = b ^ t2;
+ int t4 = a & t3;
+ int t5 = c ^ t4;
+ X1 = d ^ t5;
+ int t7 = ~a;
+ int t8 = t5 & X1;
+ X3 = t3 ^ t8;
+ int t10 = X1 | t7;
+ int t11 = d ^ t10;
+ X0 = X3 ^ t11;
+ X2 = (t3 & t11) ^ (X1 ^ t7);
+ }
+
+ /**
+ * S5 - {15, 5, 2,11, 4,10, 9,12, 0, 3,14, 8,13, 6, 7, 1 } - 16 terms.
+ */
+ protected void Sb5(int a, int b, int c, int d)
+ {
+ int t1 = ~a;
+ int t2 = a ^ b;
+ int t3 = a ^ d;
+ int t4 = c ^ t1;
+ int t5 = t2 | t3;
+ X0 = t4 ^ t5;
+ int t7 = d & X0;
+ int t8 = t2 ^ X0;
+ X1 = t7 ^ t8;
+ int t10 = t1 | X0;
+ int t11 = t2 | t7;
+ int t12 = t3 ^ t10;
+ X2 = t11 ^ t12;
+ X3 = (b ^ t7) ^ (X1 & t12);
+ }
+
+ /**
+ * InvS5 - { 8,15, 2, 9, 4, 1,13,14,11, 6, 5, 3, 7,12,10, 0 } - 16 terms.
+ */
+ protected void Ib5(int a, int b, int c, int d)
+ {
+ int t1 = ~c;
+ int t2 = b & t1;
+ int t3 = d ^ t2;
+ int t4 = a & t3;
+ int t5 = b ^ t1;
+ X3 = t4 ^ t5;
+ int t7 = b | X3;
+ int t8 = a & t7;
+ X1 = t3 ^ t8;
+ int t10 = a | d;
+ int t11 = t1 ^ t7;
+ X0 = t10 ^ t11;
+ X2 = (b & t10) ^ (t4 | (a ^ c));
+ }
+
+ /**
+ * S6 - { 7, 2,12, 5, 8, 4, 6,11,14, 9, 1,15,13, 3,10, 0 } - 15 terms.
+ */
+ protected void Sb6(int a, int b, int c, int d)
+ {
+ int t1 = ~a;
+ int t2 = a ^ d;
+ int t3 = b ^ t2;
+ int t4 = t1 | t2;
+ int t5 = c ^ t4;
+ X1 = b ^ t5;
+ int t7 = t2 | X1;
+ int t8 = d ^ t7;
+ int t9 = t5 & t8;
+ X2 = t3 ^ t9;
+ int t11 = t5 ^ t8;
+ X0 = X2 ^ t11;
+ X3 = (~t5) ^ (t3 & t11);
+ }
+
+ /**
+ * InvS6 - {15,10, 1,13, 5, 3, 6, 0, 4, 9,14, 7, 2,12, 8,11 } - 15 terms.
+ */
+ protected void Ib6(int a, int b, int c, int d)
+ {
+ int t1 = ~a;
+ int t2 = a ^ b;
+ int t3 = c ^ t2;
+ int t4 = c | t1;
+ int t5 = d ^ t4;
+ X1 = t3 ^ t5;
+ int t7 = t3 & t5;
+ int t8 = t2 ^ t7;
+ int t9 = b | t8;
+ X3 = t5 ^ t9;
+ int t11 = b | X3;
+ X0 = t8 ^ t11;
+ X2 = (d & t1) ^ (t3 ^ t11);
+ }
+
+ /**
+ * S7 - { 1,13,15, 0,14, 8, 2,11, 7, 4,12,10, 9, 3, 5, 6 } - 16 terms.
+ */
+ protected void Sb7(int a, int b, int c, int d)
+ {
+ int t1 = b ^ c;
+ int t2 = c & t1;
+ int t3 = d ^ t2;
+ int t4 = a ^ t3;
+ int t5 = d | t1;
+ int t6 = t4 & t5;
+ X1 = b ^ t6;
+ int t8 = t3 | X1;
+ int t9 = a & t4;
+ X3 = t1 ^ t9;
+ int t11 = t4 ^ t8;
+ int t12 = X3 & t11;
+ X2 = t3 ^ t12;
+ X0 = (~t11) ^ (X3 & X2);
+ }
+
+ /**
+ * InvS7 - { 3, 0, 6,13, 9,14,15, 8, 5,12,11, 7,10, 1, 4, 2 } - 17 terms.
+ */
+ protected void Ib7(int a, int b, int c, int d)
+ {
+ int t3 = c | (a & b);
+ int t4 = d & (a | b);
+ X3 = t3 ^ t4;
+ int t6 = ~d;
+ int t7 = b ^ t4;
+ int t9 = t7 | (X3 ^ t6);
+ X1 = a ^ t9;
+ X0 = (c ^ t7) ^ (d | X1);
+ X2 = (t3 ^ X1) ^ (X0 ^ (a & X3));
+ }
+
+ /**
+ * Apply the linear transformation to the register set.
+ */
+ protected void LT()
+ {
+ int x0 = RotateLeft(X0, 13);
+ int x2 = RotateLeft(X2, 3);
+ int x1 = X1 ^ x0 ^ x2;
+ int x3 = X3 ^ x2 ^ x0 << 3;
+
+ X1 = RotateLeft(x1, 1);
+ X3 = RotateLeft(x3, 7);
+ X0 = RotateLeft(x0 ^ X1 ^ X3, 5);
+ X2 = RotateLeft(x2 ^ X3 ^ (X1 << 7), 22);
+ }
+
+ /**
+ * Apply the inverse of the linear transformation to the register set.
+ */
+ protected void InverseLT()
+ {
+ int x2 = RotateRight(X2, 22) ^ X3 ^ (X1 << 7);
+ int x0 = RotateRight(X0, 5) ^ X1 ^ X3;
+ int x3 = RotateRight(X3, 7);
+ int x1 = RotateRight(X1, 1);
+ X3 = x3 ^ x2 ^ x0 << 3;
+ X1 = x1 ^ x0 ^ x2;
+ X2 = RotateRight(x2, 3);
+ X0 = RotateRight(x0, 13);
+ }
+
+ protected abstract int[] MakeWorkingKey(byte[] key);
+
+ protected abstract void EncryptBlock(byte[] input, int inOff, byte[] output, int outOff);
+
+ protected abstract void DecryptBlock(byte[] input, int inOff, byte[] output, int outOff);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/SerpentEngineBase.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/SerpentEngineBase.cs.meta
new file mode 100644
index 00000000..047ea6b7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/SerpentEngineBase.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: f164055e1ead4fa418746f4253a72692
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/SkipjackEngine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/SkipjackEngine.cs
new file mode 100644
index 00000000..000161d1
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/SkipjackEngine.cs
@@ -0,0 +1,258 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ /**
+ * a class that provides a basic SKIPJACK engine.
+ */
+ public class SkipjackEngine
+ : IBlockCipher
+ {
+ const int BLOCK_SIZE = 8;
+
+ static readonly short [] ftable =
+ {
+ 0xa3, 0xd7, 0x09, 0x83, 0xf8, 0x48, 0xf6, 0xf4, 0xb3, 0x21, 0x15, 0x78, 0x99, 0xb1, 0xaf, 0xf9,
+ 0xe7, 0x2d, 0x4d, 0x8a, 0xce, 0x4c, 0xca, 0x2e, 0x52, 0x95, 0xd9, 0x1e, 0x4e, 0x38, 0x44, 0x28,
+ 0x0a, 0xdf, 0x02, 0xa0, 0x17, 0xf1, 0x60, 0x68, 0x12, 0xb7, 0x7a, 0xc3, 0xe9, 0xfa, 0x3d, 0x53,
+ 0x96, 0x84, 0x6b, 0xba, 0xf2, 0x63, 0x9a, 0x19, 0x7c, 0xae, 0xe5, 0xf5, 0xf7, 0x16, 0x6a, 0xa2,
+ 0x39, 0xb6, 0x7b, 0x0f, 0xc1, 0x93, 0x81, 0x1b, 0xee, 0xb4, 0x1a, 0xea, 0xd0, 0x91, 0x2f, 0xb8,
+ 0x55, 0xb9, 0xda, 0x85, 0x3f, 0x41, 0xbf, 0xe0, 0x5a, 0x58, 0x80, 0x5f, 0x66, 0x0b, 0xd8, 0x90,
+ 0x35, 0xd5, 0xc0, 0xa7, 0x33, 0x06, 0x65, 0x69, 0x45, 0x00, 0x94, 0x56, 0x6d, 0x98, 0x9b, 0x76,
+ 0x97, 0xfc, 0xb2, 0xc2, 0xb0, 0xfe, 0xdb, 0x20, 0xe1, 0xeb, 0xd6, 0xe4, 0xdd, 0x47, 0x4a, 0x1d,
+ 0x42, 0xed, 0x9e, 0x6e, 0x49, 0x3c, 0xcd, 0x43, 0x27, 0xd2, 0x07, 0xd4, 0xde, 0xc7, 0x67, 0x18,
+ 0x89, 0xcb, 0x30, 0x1f, 0x8d, 0xc6, 0x8f, 0xaa, 0xc8, 0x74, 0xdc, 0xc9, 0x5d, 0x5c, 0x31, 0xa4,
+ 0x70, 0x88, 0x61, 0x2c, 0x9f, 0x0d, 0x2b, 0x87, 0x50, 0x82, 0x54, 0x64, 0x26, 0x7d, 0x03, 0x40,
+ 0x34, 0x4b, 0x1c, 0x73, 0xd1, 0xc4, 0xfd, 0x3b, 0xcc, 0xfb, 0x7f, 0xab, 0xe6, 0x3e, 0x5b, 0xa5,
+ 0xad, 0x04, 0x23, 0x9c, 0x14, 0x51, 0x22, 0xf0, 0x29, 0x79, 0x71, 0x7e, 0xff, 0x8c, 0x0e, 0xe2,
+ 0x0c, 0xef, 0xbc, 0x72, 0x75, 0x6f, 0x37, 0xa1, 0xec, 0xd3, 0x8e, 0x62, 0x8b, 0x86, 0x10, 0xe8,
+ 0x08, 0x77, 0x11, 0xbe, 0x92, 0x4f, 0x24, 0xc5, 0x32, 0x36, 0x9d, 0xcf, 0xf3, 0xa6, 0xbb, 0xac,
+ 0x5e, 0x6c, 0xa9, 0x13, 0x57, 0x25, 0xb5, 0xe3, 0xbd, 0xa8, 0x3a, 0x01, 0x05, 0x59, 0x2a, 0x46
+ };
+
+ private int[] key0, key1, key2, key3;
+ private bool encrypting;
+
+ /**
+ * initialise a SKIPJACK cipher.
+ *
+ * @param forEncryption whether or not we are for encryption.
+ * @param parameters the parameters required to set up the cipher.
+ * @exception ArgumentException if the parameters argument is
+ * inappropriate.
+ */
+ public virtual void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ if (!(parameters is KeyParameter))
+ throw new ArgumentException("invalid parameter passed to SKIPJACK init - " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters));
+
+ byte[] keyBytes = ((KeyParameter)parameters).GetKey();
+
+ this.encrypting = forEncryption;
+ this.key0 = new int[32];
+ this.key1 = new int[32];
+ this.key2 = new int[32];
+ this.key3 = new int[32];
+
+ //
+ // expand the key to 128 bytes in 4 parts (saving us a modulo, multiply
+ // and an addition).
+ //
+ for (int i = 0; i < 32; i ++)
+ {
+ key0[i] = keyBytes[(i * 4) % 10] & 0xff;
+ key1[i] = keyBytes[(i * 4 + 1) % 10] & 0xff;
+ key2[i] = keyBytes[(i * 4 + 2) % 10] & 0xff;
+ key3[i] = keyBytes[(i * 4 + 3) % 10] & 0xff;
+ }
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "SKIPJACK"; }
+ }
+
+ public virtual bool IsPartialBlockOkay
+ {
+ get { return false; }
+ }
+
+ public virtual int GetBlockSize()
+ {
+ return BLOCK_SIZE;
+ }
+
+ public virtual int ProcessBlock(
+ byte[] input,
+ int inOff,
+ byte[] output,
+ int outOff)
+ {
+ if (key1 == null)
+ throw new InvalidOperationException("SKIPJACK engine not initialised");
+
+ Check.DataLength(input, inOff, BLOCK_SIZE, "input buffer too short");
+ Check.OutputLength(output, outOff, BLOCK_SIZE, "output buffer too short");
+
+ if (encrypting)
+ {
+ EncryptBlock(input, inOff, output, outOff);
+ }
+ else
+ {
+ DecryptBlock(input, inOff, output, outOff);
+ }
+
+ return BLOCK_SIZE;
+ }
+
+ public virtual void Reset()
+ {
+ }
+
+ /**
+ * The G permutation
+ */
+ private int G(
+ int k,
+ int w)
+ {
+ int g1, g2, g3, g4, g5, g6;
+
+ g1 = (w >> 8) & 0xff;
+ g2 = w & 0xff;
+
+ g3 = ftable[g2 ^ key0[k]] ^ g1;
+ g4 = ftable[g3 ^ key1[k]] ^ g2;
+ g5 = ftable[g4 ^ key2[k]] ^ g3;
+ g6 = ftable[g5 ^ key3[k]] ^ g4;
+
+ return ((g5 << 8) + g6);
+ }
+
+ public virtual int EncryptBlock(
+ byte[] input,
+ int inOff,
+ byte[] outBytes,
+ int outOff)
+ {
+ int w1 = (input[inOff + 0] << 8) + (input[inOff + 1] & 0xff);
+ int w2 = (input[inOff + 2] << 8) + (input[inOff + 3] & 0xff);
+ int w3 = (input[inOff + 4] << 8) + (input[inOff + 5] & 0xff);
+ int w4 = (input[inOff + 6] << 8) + (input[inOff + 7] & 0xff);
+
+ int k = 0;
+
+ for (int t = 0; t < 2; t++)
+ {
+ for(int i = 0; i < 8; i++)
+ {
+ int tmp = w4;
+ w4 = w3;
+ w3 = w2;
+ w2 = G(k, w1);
+ w1 = w2 ^ tmp ^ (k + 1);
+ k++;
+ }
+
+ for(int i = 0; i < 8; i++)
+ {
+ int tmp = w4;
+ w4 = w3;
+ w3 = w1 ^ w2 ^ (k + 1);
+ w2 = G(k, w1);
+ w1 = tmp;
+ k++;
+ }
+ }
+
+ outBytes[outOff + 0] = (byte)((w1 >> 8));
+ outBytes[outOff + 1] = (byte)(w1);
+ outBytes[outOff + 2] = (byte)((w2 >> 8));
+ outBytes[outOff + 3] = (byte)(w2);
+ outBytes[outOff + 4] = (byte)((w3 >> 8));
+ outBytes[outOff + 5] = (byte)(w3);
+ outBytes[outOff + 6] = (byte)((w4 >> 8));
+ outBytes[outOff + 7] = (byte)(w4);
+
+ return BLOCK_SIZE;
+ }
+
+ /**
+ * the inverse of the G permutation.
+ */
+ private int H(
+ int k,
+ int w)
+ {
+ int h1, h2, h3, h4, h5, h6;
+
+ h1 = w & 0xff;
+ h2 = (w >> 8) & 0xff;
+
+ h3 = ftable[h2 ^ key3[k]] ^ h1;
+ h4 = ftable[h3 ^ key2[k]] ^ h2;
+ h5 = ftable[h4 ^ key1[k]] ^ h3;
+ h6 = ftable[h5 ^ key0[k]] ^ h4;
+
+ return ((h6 << 8) + h5);
+ }
+
+ public virtual int DecryptBlock(
+ byte[] input,
+ int inOff,
+ byte[] outBytes,
+ int outOff)
+ {
+ int w2 = (input[inOff + 0] << 8) + (input[inOff + 1] & 0xff);
+ int w1 = (input[inOff + 2] << 8) + (input[inOff + 3] & 0xff);
+ int w4 = (input[inOff + 4] << 8) + (input[inOff + 5] & 0xff);
+ int w3 = (input[inOff + 6] << 8) + (input[inOff + 7] & 0xff);
+
+ int k = 31;
+
+ for (int t = 0; t < 2; t++)
+ {
+ for(int i = 0; i < 8; i++)
+ {
+ int tmp = w4;
+ w4 = w3;
+ w3 = w2;
+ w2 = H(k, w1);
+ w1 = w2 ^ tmp ^ (k + 1);
+ k--;
+ }
+
+ for(int i = 0; i < 8; i++)
+ {
+ int tmp = w4;
+ w4 = w3;
+ w3 = w1 ^ w2 ^ (k + 1);
+ w2 = H(k, w1);
+ w1 = tmp;
+ k--;
+ }
+ }
+
+ outBytes[outOff + 0] = (byte)((w2 >> 8));
+ outBytes[outOff + 1] = (byte)(w2);
+ outBytes[outOff + 2] = (byte)((w1 >> 8));
+ outBytes[outOff + 3] = (byte)(w1);
+ outBytes[outOff + 4] = (byte)((w4 >> 8));
+ outBytes[outOff + 5] = (byte)(w4);
+ outBytes[outOff + 6] = (byte)((w3 >> 8));
+ outBytes[outOff + 7] = (byte)(w3);
+
+ return BLOCK_SIZE;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/SkipjackEngine.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/SkipjackEngine.cs.meta
new file mode 100644
index 00000000..14ba4236
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/SkipjackEngine.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ee50d237d55d7f9409d3850b96c5a875
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/TEAEngine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/TEAEngine.cs
new file mode 100644
index 00000000..71081aed
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/TEAEngine.cs
@@ -0,0 +1,170 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ /**
+ * An TEA engine.
+ */
+ public class TeaEngine
+ : IBlockCipher
+ {
+ private const int
+ rounds = 32,
+ block_size = 8;
+// key_size = 16,
+
+ private const uint
+ delta = 0x9E3779B9,
+ d_sum = 0xC6EF3720; // sum on decrypt
+
+ /*
+ * the expanded key array of 4 subkeys
+ */
+ private uint _a, _b, _c, _d;
+ private bool _initialised;
+ private bool _forEncryption;
+
+ /**
+ * Create an instance of the TEA encryption algorithm
+ * and set some defaults
+ */
+ public TeaEngine()
+ {
+ _initialised = false;
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "TEA"; }
+ }
+
+ public virtual bool IsPartialBlockOkay
+ {
+ get { return false; }
+ }
+
+ public virtual int GetBlockSize()
+ {
+ return block_size;
+ }
+
+ /**
+ * initialise
+ *
+ * @param forEncryption whether or not we are for encryption.
+ * @param params the parameters required to set up the cipher.
+ * @exception ArgumentException if the params argument is
+ * inappropriate.
+ */
+ public virtual void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ if (!(parameters is KeyParameter))
+ {
+ throw new ArgumentException("invalid parameter passed to TEA init - "
+ + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters));
+ }
+
+ _forEncryption = forEncryption;
+ _initialised = true;
+
+ KeyParameter p = (KeyParameter) parameters;
+
+ setKey(p.GetKey());
+ }
+
+ public virtual int ProcessBlock(
+ byte[] inBytes,
+ int inOff,
+ byte[] outBytes,
+ int outOff)
+ {
+ if (!_initialised)
+ throw new InvalidOperationException(AlgorithmName + " not initialised");
+
+ Check.DataLength(inBytes, inOff, block_size, "input buffer too short");
+ Check.OutputLength(outBytes, outOff, block_size, "output buffer too short");
+
+ return _forEncryption
+ ? encryptBlock(inBytes, inOff, outBytes, outOff)
+ : decryptBlock(inBytes, inOff, outBytes, outOff);
+ }
+
+ public virtual void Reset()
+ {
+ }
+
+ /**
+ * Re-key the cipher.
+ *
+ * @param key the key to be used
+ */
+ private void setKey(
+ byte[] key)
+ {
+ _a = Pack.BE_To_UInt32(key, 0);
+ _b = Pack.BE_To_UInt32(key, 4);
+ _c = Pack.BE_To_UInt32(key, 8);
+ _d = Pack.BE_To_UInt32(key, 12);
+ }
+
+ private int encryptBlock(
+ byte[] inBytes,
+ int inOff,
+ byte[] outBytes,
+ int outOff)
+ {
+ // Pack bytes into integers
+ uint v0 = Pack.BE_To_UInt32(inBytes, inOff);
+ uint v1 = Pack.BE_To_UInt32(inBytes, inOff + 4);
+
+ uint sum = 0;
+
+ for (int i = 0; i != rounds; i++)
+ {
+ sum += delta;
+ v0 += ((v1 << 4) + _a) ^ (v1 + sum) ^ ((v1 >> 5) + _b);
+ v1 += ((v0 << 4) + _c) ^ (v0 + sum) ^ ((v0 >> 5) + _d);
+ }
+
+ Pack.UInt32_To_BE(v0, outBytes, outOff);
+ Pack.UInt32_To_BE(v1, outBytes, outOff + 4);
+
+ return block_size;
+ }
+
+ private int decryptBlock(
+ byte[] inBytes,
+ int inOff,
+ byte[] outBytes,
+ int outOff)
+ {
+ // Pack bytes into integers
+ uint v0 = Pack.BE_To_UInt32(inBytes, inOff);
+ uint v1 = Pack.BE_To_UInt32(inBytes, inOff + 4);
+
+ uint sum = d_sum;
+
+ for (int i = 0; i != rounds; i++)
+ {
+ v1 -= ((v0 << 4) + _c) ^ (v0 + sum) ^ ((v0 >> 5) + _d);
+ v0 -= ((v1 << 4) + _a) ^ (v1 + sum) ^ ((v1 >> 5) + _b);
+ sum -= delta;
+ }
+
+ Pack.UInt32_To_BE(v0, outBytes, outOff);
+ Pack.UInt32_To_BE(v1, outBytes, outOff + 4);
+
+ return block_size;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/TEAEngine.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/TEAEngine.cs.meta
new file mode 100644
index 00000000..5f82aab8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/TEAEngine.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 35dd311c76c77164f9dd915b865c17d6
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/ThreefishEngine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/ThreefishEngine.cs
new file mode 100644
index 00000000..9a672ae9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/ThreefishEngine.cs
@@ -0,0 +1,1495 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ ///
+ /// Implementation of the Threefish tweakable large block cipher in 256, 512 and 1024 bit block
+ /// sizes.
+ ///
+ ///
+ /// This is the 1.3 version of Threefish defined in the Skein hash function submission to the NIST
+ /// SHA-3 competition in October 2010.
+ ///
+ /// Threefish was designed by Niels Ferguson - Stefan Lucks - Bruce Schneier - Doug Whiting - Mihir
+ /// Bellare - Tadayoshi Kohno - Jon Callas - Jesse Walker.
+ ///
+ /// This implementation inlines all round functions, unrolls 8 rounds, and uses 1.2k of static tables
+ /// to speed up key schedule injection.
+ /// 2 x block size state is retained by each cipher instance.
+ ///
+ public class ThreefishEngine
+ : IBlockCipher
+ {
+ ///
+ /// 256 bit block size - Threefish-256
+ ///
+ public const int BLOCKSIZE_256 = 256;
+ ///
+ /// 512 bit block size - Threefish-512
+ ///
+ public const int BLOCKSIZE_512 = 512;
+ ///
+ /// 1024 bit block size - Threefish-1024
+ ///
+ public const int BLOCKSIZE_1024 = 1024;
+
+ /**
+ * Size of the tweak in bytes (always 128 bit/16 bytes)
+ */
+ private const int TWEAK_SIZE_BYTES = 16;
+ private const int TWEAK_SIZE_WORDS = TWEAK_SIZE_BYTES / 8;
+
+ /**
+ * Rounds in Threefish-256
+ */
+ private const int ROUNDS_256 = 72;
+ /**
+ * Rounds in Threefish-512
+ */
+ private const int ROUNDS_512 = 72;
+ /**
+ * Rounds in Threefish-1024
+ */
+ private const int ROUNDS_1024 = 80;
+
+ /**
+ * Max rounds of any of the variants
+ */
+ private const int MAX_ROUNDS = ROUNDS_1024;
+
+ /**
+ * Key schedule parity constant
+ */
+ private const ulong C_240 = 0x1BD11BDAA9FC1A22L;
+
+ /* Pre-calculated modulo arithmetic tables for key schedule lookups */
+ private static readonly int[] MOD9 = new int[MAX_ROUNDS];
+ private static readonly int[] MOD17 = new int[MOD9.Length];
+ private static readonly int[] MOD5 = new int[MOD9.Length];
+ private static readonly int[] MOD3 = new int[MOD9.Length];
+
+ static ThreefishEngine()
+ {
+ for (int i = 0; i < MOD9.Length; i++)
+ {
+ MOD17[i] = i % 17;
+ MOD9[i] = i % 9;
+ MOD5[i] = i % 5;
+ MOD3[i] = i % 3;
+ }
+ }
+
+ /**
+ * Block size in bytes
+ */
+ private readonly int blocksizeBytes;
+
+ /**
+ * Block size in 64 bit words
+ */
+ private readonly int blocksizeWords;
+
+ /**
+ * Buffer for byte oriented processBytes to call internal word API
+ */
+ private readonly ulong[] currentBlock;
+
+ /**
+ * Tweak bytes (2 byte t1,t2, calculated t3 and repeat of t1,t2 for modulo free lookup
+ */
+ private readonly ulong[] t = new ulong[5];
+
+ /**
+ * Key schedule words
+ */
+ private readonly ulong[] kw;
+
+ /**
+ * The internal cipher implementation (varies by blocksize)
+ */
+ private readonly ThreefishCipher cipher;
+
+ private bool forEncryption;
+
+ ///
+ /// Constructs a new Threefish cipher, with a specified block size.
+ ///
+ /// the block size in bits, one of , ,
+ /// .
+ public ThreefishEngine(int blocksizeBits)
+ {
+ this.blocksizeBytes = (blocksizeBits / 8);
+ this.blocksizeWords = (this.blocksizeBytes / 8);
+ this.currentBlock = new ulong[blocksizeWords];
+
+ /*
+ * Provide room for original key words, extended key word and repeat of key words for modulo
+ * free lookup of key schedule words.
+ */
+ this.kw = new ulong[2 * blocksizeWords + 1];
+
+ switch (blocksizeBits)
+ {
+ case BLOCKSIZE_256:
+ cipher = new Threefish256Cipher(kw, t);
+ break;
+ case BLOCKSIZE_512:
+ cipher = new Threefish512Cipher(kw, t);
+ break;
+ case BLOCKSIZE_1024:
+ cipher = new Threefish1024Cipher(kw, t);
+ break;
+ default:
+ throw new ArgumentException(
+ "Invalid blocksize - Threefish is defined with block size of 256, 512, or 1024 bits");
+ }
+ }
+
+ ///
+ /// Initialise the engine.
+ ///
+ /// Initialise for encryption if true, for decryption if false.
+ /// an instance of or (to
+ /// use a 0 tweak)
+ public virtual void Init(bool forEncryption, ICipherParameters parameters)
+ {
+ byte[] keyBytes;
+ byte[] tweakBytes;
+
+ if (parameters is TweakableBlockCipherParameters)
+ {
+ TweakableBlockCipherParameters tParams = (TweakableBlockCipherParameters)parameters;
+ keyBytes = tParams.Key.GetKey();
+ tweakBytes = tParams.Tweak;
+ }
+ else if (parameters is KeyParameter)
+ {
+ keyBytes = ((KeyParameter)parameters).GetKey();
+ tweakBytes = null;
+ }
+ else
+ {
+ throw new ArgumentException("Invalid parameter passed to Threefish init - "
+ + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters));
+ }
+
+ ulong[] keyWords = null;
+ ulong[] tweakWords = null;
+
+ if (keyBytes != null)
+ {
+ if (keyBytes.Length != this.blocksizeBytes)
+ {
+ throw new ArgumentException("Threefish key must be same size as block (" + blocksizeBytes
+ + " bytes)");
+ }
+ keyWords = new ulong[blocksizeWords];
+ for (int i = 0; i < keyWords.Length; i++)
+ {
+ keyWords[i] = BytesToWord(keyBytes, i * 8);
+ }
+ }
+ if (tweakBytes != null)
+ {
+ if (tweakBytes.Length != TWEAK_SIZE_BYTES)
+ {
+ throw new ArgumentException("Threefish tweak must be " + TWEAK_SIZE_BYTES + " bytes");
+ }
+ tweakWords = new ulong[]{BytesToWord(tweakBytes, 0), BytesToWord(tweakBytes, 8)};
+ }
+ Init(forEncryption, keyWords, tweakWords);
+ }
+
+ ///
+ /// Initialise the engine, specifying the key and tweak directly.
+ ///
+ /// the cipher mode.
+ /// the words of the key, or null to use the current key.
+ /// the 2 word (128 bit) tweak, or null to use the current tweak.
+ internal void Init(bool forEncryption, ulong[] key, ulong[] tweak)
+ {
+ this.forEncryption = forEncryption;
+ if (key != null)
+ {
+ SetKey(key);
+ }
+ if (tweak != null)
+ {
+ SetTweak(tweak);
+ }
+ }
+
+ private void SetKey(ulong[] key)
+ {
+ if (key.Length != this.blocksizeWords)
+ {
+ throw new ArgumentException("Threefish key must be same size as block (" + blocksizeWords
+ + " words)");
+ }
+
+ /*
+ * Full subkey schedule is deferred to execution to avoid per cipher overhead (10k for 512,
+ * 20k for 1024).
+ *
+ * Key and tweak word sequences are repeated, and static MOD17/MOD9/MOD5/MOD3 calculations
+ * used, to avoid expensive mod computations during cipher operation.
+ */
+
+ ulong knw = C_240;
+ for (int i = 0; i < blocksizeWords; i++)
+ {
+ kw[i] = key[i];
+ knw = knw ^ kw[i];
+ }
+ kw[blocksizeWords] = knw;
+ Array.Copy(kw, 0, kw, blocksizeWords + 1, blocksizeWords);
+ }
+
+ private void SetTweak(ulong[] tweak)
+ {
+ if (tweak.Length != TWEAK_SIZE_WORDS)
+ {
+ throw new ArgumentException("Tweak must be " + TWEAK_SIZE_WORDS + " words.");
+ }
+
+ /*
+ * Tweak schedule partially repeated to avoid mod computations during cipher operation
+ */
+ t[0] = tweak[0];
+ t[1] = tweak[1];
+ t[2] = t[0] ^ t[1];
+ t[3] = t[0];
+ t[4] = t[1];
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "Threefish-" + (blocksizeBytes * 8); }
+ }
+
+ public virtual bool IsPartialBlockOkay
+ {
+ get { return false; }
+ }
+
+ public virtual int GetBlockSize()
+ {
+ return blocksizeBytes;
+ }
+
+ public virtual void Reset()
+ {
+ }
+
+ public virtual int ProcessBlock(byte[] inBytes, int inOff, byte[] outBytes, int outOff)
+ {
+ if ((outOff + blocksizeBytes) > outBytes.Length)
+ {
+ throw new DataLengthException("Output buffer too short");
+ }
+
+ if ((inOff + blocksizeBytes) > inBytes.Length)
+ {
+ throw new DataLengthException("Input buffer too short");
+ }
+
+ for (int i = 0; i < blocksizeBytes; i += 8)
+ {
+ currentBlock[i >> 3] = BytesToWord(inBytes, inOff + i);
+ }
+ ProcessBlock(this.currentBlock, this.currentBlock);
+ for (int i = 0; i < blocksizeBytes; i += 8)
+ {
+ WordToBytes(this.currentBlock[i >> 3], outBytes, outOff + i);
+ }
+
+ return blocksizeBytes;
+ }
+
+ ///
+ /// Process a block of data represented as 64 bit words.
+ ///
+ /// the number of 8 byte words processed (which will be the same as the block size).
+ /// a block sized buffer of words to process.
+ /// a block sized buffer of words to receive the output of the operation.
+ /// if either the input or output is not block sized
+ /// if this engine is not initialised
+ internal int ProcessBlock(ulong[] inWords, ulong[] outWords)
+ {
+ if (kw[blocksizeWords] == 0)
+ {
+ throw new InvalidOperationException("Threefish engine not initialised");
+ }
+
+ if (inWords.Length != blocksizeWords)
+ {
+ throw new DataLengthException("Input buffer too short");
+ }
+ if (outWords.Length != blocksizeWords)
+ {
+ throw new DataLengthException("Output buffer too short");
+ }
+
+ if (forEncryption)
+ {
+ cipher.EncryptBlock(inWords, outWords);
+ }
+ else
+ {
+ cipher.DecryptBlock(inWords, outWords);
+ }
+
+ return blocksizeWords;
+ }
+
+ ///
+ /// Read a single 64 bit word from input in LSB first order.
+ ///
+ internal static ulong BytesToWord(byte[] bytes, int off)
+ {
+ if ((off + 8) > bytes.Length)
+ {
+ // Help the JIT avoid index checks
+ throw new ArgumentException();
+ }
+
+ ulong word = 0;
+ int index = off;
+
+ word = (bytes[index++] & 0xffUL);
+ word |= (bytes[index++] & 0xffUL) << 8;
+ word |= (bytes[index++] & 0xffUL) << 16;
+ word |= (bytes[index++] & 0xffUL) << 24;
+ word |= (bytes[index++] & 0xffUL) << 32;
+ word |= (bytes[index++] & 0xffUL) << 40;
+ word |= (bytes[index++] & 0xffUL) << 48;
+ word |= (bytes[index++] & 0xffUL) << 56;
+
+ return word;
+ }
+
+ ///
+ /// Write a 64 bit word to output in LSB first order.
+ ///
+ internal static void WordToBytes(ulong word, byte[] bytes, int off)
+ {
+ if ((off + 8) > bytes.Length)
+ {
+ // Help the JIT avoid index checks
+ throw new ArgumentException();
+ }
+ int index = off;
+
+ bytes[index++] = (byte)word;
+ bytes[index++] = (byte)(word >> 8);
+ bytes[index++] = (byte)(word >> 16);
+ bytes[index++] = (byte)(word >> 24);
+ bytes[index++] = (byte)(word >> 32);
+ bytes[index++] = (byte)(word >> 40);
+ bytes[index++] = (byte)(word >> 48);
+ bytes[index++] = (byte)(word >> 56);
+ }
+
+ /**
+ * Rotate left + xor part of the mix operation.
+ */
+ private static ulong RotlXor(ulong x, int n, ulong xor)
+ {
+ return ((x << n) | (x >> (64 - n))) ^ xor;
+ }
+
+ /**
+ * Rotate xor + rotate right part of the unmix operation.
+ */
+ private static ulong XorRotr(ulong x, int n, ulong xor)
+ {
+ ulong xored = x ^ xor;
+ return (xored >> n) | (xored << (64 - n));
+ }
+
+ private abstract class ThreefishCipher
+ {
+ /**
+ * The extended + repeated tweak words
+ */
+ protected readonly ulong[] t;
+ /**
+ * The extended + repeated key words
+ */
+ protected readonly ulong[] kw;
+
+ protected ThreefishCipher(ulong[] kw, ulong[] t)
+ {
+ this.kw = kw;
+ this.t = t;
+ }
+
+ internal abstract void EncryptBlock(ulong[] block, ulong[] outWords);
+
+ internal abstract void DecryptBlock(ulong[] block, ulong[] outWords);
+
+ }
+
+ private sealed class Threefish256Cipher
+ : ThreefishCipher
+ {
+ /**
+ * Mix rotation constants defined in Skein 1.3 specification
+ */
+ private const int ROTATION_0_0 = 14, ROTATION_0_1 = 16;
+ private const int ROTATION_1_0 = 52, ROTATION_1_1 = 57;
+ private const int ROTATION_2_0 = 23, ROTATION_2_1 = 40;
+ private const int ROTATION_3_0 = 5, ROTATION_3_1 = 37;
+
+ private const int ROTATION_4_0 = 25, ROTATION_4_1 = 33;
+ private const int ROTATION_5_0 = 46, ROTATION_5_1 = 12;
+ private const int ROTATION_6_0 = 58, ROTATION_6_1 = 22;
+ private const int ROTATION_7_0 = 32, ROTATION_7_1 = 32;
+
+ public Threefish256Cipher(ulong[] kw, ulong[] t)
+ : base(kw, t)
+ {
+ }
+
+ internal override void EncryptBlock(ulong[] block, ulong[] outWords)
+ {
+ ulong[] kw = this.kw;
+ ulong[] t = this.t;
+ int[] mod5 = MOD5;
+ int[] mod3 = MOD3;
+
+ /* Help the JIT avoid index bounds checks */
+ if (kw.Length != 9)
+ {
+ throw new ArgumentException();
+ }
+ if (t.Length != 5)
+ {
+ throw new ArgumentException();
+ }
+
+ /*
+ * Read 4 words of plaintext data, not using arrays for cipher state
+ */
+ ulong b0 = block[0];
+ ulong b1 = block[1];
+ ulong b2 = block[2];
+ ulong b3 = block[3];
+
+ /*
+ * First subkey injection.
+ */
+ b0 += kw[0];
+ b1 += kw[1] + t[0];
+ b2 += kw[2] + t[1];
+ b3 += kw[3];
+
+ /*
+ * Rounds loop, unrolled to 8 rounds per iteration.
+ *
+ * Unrolling to multiples of 4 avoids the mod 4 check for key injection, and allows
+ * inlining of the permutations, which cycle every of 2 rounds (avoiding array
+ * index/lookup).
+ *
+ * Unrolling to multiples of 8 avoids the mod 8 rotation constant lookup, and allows
+ * inlining constant rotation values (avoiding array index/lookup).
+ */
+
+ for (int d = 1; d < (ROUNDS_256 / 4); d += 2)
+ {
+ int dm5 = mod5[d];
+ int dm3 = mod3[d];
+
+ /*
+ * 4 rounds of mix and permute.
+ *
+ * Permute schedule has a 2 round cycle, so permutes are inlined in the mix
+ * operations in each 4 round block.
+ */
+ b1 = RotlXor(b1, ROTATION_0_0, b0 += b1);
+ b3 = RotlXor(b3, ROTATION_0_1, b2 += b3);
+
+ b3 = RotlXor(b3, ROTATION_1_0, b0 += b3);
+ b1 = RotlXor(b1, ROTATION_1_1, b2 += b1);
+
+ b1 = RotlXor(b1, ROTATION_2_0, b0 += b1);
+ b3 = RotlXor(b3, ROTATION_2_1, b2 += b3);
+
+ b3 = RotlXor(b3, ROTATION_3_0, b0 += b3);
+ b1 = RotlXor(b1, ROTATION_3_1, b2 += b1);
+
+ /*
+ * Subkey injection for first 4 rounds.
+ */
+ b0 += kw[dm5];
+ b1 += kw[dm5 + 1] + t[dm3];
+ b2 += kw[dm5 + 2] + t[dm3 + 1];
+ b3 += kw[dm5 + 3] + (uint)d;
+
+ /*
+ * 4 more rounds of mix/permute
+ */
+ b1 = RotlXor(b1, ROTATION_4_0, b0 += b1);
+ b3 = RotlXor(b3, ROTATION_4_1, b2 += b3);
+
+ b3 = RotlXor(b3, ROTATION_5_0, b0 += b3);
+ b1 = RotlXor(b1, ROTATION_5_1, b2 += b1);
+
+ b1 = RotlXor(b1, ROTATION_6_0, b0 += b1);
+ b3 = RotlXor(b3, ROTATION_6_1, b2 += b3);
+
+ b3 = RotlXor(b3, ROTATION_7_0, b0 += b3);
+ b1 = RotlXor(b1, ROTATION_7_1, b2 += b1);
+
+ /*
+ * Subkey injection for next 4 rounds.
+ */
+ b0 += kw[dm5 + 1];
+ b1 += kw[dm5 + 2] + t[dm3 + 1];
+ b2 += kw[dm5 + 3] + t[dm3 + 2];
+ b3 += kw[dm5 + 4] + (uint)d + 1;
+ }
+
+ /*
+ * Output cipher state.
+ */
+ outWords[0] = b0;
+ outWords[1] = b1;
+ outWords[2] = b2;
+ outWords[3] = b3;
+ }
+
+ internal override void DecryptBlock(ulong[] block, ulong[] state)
+ {
+ ulong[] kw = this.kw;
+ ulong[] t = this.t;
+ int[] mod5 = MOD5;
+ int[] mod3 = MOD3;
+
+ /* Help the JIT avoid index bounds checks */
+ if (kw.Length != 9)
+ {
+ throw new ArgumentException();
+ }
+ if (t.Length != 5)
+ {
+ throw new ArgumentException();
+ }
+
+ ulong b0 = block[0];
+ ulong b1 = block[1];
+ ulong b2 = block[2];
+ ulong b3 = block[3];
+
+ for (int d = (ROUNDS_256 / 4) - 1; d >= 1; d -= 2)
+ {
+ int dm5 = mod5[d];
+ int dm3 = mod3[d];
+
+ /* Reverse key injection for second 4 rounds */
+ b0 -= kw[dm5 + 1];
+ b1 -= kw[dm5 + 2] + t[dm3 + 1];
+ b2 -= kw[dm5 + 3] + t[dm3 + 2];
+ b3 -= kw[dm5 + 4] + (uint)d + 1;
+
+ /* Reverse second 4 mix/permute rounds */
+
+ b3 = XorRotr(b3, ROTATION_7_0, b0);
+ b0 -= b3;
+ b1 = XorRotr(b1, ROTATION_7_1, b2);
+ b2 -= b1;
+
+ b1 = XorRotr(b1, ROTATION_6_0, b0);
+ b0 -= b1;
+ b3 = XorRotr(b3, ROTATION_6_1, b2);
+ b2 -= b3;
+
+ b3 = XorRotr(b3, ROTATION_5_0, b0);
+ b0 -= b3;
+ b1 = XorRotr(b1, ROTATION_5_1, b2);
+ b2 -= b1;
+
+ b1 = XorRotr(b1, ROTATION_4_0, b0);
+ b0 -= b1;
+ b3 = XorRotr(b3, ROTATION_4_1, b2);
+ b2 -= b3;
+
+ /* Reverse key injection for first 4 rounds */
+ b0 -= kw[dm5];
+ b1 -= kw[dm5 + 1] + t[dm3];
+ b2 -= kw[dm5 + 2] + t[dm3 + 1];
+ b3 -= kw[dm5 + 3] + (uint)d;
+
+ /* Reverse first 4 mix/permute rounds */
+ b3 = XorRotr(b3, ROTATION_3_0, b0);
+ b0 -= b3;
+ b1 = XorRotr(b1, ROTATION_3_1, b2);
+ b2 -= b1;
+
+ b1 = XorRotr(b1, ROTATION_2_0, b0);
+ b0 -= b1;
+ b3 = XorRotr(b3, ROTATION_2_1, b2);
+ b2 -= b3;
+
+ b3 = XorRotr(b3, ROTATION_1_0, b0);
+ b0 -= b3;
+ b1 = XorRotr(b1, ROTATION_1_1, b2);
+ b2 -= b1;
+
+ b1 = XorRotr(b1, ROTATION_0_0, b0);
+ b0 -= b1;
+ b3 = XorRotr(b3, ROTATION_0_1, b2);
+ b2 -= b3;
+ }
+
+ /*
+ * First subkey uninjection.
+ */
+ b0 -= kw[0];
+ b1 -= kw[1] + t[0];
+ b2 -= kw[2] + t[1];
+ b3 -= kw[3];
+
+ /*
+ * Output cipher state.
+ */
+ state[0] = b0;
+ state[1] = b1;
+ state[2] = b2;
+ state[3] = b3;
+ }
+
+ }
+
+ private sealed class Threefish512Cipher
+ : ThreefishCipher
+ {
+ /**
+ * Mix rotation constants defined in Skein 1.3 specification
+ */
+ private const int ROTATION_0_0 = 46, ROTATION_0_1 = 36, ROTATION_0_2 = 19, ROTATION_0_3 = 37;
+ private const int ROTATION_1_0 = 33, ROTATION_1_1 = 27, ROTATION_1_2 = 14, ROTATION_1_3 = 42;
+ private const int ROTATION_2_0 = 17, ROTATION_2_1 = 49, ROTATION_2_2 = 36, ROTATION_2_3 = 39;
+ private const int ROTATION_3_0 = 44, ROTATION_3_1 = 9, ROTATION_3_2 = 54, ROTATION_3_3 = 56;
+
+ private const int ROTATION_4_0 = 39, ROTATION_4_1 = 30, ROTATION_4_2 = 34, ROTATION_4_3 = 24;
+ private const int ROTATION_5_0 = 13, ROTATION_5_1 = 50, ROTATION_5_2 = 10, ROTATION_5_3 = 17;
+ private const int ROTATION_6_0 = 25, ROTATION_6_1 = 29, ROTATION_6_2 = 39, ROTATION_6_3 = 43;
+ private const int ROTATION_7_0 = 8, ROTATION_7_1 = 35, ROTATION_7_2 = 56, ROTATION_7_3 = 22;
+
+ internal Threefish512Cipher(ulong[] kw, ulong[] t)
+ : base(kw, t)
+ {
+ }
+
+ internal override void EncryptBlock(ulong[] block, ulong[] outWords)
+ {
+ ulong[] kw = this.kw;
+ ulong[] t = this.t;
+ int[] mod9 = MOD9;
+ int[] mod3 = MOD3;
+
+ /* Help the JIT avoid index bounds checks */
+ if (kw.Length != 17)
+ {
+ throw new ArgumentException();
+ }
+ if (t.Length != 5)
+ {
+ throw new ArgumentException();
+ }
+
+ /*
+ * Read 8 words of plaintext data, not using arrays for cipher state
+ */
+ ulong b0 = block[0];
+ ulong b1 = block[1];
+ ulong b2 = block[2];
+ ulong b3 = block[3];
+ ulong b4 = block[4];
+ ulong b5 = block[5];
+ ulong b6 = block[6];
+ ulong b7 = block[7];
+
+ /*
+ * First subkey injection.
+ */
+ b0 += kw[0];
+ b1 += kw[1];
+ b2 += kw[2];
+ b3 += kw[3];
+ b4 += kw[4];
+ b5 += kw[5] + t[0];
+ b6 += kw[6] + t[1];
+ b7 += kw[7];
+
+ /*
+ * Rounds loop, unrolled to 8 rounds per iteration.
+ *
+ * Unrolling to multiples of 4 avoids the mod 4 check for key injection, and allows
+ * inlining of the permutations, which cycle every of 4 rounds (avoiding array
+ * index/lookup).
+ *
+ * Unrolling to multiples of 8 avoids the mod 8 rotation constant lookup, and allows
+ * inlining constant rotation values (avoiding array index/lookup).
+ */
+
+ for (int d = 1; d < (ROUNDS_512 / 4); d += 2)
+ {
+ int dm9 = mod9[d];
+ int dm3 = mod3[d];
+
+ /*
+ * 4 rounds of mix and permute.
+ *
+ * Permute schedule has a 4 round cycle, so permutes are inlined in the mix
+ * operations in each 4 round block.
+ */
+ b1 = RotlXor(b1, ROTATION_0_0, b0 += b1);
+ b3 = RotlXor(b3, ROTATION_0_1, b2 += b3);
+ b5 = RotlXor(b5, ROTATION_0_2, b4 += b5);
+ b7 = RotlXor(b7, ROTATION_0_3, b6 += b7);
+
+ b1 = RotlXor(b1, ROTATION_1_0, b2 += b1);
+ b7 = RotlXor(b7, ROTATION_1_1, b4 += b7);
+ b5 = RotlXor(b5, ROTATION_1_2, b6 += b5);
+ b3 = RotlXor(b3, ROTATION_1_3, b0 += b3);
+
+ b1 = RotlXor(b1, ROTATION_2_0, b4 += b1);
+ b3 = RotlXor(b3, ROTATION_2_1, b6 += b3);
+ b5 = RotlXor(b5, ROTATION_2_2, b0 += b5);
+ b7 = RotlXor(b7, ROTATION_2_3, b2 += b7);
+
+ b1 = RotlXor(b1, ROTATION_3_0, b6 += b1);
+ b7 = RotlXor(b7, ROTATION_3_1, b0 += b7);
+ b5 = RotlXor(b5, ROTATION_3_2, b2 += b5);
+ b3 = RotlXor(b3, ROTATION_3_3, b4 += b3);
+
+ /*
+ * Subkey injection for first 4 rounds.
+ */
+ b0 += kw[dm9];
+ b1 += kw[dm9 + 1];
+ b2 += kw[dm9 + 2];
+ b3 += kw[dm9 + 3];
+ b4 += kw[dm9 + 4];
+ b5 += kw[dm9 + 5] + t[dm3];
+ b6 += kw[dm9 + 6] + t[dm3 + 1];
+ b7 += kw[dm9 + 7] + (uint)d;
+
+ /*
+ * 4 more rounds of mix/permute
+ */
+ b1 = RotlXor(b1, ROTATION_4_0, b0 += b1);
+ b3 = RotlXor(b3, ROTATION_4_1, b2 += b3);
+ b5 = RotlXor(b5, ROTATION_4_2, b4 += b5);
+ b7 = RotlXor(b7, ROTATION_4_3, b6 += b7);
+
+ b1 = RotlXor(b1, ROTATION_5_0, b2 += b1);
+ b7 = RotlXor(b7, ROTATION_5_1, b4 += b7);
+ b5 = RotlXor(b5, ROTATION_5_2, b6 += b5);
+ b3 = RotlXor(b3, ROTATION_5_3, b0 += b3);
+
+ b1 = RotlXor(b1, ROTATION_6_0, b4 += b1);
+ b3 = RotlXor(b3, ROTATION_6_1, b6 += b3);
+ b5 = RotlXor(b5, ROTATION_6_2, b0 += b5);
+ b7 = RotlXor(b7, ROTATION_6_3, b2 += b7);
+
+ b1 = RotlXor(b1, ROTATION_7_0, b6 += b1);
+ b7 = RotlXor(b7, ROTATION_7_1, b0 += b7);
+ b5 = RotlXor(b5, ROTATION_7_2, b2 += b5);
+ b3 = RotlXor(b3, ROTATION_7_3, b4 += b3);
+
+ /*
+ * Subkey injection for next 4 rounds.
+ */
+ b0 += kw[dm9 + 1];
+ b1 += kw[dm9 + 2];
+ b2 += kw[dm9 + 3];
+ b3 += kw[dm9 + 4];
+ b4 += kw[dm9 + 5];
+ b5 += kw[dm9 + 6] + t[dm3 + 1];
+ b6 += kw[dm9 + 7] + t[dm3 + 2];
+ b7 += kw[dm9 + 8] + (uint)d + 1;
+ }
+
+ /*
+ * Output cipher state.
+ */
+ outWords[0] = b0;
+ outWords[1] = b1;
+ outWords[2] = b2;
+ outWords[3] = b3;
+ outWords[4] = b4;
+ outWords[5] = b5;
+ outWords[6] = b6;
+ outWords[7] = b7;
+ }
+
+ internal override void DecryptBlock(ulong[] block, ulong[] state)
+ {
+ ulong[] kw = this.kw;
+ ulong[] t = this.t;
+ int[] mod9 = MOD9;
+ int[] mod3 = MOD3;
+
+ /* Help the JIT avoid index bounds checks */
+ if (kw.Length != 17)
+ {
+ throw new ArgumentException();
+ }
+ if (t.Length != 5)
+ {
+ throw new ArgumentException();
+ }
+
+ ulong b0 = block[0];
+ ulong b1 = block[1];
+ ulong b2 = block[2];
+ ulong b3 = block[3];
+ ulong b4 = block[4];
+ ulong b5 = block[5];
+ ulong b6 = block[6];
+ ulong b7 = block[7];
+
+ for (int d = (ROUNDS_512 / 4) - 1; d >= 1; d -= 2)
+ {
+ int dm9 = mod9[d];
+ int dm3 = mod3[d];
+
+ /* Reverse key injection for second 4 rounds */
+ b0 -= kw[dm9 + 1];
+ b1 -= kw[dm9 + 2];
+ b2 -= kw[dm9 + 3];
+ b3 -= kw[dm9 + 4];
+ b4 -= kw[dm9 + 5];
+ b5 -= kw[dm9 + 6] + t[dm3 + 1];
+ b6 -= kw[dm9 + 7] + t[dm3 + 2];
+ b7 -= kw[dm9 + 8] + (uint)d + 1;
+
+ /* Reverse second 4 mix/permute rounds */
+
+ b1 = XorRotr(b1, ROTATION_7_0, b6);
+ b6 -= b1;
+ b7 = XorRotr(b7, ROTATION_7_1, b0);
+ b0 -= b7;
+ b5 = XorRotr(b5, ROTATION_7_2, b2);
+ b2 -= b5;
+ b3 = XorRotr(b3, ROTATION_7_3, b4);
+ b4 -= b3;
+
+ b1 = XorRotr(b1, ROTATION_6_0, b4);
+ b4 -= b1;
+ b3 = XorRotr(b3, ROTATION_6_1, b6);
+ b6 -= b3;
+ b5 = XorRotr(b5, ROTATION_6_2, b0);
+ b0 -= b5;
+ b7 = XorRotr(b7, ROTATION_6_3, b2);
+ b2 -= b7;
+
+ b1 = XorRotr(b1, ROTATION_5_0, b2);
+ b2 -= b1;
+ b7 = XorRotr(b7, ROTATION_5_1, b4);
+ b4 -= b7;
+ b5 = XorRotr(b5, ROTATION_5_2, b6);
+ b6 -= b5;
+ b3 = XorRotr(b3, ROTATION_5_3, b0);
+ b0 -= b3;
+
+ b1 = XorRotr(b1, ROTATION_4_0, b0);
+ b0 -= b1;
+ b3 = XorRotr(b3, ROTATION_4_1, b2);
+ b2 -= b3;
+ b5 = XorRotr(b5, ROTATION_4_2, b4);
+ b4 -= b5;
+ b7 = XorRotr(b7, ROTATION_4_3, b6);
+ b6 -= b7;
+
+ /* Reverse key injection for first 4 rounds */
+ b0 -= kw[dm9];
+ b1 -= kw[dm9 + 1];
+ b2 -= kw[dm9 + 2];
+ b3 -= kw[dm9 + 3];
+ b4 -= kw[dm9 + 4];
+ b5 -= kw[dm9 + 5] + t[dm3];
+ b6 -= kw[dm9 + 6] + t[dm3 + 1];
+ b7 -= kw[dm9 + 7] + (uint)d;
+
+ /* Reverse first 4 mix/permute rounds */
+ b1 = XorRotr(b1, ROTATION_3_0, b6);
+ b6 -= b1;
+ b7 = XorRotr(b7, ROTATION_3_1, b0);
+ b0 -= b7;
+ b5 = XorRotr(b5, ROTATION_3_2, b2);
+ b2 -= b5;
+ b3 = XorRotr(b3, ROTATION_3_3, b4);
+ b4 -= b3;
+
+ b1 = XorRotr(b1, ROTATION_2_0, b4);
+ b4 -= b1;
+ b3 = XorRotr(b3, ROTATION_2_1, b6);
+ b6 -= b3;
+ b5 = XorRotr(b5, ROTATION_2_2, b0);
+ b0 -= b5;
+ b7 = XorRotr(b7, ROTATION_2_3, b2);
+ b2 -= b7;
+
+ b1 = XorRotr(b1, ROTATION_1_0, b2);
+ b2 -= b1;
+ b7 = XorRotr(b7, ROTATION_1_1, b4);
+ b4 -= b7;
+ b5 = XorRotr(b5, ROTATION_1_2, b6);
+ b6 -= b5;
+ b3 = XorRotr(b3, ROTATION_1_3, b0);
+ b0 -= b3;
+
+ b1 = XorRotr(b1, ROTATION_0_0, b0);
+ b0 -= b1;
+ b3 = XorRotr(b3, ROTATION_0_1, b2);
+ b2 -= b3;
+ b5 = XorRotr(b5, ROTATION_0_2, b4);
+ b4 -= b5;
+ b7 = XorRotr(b7, ROTATION_0_3, b6);
+ b6 -= b7;
+ }
+
+ /*
+ * First subkey uninjection.
+ */
+ b0 -= kw[0];
+ b1 -= kw[1];
+ b2 -= kw[2];
+ b3 -= kw[3];
+ b4 -= kw[4];
+ b5 -= kw[5] + t[0];
+ b6 -= kw[6] + t[1];
+ b7 -= kw[7];
+
+ /*
+ * Output cipher state.
+ */
+ state[0] = b0;
+ state[1] = b1;
+ state[2] = b2;
+ state[3] = b3;
+ state[4] = b4;
+ state[5] = b5;
+ state[6] = b6;
+ state[7] = b7;
+ }
+ }
+
+ private sealed class Threefish1024Cipher
+ : ThreefishCipher
+ {
+ /**
+ * Mix rotation constants defined in Skein 1.3 specification
+ */
+ private const int ROTATION_0_0 = 24, ROTATION_0_1 = 13, ROTATION_0_2 = 8, ROTATION_0_3 = 47;
+ private const int ROTATION_0_4 = 8, ROTATION_0_5 = 17, ROTATION_0_6 = 22, ROTATION_0_7 = 37;
+ private const int ROTATION_1_0 = 38, ROTATION_1_1 = 19, ROTATION_1_2 = 10, ROTATION_1_3 = 55;
+ private const int ROTATION_1_4 = 49, ROTATION_1_5 = 18, ROTATION_1_6 = 23, ROTATION_1_7 = 52;
+ private const int ROTATION_2_0 = 33, ROTATION_2_1 = 4, ROTATION_2_2 = 51, ROTATION_2_3 = 13;
+ private const int ROTATION_2_4 = 34, ROTATION_2_5 = 41, ROTATION_2_6 = 59, ROTATION_2_7 = 17;
+ private const int ROTATION_3_0 = 5, ROTATION_3_1 = 20, ROTATION_3_2 = 48, ROTATION_3_3 = 41;
+ private const int ROTATION_3_4 = 47, ROTATION_3_5 = 28, ROTATION_3_6 = 16, ROTATION_3_7 = 25;
+
+ private const int ROTATION_4_0 = 41, ROTATION_4_1 = 9, ROTATION_4_2 = 37, ROTATION_4_3 = 31;
+ private const int ROTATION_4_4 = 12, ROTATION_4_5 = 47, ROTATION_4_6 = 44, ROTATION_4_7 = 30;
+ private const int ROTATION_5_0 = 16, ROTATION_5_1 = 34, ROTATION_5_2 = 56, ROTATION_5_3 = 51;
+ private const int ROTATION_5_4 = 4, ROTATION_5_5 = 53, ROTATION_5_6 = 42, ROTATION_5_7 = 41;
+ private const int ROTATION_6_0 = 31, ROTATION_6_1 = 44, ROTATION_6_2 = 47, ROTATION_6_3 = 46;
+ private const int ROTATION_6_4 = 19, ROTATION_6_5 = 42, ROTATION_6_6 = 44, ROTATION_6_7 = 25;
+ private const int ROTATION_7_0 = 9, ROTATION_7_1 = 48, ROTATION_7_2 = 35, ROTATION_7_3 = 52;
+ private const int ROTATION_7_4 = 23, ROTATION_7_5 = 31, ROTATION_7_6 = 37, ROTATION_7_7 = 20;
+
+ public Threefish1024Cipher(ulong[] kw, ulong[] t)
+ : base(kw, t)
+ {
+ }
+
+ internal override void EncryptBlock(ulong[] block, ulong[] outWords)
+ {
+ ulong[] kw = this.kw;
+ ulong[] t = this.t;
+ int[] mod17 = MOD17;
+ int[] mod3 = MOD3;
+
+ /* Help the JIT avoid index bounds checks */
+ if (kw.Length != 33)
+ {
+ throw new ArgumentException();
+ }
+ if (t.Length != 5)
+ {
+ throw new ArgumentException();
+ }
+
+ /*
+ * Read 16 words of plaintext data, not using arrays for cipher state
+ */
+ ulong b0 = block[0];
+ ulong b1 = block[1];
+ ulong b2 = block[2];
+ ulong b3 = block[3];
+ ulong b4 = block[4];
+ ulong b5 = block[5];
+ ulong b6 = block[6];
+ ulong b7 = block[7];
+ ulong b8 = block[8];
+ ulong b9 = block[9];
+ ulong b10 = block[10];
+ ulong b11 = block[11];
+ ulong b12 = block[12];
+ ulong b13 = block[13];
+ ulong b14 = block[14];
+ ulong b15 = block[15];
+
+ /*
+ * First subkey injection.
+ */
+ b0 += kw[0];
+ b1 += kw[1];
+ b2 += kw[2];
+ b3 += kw[3];
+ b4 += kw[4];
+ b5 += kw[5];
+ b6 += kw[6];
+ b7 += kw[7];
+ b8 += kw[8];
+ b9 += kw[9];
+ b10 += kw[10];
+ b11 += kw[11];
+ b12 += kw[12];
+ b13 += kw[13] + t[0];
+ b14 += kw[14] + t[1];
+ b15 += kw[15];
+
+ /*
+ * Rounds loop, unrolled to 8 rounds per iteration.
+ *
+ * Unrolling to multiples of 4 avoids the mod 4 check for key injection, and allows
+ * inlining of the permutations, which cycle every of 4 rounds (avoiding array
+ * index/lookup).
+ *
+ * Unrolling to multiples of 8 avoids the mod 8 rotation constant lookup, and allows
+ * inlining constant rotation values (avoiding array index/lookup).
+ */
+
+ for (int d = 1; d < (ROUNDS_1024 / 4); d += 2)
+ {
+ int dm17 = mod17[d];
+ int dm3 = mod3[d];
+
+ /*
+ * 4 rounds of mix and permute.
+ *
+ * Permute schedule has a 4 round cycle, so permutes are inlined in the mix
+ * operations in each 4 round block.
+ */
+ b1 = RotlXor(b1, ROTATION_0_0, b0 += b1);
+ b3 = RotlXor(b3, ROTATION_0_1, b2 += b3);
+ b5 = RotlXor(b5, ROTATION_0_2, b4 += b5);
+ b7 = RotlXor(b7, ROTATION_0_3, b6 += b7);
+ b9 = RotlXor(b9, ROTATION_0_4, b8 += b9);
+ b11 = RotlXor(b11, ROTATION_0_5, b10 += b11);
+ b13 = RotlXor(b13, ROTATION_0_6, b12 += b13);
+ b15 = RotlXor(b15, ROTATION_0_7, b14 += b15);
+
+ b9 = RotlXor(b9, ROTATION_1_0, b0 += b9);
+ b13 = RotlXor(b13, ROTATION_1_1, b2 += b13);
+ b11 = RotlXor(b11, ROTATION_1_2, b6 += b11);
+ b15 = RotlXor(b15, ROTATION_1_3, b4 += b15);
+ b7 = RotlXor(b7, ROTATION_1_4, b10 += b7);
+ b3 = RotlXor(b3, ROTATION_1_5, b12 += b3);
+ b5 = RotlXor(b5, ROTATION_1_6, b14 += b5);
+ b1 = RotlXor(b1, ROTATION_1_7, b8 += b1);
+
+ b7 = RotlXor(b7, ROTATION_2_0, b0 += b7);
+ b5 = RotlXor(b5, ROTATION_2_1, b2 += b5);
+ b3 = RotlXor(b3, ROTATION_2_2, b4 += b3);
+ b1 = RotlXor(b1, ROTATION_2_3, b6 += b1);
+ b15 = RotlXor(b15, ROTATION_2_4, b12 += b15);
+ b13 = RotlXor(b13, ROTATION_2_5, b14 += b13);
+ b11 = RotlXor(b11, ROTATION_2_6, b8 += b11);
+ b9 = RotlXor(b9, ROTATION_2_7, b10 += b9);
+
+ b15 = RotlXor(b15, ROTATION_3_0, b0 += b15);
+ b11 = RotlXor(b11, ROTATION_3_1, b2 += b11);
+ b13 = RotlXor(b13, ROTATION_3_2, b6 += b13);
+ b9 = RotlXor(b9, ROTATION_3_3, b4 += b9);
+ b1 = RotlXor(b1, ROTATION_3_4, b14 += b1);
+ b5 = RotlXor(b5, ROTATION_3_5, b8 += b5);
+ b3 = RotlXor(b3, ROTATION_3_6, b10 += b3);
+ b7 = RotlXor(b7, ROTATION_3_7, b12 += b7);
+
+ /*
+ * Subkey injection for first 4 rounds.
+ */
+ b0 += kw[dm17];
+ b1 += kw[dm17 + 1];
+ b2 += kw[dm17 + 2];
+ b3 += kw[dm17 + 3];
+ b4 += kw[dm17 + 4];
+ b5 += kw[dm17 + 5];
+ b6 += kw[dm17 + 6];
+ b7 += kw[dm17 + 7];
+ b8 += kw[dm17 + 8];
+ b9 += kw[dm17 + 9];
+ b10 += kw[dm17 + 10];
+ b11 += kw[dm17 + 11];
+ b12 += kw[dm17 + 12];
+ b13 += kw[dm17 + 13] + t[dm3];
+ b14 += kw[dm17 + 14] + t[dm3 + 1];
+ b15 += kw[dm17 + 15] + (uint)d;
+
+ /*
+ * 4 more rounds of mix/permute
+ */
+ b1 = RotlXor(b1, ROTATION_4_0, b0 += b1);
+ b3 = RotlXor(b3, ROTATION_4_1, b2 += b3);
+ b5 = RotlXor(b5, ROTATION_4_2, b4 += b5);
+ b7 = RotlXor(b7, ROTATION_4_3, b6 += b7);
+ b9 = RotlXor(b9, ROTATION_4_4, b8 += b9);
+ b11 = RotlXor(b11, ROTATION_4_5, b10 += b11);
+ b13 = RotlXor(b13, ROTATION_4_6, b12 += b13);
+ b15 = RotlXor(b15, ROTATION_4_7, b14 += b15);
+
+ b9 = RotlXor(b9, ROTATION_5_0, b0 += b9);
+ b13 = RotlXor(b13, ROTATION_5_1, b2 += b13);
+ b11 = RotlXor(b11, ROTATION_5_2, b6 += b11);
+ b15 = RotlXor(b15, ROTATION_5_3, b4 += b15);
+ b7 = RotlXor(b7, ROTATION_5_4, b10 += b7);
+ b3 = RotlXor(b3, ROTATION_5_5, b12 += b3);
+ b5 = RotlXor(b5, ROTATION_5_6, b14 += b5);
+ b1 = RotlXor(b1, ROTATION_5_7, b8 += b1);
+
+ b7 = RotlXor(b7, ROTATION_6_0, b0 += b7);
+ b5 = RotlXor(b5, ROTATION_6_1, b2 += b5);
+ b3 = RotlXor(b3, ROTATION_6_2, b4 += b3);
+ b1 = RotlXor(b1, ROTATION_6_3, b6 += b1);
+ b15 = RotlXor(b15, ROTATION_6_4, b12 += b15);
+ b13 = RotlXor(b13, ROTATION_6_5, b14 += b13);
+ b11 = RotlXor(b11, ROTATION_6_6, b8 += b11);
+ b9 = RotlXor(b9, ROTATION_6_7, b10 += b9);
+
+ b15 = RotlXor(b15, ROTATION_7_0, b0 += b15);
+ b11 = RotlXor(b11, ROTATION_7_1, b2 += b11);
+ b13 = RotlXor(b13, ROTATION_7_2, b6 += b13);
+ b9 = RotlXor(b9, ROTATION_7_3, b4 += b9);
+ b1 = RotlXor(b1, ROTATION_7_4, b14 += b1);
+ b5 = RotlXor(b5, ROTATION_7_5, b8 += b5);
+ b3 = RotlXor(b3, ROTATION_7_6, b10 += b3);
+ b7 = RotlXor(b7, ROTATION_7_7, b12 += b7);
+
+ /*
+ * Subkey injection for next 4 rounds.
+ */
+ b0 += kw[dm17 + 1];
+ b1 += kw[dm17 + 2];
+ b2 += kw[dm17 + 3];
+ b3 += kw[dm17 + 4];
+ b4 += kw[dm17 + 5];
+ b5 += kw[dm17 + 6];
+ b6 += kw[dm17 + 7];
+ b7 += kw[dm17 + 8];
+ b8 += kw[dm17 + 9];
+ b9 += kw[dm17 + 10];
+ b10 += kw[dm17 + 11];
+ b11 += kw[dm17 + 12];
+ b12 += kw[dm17 + 13];
+ b13 += kw[dm17 + 14] + t[dm3 + 1];
+ b14 += kw[dm17 + 15] + t[dm3 + 2];
+ b15 += kw[dm17 + 16] + (uint)d + 1;
+
+ }
+
+ /*
+ * Output cipher state.
+ */
+ outWords[0] = b0;
+ outWords[1] = b1;
+ outWords[2] = b2;
+ outWords[3] = b3;
+ outWords[4] = b4;
+ outWords[5] = b5;
+ outWords[6] = b6;
+ outWords[7] = b7;
+ outWords[8] = b8;
+ outWords[9] = b9;
+ outWords[10] = b10;
+ outWords[11] = b11;
+ outWords[12] = b12;
+ outWords[13] = b13;
+ outWords[14] = b14;
+ outWords[15] = b15;
+ }
+
+ internal override void DecryptBlock(ulong[] block, ulong[] state)
+ {
+ ulong[] kw = this.kw;
+ ulong[] t = this.t;
+ int[] mod17 = MOD17;
+ int[] mod3 = MOD3;
+
+ /* Help the JIT avoid index bounds checks */
+ if (kw.Length != 33)
+ {
+ throw new ArgumentException();
+ }
+ if (t.Length != 5)
+ {
+ throw new ArgumentException();
+ }
+
+ ulong b0 = block[0];
+ ulong b1 = block[1];
+ ulong b2 = block[2];
+ ulong b3 = block[3];
+ ulong b4 = block[4];
+ ulong b5 = block[5];
+ ulong b6 = block[6];
+ ulong b7 = block[7];
+ ulong b8 = block[8];
+ ulong b9 = block[9];
+ ulong b10 = block[10];
+ ulong b11 = block[11];
+ ulong b12 = block[12];
+ ulong b13 = block[13];
+ ulong b14 = block[14];
+ ulong b15 = block[15];
+
+ for (int d = (ROUNDS_1024 / 4) - 1; d >= 1; d -= 2)
+ {
+ int dm17 = mod17[d];
+ int dm3 = mod3[d];
+
+ /* Reverse key injection for second 4 rounds */
+ b0 -= kw[dm17 + 1];
+ b1 -= kw[dm17 + 2];
+ b2 -= kw[dm17 + 3];
+ b3 -= kw[dm17 + 4];
+ b4 -= kw[dm17 + 5];
+ b5 -= kw[dm17 + 6];
+ b6 -= kw[dm17 + 7];
+ b7 -= kw[dm17 + 8];
+ b8 -= kw[dm17 + 9];
+ b9 -= kw[dm17 + 10];
+ b10 -= kw[dm17 + 11];
+ b11 -= kw[dm17 + 12];
+ b12 -= kw[dm17 + 13];
+ b13 -= kw[dm17 + 14] + t[dm3 + 1];
+ b14 -= kw[dm17 + 15] + t[dm3 + 2];
+ b15 -= kw[dm17 + 16] + (uint)d + 1;
+
+ /* Reverse second 4 mix/permute rounds */
+ b15 = XorRotr(b15, ROTATION_7_0, b0);
+ b0 -= b15;
+ b11 = XorRotr(b11, ROTATION_7_1, b2);
+ b2 -= b11;
+ b13 = XorRotr(b13, ROTATION_7_2, b6);
+ b6 -= b13;
+ b9 = XorRotr(b9, ROTATION_7_3, b4);
+ b4 -= b9;
+ b1 = XorRotr(b1, ROTATION_7_4, b14);
+ b14 -= b1;
+ b5 = XorRotr(b5, ROTATION_7_5, b8);
+ b8 -= b5;
+ b3 = XorRotr(b3, ROTATION_7_6, b10);
+ b10 -= b3;
+ b7 = XorRotr(b7, ROTATION_7_7, b12);
+ b12 -= b7;
+
+ b7 = XorRotr(b7, ROTATION_6_0, b0);
+ b0 -= b7;
+ b5 = XorRotr(b5, ROTATION_6_1, b2);
+ b2 -= b5;
+ b3 = XorRotr(b3, ROTATION_6_2, b4);
+ b4 -= b3;
+ b1 = XorRotr(b1, ROTATION_6_3, b6);
+ b6 -= b1;
+ b15 = XorRotr(b15, ROTATION_6_4, b12);
+ b12 -= b15;
+ b13 = XorRotr(b13, ROTATION_6_5, b14);
+ b14 -= b13;
+ b11 = XorRotr(b11, ROTATION_6_6, b8);
+ b8 -= b11;
+ b9 = XorRotr(b9, ROTATION_6_7, b10);
+ b10 -= b9;
+
+ b9 = XorRotr(b9, ROTATION_5_0, b0);
+ b0 -= b9;
+ b13 = XorRotr(b13, ROTATION_5_1, b2);
+ b2 -= b13;
+ b11 = XorRotr(b11, ROTATION_5_2, b6);
+ b6 -= b11;
+ b15 = XorRotr(b15, ROTATION_5_3, b4);
+ b4 -= b15;
+ b7 = XorRotr(b7, ROTATION_5_4, b10);
+ b10 -= b7;
+ b3 = XorRotr(b3, ROTATION_5_5, b12);
+ b12 -= b3;
+ b5 = XorRotr(b5, ROTATION_5_6, b14);
+ b14 -= b5;
+ b1 = XorRotr(b1, ROTATION_5_7, b8);
+ b8 -= b1;
+
+ b1 = XorRotr(b1, ROTATION_4_0, b0);
+ b0 -= b1;
+ b3 = XorRotr(b3, ROTATION_4_1, b2);
+ b2 -= b3;
+ b5 = XorRotr(b5, ROTATION_4_2, b4);
+ b4 -= b5;
+ b7 = XorRotr(b7, ROTATION_4_3, b6);
+ b6 -= b7;
+ b9 = XorRotr(b9, ROTATION_4_4, b8);
+ b8 -= b9;
+ b11 = XorRotr(b11, ROTATION_4_5, b10);
+ b10 -= b11;
+ b13 = XorRotr(b13, ROTATION_4_6, b12);
+ b12 -= b13;
+ b15 = XorRotr(b15, ROTATION_4_7, b14);
+ b14 -= b15;
+
+ /* Reverse key injection for first 4 rounds */
+ b0 -= kw[dm17];
+ b1 -= kw[dm17 + 1];
+ b2 -= kw[dm17 + 2];
+ b3 -= kw[dm17 + 3];
+ b4 -= kw[dm17 + 4];
+ b5 -= kw[dm17 + 5];
+ b6 -= kw[dm17 + 6];
+ b7 -= kw[dm17 + 7];
+ b8 -= kw[dm17 + 8];
+ b9 -= kw[dm17 + 9];
+ b10 -= kw[dm17 + 10];
+ b11 -= kw[dm17 + 11];
+ b12 -= kw[dm17 + 12];
+ b13 -= kw[dm17 + 13] + t[dm3];
+ b14 -= kw[dm17 + 14] + t[dm3 + 1];
+ b15 -= kw[dm17 + 15] + (uint)d;
+
+ /* Reverse first 4 mix/permute rounds */
+ b15 = XorRotr(b15, ROTATION_3_0, b0);
+ b0 -= b15;
+ b11 = XorRotr(b11, ROTATION_3_1, b2);
+ b2 -= b11;
+ b13 = XorRotr(b13, ROTATION_3_2, b6);
+ b6 -= b13;
+ b9 = XorRotr(b9, ROTATION_3_3, b4);
+ b4 -= b9;
+ b1 = XorRotr(b1, ROTATION_3_4, b14);
+ b14 -= b1;
+ b5 = XorRotr(b5, ROTATION_3_5, b8);
+ b8 -= b5;
+ b3 = XorRotr(b3, ROTATION_3_6, b10);
+ b10 -= b3;
+ b7 = XorRotr(b7, ROTATION_3_7, b12);
+ b12 -= b7;
+
+ b7 = XorRotr(b7, ROTATION_2_0, b0);
+ b0 -= b7;
+ b5 = XorRotr(b5, ROTATION_2_1, b2);
+ b2 -= b5;
+ b3 = XorRotr(b3, ROTATION_2_2, b4);
+ b4 -= b3;
+ b1 = XorRotr(b1, ROTATION_2_3, b6);
+ b6 -= b1;
+ b15 = XorRotr(b15, ROTATION_2_4, b12);
+ b12 -= b15;
+ b13 = XorRotr(b13, ROTATION_2_5, b14);
+ b14 -= b13;
+ b11 = XorRotr(b11, ROTATION_2_6, b8);
+ b8 -= b11;
+ b9 = XorRotr(b9, ROTATION_2_7, b10);
+ b10 -= b9;
+
+ b9 = XorRotr(b9, ROTATION_1_0, b0);
+ b0 -= b9;
+ b13 = XorRotr(b13, ROTATION_1_1, b2);
+ b2 -= b13;
+ b11 = XorRotr(b11, ROTATION_1_2, b6);
+ b6 -= b11;
+ b15 = XorRotr(b15, ROTATION_1_3, b4);
+ b4 -= b15;
+ b7 = XorRotr(b7, ROTATION_1_4, b10);
+ b10 -= b7;
+ b3 = XorRotr(b3, ROTATION_1_5, b12);
+ b12 -= b3;
+ b5 = XorRotr(b5, ROTATION_1_6, b14);
+ b14 -= b5;
+ b1 = XorRotr(b1, ROTATION_1_7, b8);
+ b8 -= b1;
+
+ b1 = XorRotr(b1, ROTATION_0_0, b0);
+ b0 -= b1;
+ b3 = XorRotr(b3, ROTATION_0_1, b2);
+ b2 -= b3;
+ b5 = XorRotr(b5, ROTATION_0_2, b4);
+ b4 -= b5;
+ b7 = XorRotr(b7, ROTATION_0_3, b6);
+ b6 -= b7;
+ b9 = XorRotr(b9, ROTATION_0_4, b8);
+ b8 -= b9;
+ b11 = XorRotr(b11, ROTATION_0_5, b10);
+ b10 -= b11;
+ b13 = XorRotr(b13, ROTATION_0_6, b12);
+ b12 -= b13;
+ b15 = XorRotr(b15, ROTATION_0_7, b14);
+ b14 -= b15;
+ }
+
+ /*
+ * First subkey uninjection.
+ */
+ b0 -= kw[0];
+ b1 -= kw[1];
+ b2 -= kw[2];
+ b3 -= kw[3];
+ b4 -= kw[4];
+ b5 -= kw[5];
+ b6 -= kw[6];
+ b7 -= kw[7];
+ b8 -= kw[8];
+ b9 -= kw[9];
+ b10 -= kw[10];
+ b11 -= kw[11];
+ b12 -= kw[12];
+ b13 -= kw[13] + t[0];
+ b14 -= kw[14] + t[1];
+ b15 -= kw[15];
+
+ /*
+ * Output cipher state.
+ */
+ state[0] = b0;
+ state[1] = b1;
+ state[2] = b2;
+ state[3] = b3;
+ state[4] = b4;
+ state[5] = b5;
+ state[6] = b6;
+ state[7] = b7;
+ state[8] = b8;
+ state[9] = b9;
+ state[10] = b10;
+ state[11] = b11;
+ state[12] = b12;
+ state[13] = b13;
+ state[14] = b14;
+ state[15] = b15;
+ }
+
+ }
+
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/ThreefishEngine.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/ThreefishEngine.cs.meta
new file mode 100644
index 00000000..9e0d787a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/ThreefishEngine.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 015b89c9dc51aec49acedc3323aad0b4
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/TnepresEngine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/TnepresEngine.cs
new file mode 100644
index 00000000..fc3c2e68
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/TnepresEngine.cs
@@ -0,0 +1,303 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ /**
+ * Tnepres is a 128-bit 32-round block cipher with variable key lengths,
+ * including 128, 192 and 256 bit keys conjectured to be at least as
+ * secure as three-key triple-DES.
+ *
+ * Tnepres is based on Serpent which was designed by Ross Anderson, Eli Biham and Lars Knudsen as a
+ * candidate algorithm for the NIST AES Quest. Unfortunately there was an endianness issue
+ * with test vectors in the AES submission and the resulting confusion lead to the Tnepres cipher
+ * as well, which is a byte swapped version of Serpent.
+ *
+ * where a = primitive root of field generator 0x14D
+ *
+ */
+ private int RS_rem(int x)
+ {
+ int b = (int) (((uint)x >> 24) & 0xff);
+ int g2 = ((b << 1) ^
+ ((b & 0x80) != 0 ? RS_GF_FDBK : 0)) & 0xff;
+ int g3 = ( (int)((uint)b >> 1) ^
+ ((b & 0x01) != 0 ? (int)((uint)RS_GF_FDBK >> 1) : 0)) ^ g2 ;
+ return ((x << 8) ^ (g3 << 24) ^ (g2 << 16) ^ (g3 << 8) ^ b);
+ }
+
+ private int LFSR1(int x)
+ {
+ return (x >> 1) ^
+ (((x & 0x01) != 0) ? GF256_FDBK_2 : 0);
+ }
+
+ private int LFSR2(int x)
+ {
+ return (x >> 2) ^
+ (((x & 0x02) != 0) ? GF256_FDBK_2 : 0) ^
+ (((x & 0x01) != 0) ? GF256_FDBK_4 : 0);
+ }
+
+ private int Mx_X(int x)
+ {
+ return x ^ LFSR2(x);
+ } // 5B
+
+ private int Mx_Y(int x)
+ {
+ return x ^ LFSR1(x) ^ LFSR2(x);
+ } // EF
+
+ private int M_b0(int x)
+ {
+ return x & 0xff;
+ }
+
+ private int M_b1(int x)
+ {
+ return (int)((uint)x >> 8) & 0xff;
+ }
+
+ private int M_b2(int x)
+ {
+ return (int)((uint)x >> 16) & 0xff;
+ }
+
+ private int M_b3(int x)
+ {
+ return (int)((uint)x >> 24) & 0xff;
+ }
+
+ private int Fe32_0(int x)
+ {
+ return gSBox[ 0x000 + 2*(x & 0xff) ] ^
+ gSBox[ 0x001 + 2*((int)((uint)x >> 8) & 0xff) ] ^
+ gSBox[ 0x200 + 2*((int)((uint)x >> 16) & 0xff) ] ^
+ gSBox[ 0x201 + 2*((int)((uint)x >> 24) & 0xff) ];
+ }
+
+ private int Fe32_3(int x)
+ {
+ return gSBox[ 0x000 + 2*((int)((uint)x >> 24) & 0xff) ] ^
+ gSBox[ 0x001 + 2*(x & 0xff) ] ^
+ gSBox[ 0x200 + 2*((int)((uint)x >> 8) & 0xff) ] ^
+ gSBox[ 0x201 + 2*((int)((uint)x >> 16) & 0xff) ];
+ }
+
+ private int BytesTo32Bits(byte[] b, int p)
+ {
+ return ((b[p] & 0xff) ) |
+ ((b[p+1] & 0xff) << 8) |
+ ((b[p+2] & 0xff) << 16) |
+ ((b[p+3] & 0xff) << 24);
+ }
+
+ private void Bits32ToBytes(int inData, byte[] b, int offset)
+ {
+ b[offset] = (byte)inData;
+ b[offset + 1] = (byte)(inData >> 8);
+ b[offset + 2] = (byte)(inData >> 16);
+ b[offset + 3] = (byte)(inData >> 24);
+ }
+ }
+
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/TwofishEngine.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/TwofishEngine.cs.meta
new file mode 100644
index 00000000..eab3ab82
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/TwofishEngine.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 55bc155aecc561841af464c77f3a4cf9
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/VMPCEngine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/VMPCEngine.cs
new file mode 100644
index 00000000..c1da4ca0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/VMPCEngine.cs
@@ -0,0 +1,137 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ public class VmpcEngine
+ : IStreamCipher
+ {
+ /*
+ * variables to hold the state of the VMPC engine during encryption and
+ * decryption
+ */
+ protected byte n = 0;
+ protected byte[] P = null;
+ protected byte s = 0;
+
+ protected byte[] workingIV;
+ protected byte[] workingKey;
+
+ public virtual string AlgorithmName
+ {
+ get { return "VMPC"; }
+ }
+
+ /**
+ * initialise a VMPC cipher.
+ *
+ * @param forEncryption
+ * whether or not we are for encryption.
+ * @param params
+ * the parameters required to set up the cipher.
+ * @exception ArgumentException
+ * if the params argument is inappropriate.
+ */
+ public virtual void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ if (!(parameters is ParametersWithIV))
+ throw new ArgumentException("VMPC Init parameters must include an IV");
+
+ ParametersWithIV ivParams = (ParametersWithIV) parameters;
+
+ if (!(ivParams.Parameters is KeyParameter))
+ throw new ArgumentException("VMPC Init parameters must include a key");
+
+ KeyParameter key = (KeyParameter)ivParams.Parameters;
+
+ this.workingIV = ivParams.GetIV();
+
+ if (workingIV == null || workingIV.Length < 1 || workingIV.Length > 768)
+ throw new ArgumentException("VMPC requires 1 to 768 bytes of IV");
+
+ this.workingKey = key.GetKey();
+
+ InitKey(this.workingKey, this.workingIV);
+ }
+
+ protected virtual void InitKey(
+ byte[] keyBytes,
+ byte[] ivBytes)
+ {
+ s = 0;
+ P = new byte[256];
+ for (int i = 0; i < 256; i++)
+ {
+ P[i] = (byte) i;
+ }
+
+ for (int m = 0; m < 768; m++)
+ {
+ s = P[(s + P[m & 0xff] + keyBytes[m % keyBytes.Length]) & 0xff];
+ byte temp = P[m & 0xff];
+ P[m & 0xff] = P[s & 0xff];
+ P[s & 0xff] = temp;
+ }
+ for (int m = 0; m < 768; m++)
+ {
+ s = P[(s + P[m & 0xff] + ivBytes[m % ivBytes.Length]) & 0xff];
+ byte temp = P[m & 0xff];
+ P[m & 0xff] = P[s & 0xff];
+ P[s & 0xff] = temp;
+ }
+ n = 0;
+ }
+
+ public virtual void ProcessBytes(
+ byte[] input,
+ int inOff,
+ int len,
+ byte[] output,
+ int outOff)
+ {
+ Check.DataLength(input, inOff, len, "input buffer too short");
+ Check.OutputLength(output, outOff, len, "output buffer too short");
+
+ for (int i = 0; i < len; i++)
+ {
+ s = P[(s + P[n & 0xff]) & 0xff];
+ byte z = P[(P[(P[s & 0xff]) & 0xff] + 1) & 0xff];
+ // encryption
+ byte temp = P[n & 0xff];
+ P[n & 0xff] = P[s & 0xff];
+ P[s & 0xff] = temp;
+ n = (byte) ((n + 1) & 0xff);
+
+ // xor
+ output[i + outOff] = (byte) (input[i + inOff] ^ z);
+ }
+ }
+
+ public virtual void Reset()
+ {
+ InitKey(this.workingKey, this.workingIV);
+ }
+
+ public virtual byte ReturnByte(
+ byte input)
+ {
+ s = P[(s + P[n & 0xff]) & 0xff];
+ byte z = P[(P[(P[s & 0xff]) & 0xff] + 1) & 0xff];
+ // encryption
+ byte temp = P[n & 0xff];
+ P[n & 0xff] = P[s & 0xff];
+ P[s & 0xff] = temp;
+ n = (byte) ((n + 1) & 0xff);
+
+ // xor
+ return (byte) (input ^ z);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/VMPCEngine.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/VMPCEngine.cs.meta
new file mode 100644
index 00000000..97e927ec
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/VMPCEngine.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 6c29feaad92e27d4a8e258e0856100ec
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/VMPCKSA3Engine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/VMPCKSA3Engine.cs
new file mode 100644
index 00000000..ed7b6c0d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/VMPCKSA3Engine.cs
@@ -0,0 +1,55 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ public class VmpcKsa3Engine
+ : VmpcEngine
+ {
+ public override string AlgorithmName
+ {
+ get { return "VMPC-KSA3"; }
+ }
+
+ protected override void InitKey(
+ byte[] keyBytes,
+ byte[] ivBytes)
+ {
+ s = 0;
+ P = new byte[256];
+ for (int i = 0; i < 256; i++)
+ {
+ P[i] = (byte) i;
+ }
+
+ for (int m = 0; m < 768; m++)
+ {
+ s = P[(s + P[m & 0xff] + keyBytes[m % keyBytes.Length]) & 0xff];
+ byte temp = P[m & 0xff];
+ P[m & 0xff] = P[s & 0xff];
+ P[s & 0xff] = temp;
+ }
+
+ for (int m = 0; m < 768; m++)
+ {
+ s = P[(s + P[m & 0xff] + ivBytes[m % ivBytes.Length]) & 0xff];
+ byte temp = P[m & 0xff];
+ P[m & 0xff] = P[s & 0xff];
+ P[s & 0xff] = temp;
+ }
+
+ for (int m = 0; m < 768; m++)
+ {
+ s = P[(s + P[m & 0xff] + keyBytes[m % keyBytes.Length]) & 0xff];
+ byte temp = P[m & 0xff];
+ P[m & 0xff] = P[s & 0xff];
+ P[s & 0xff] = temp;
+ }
+
+ n = 0;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/VMPCKSA3Engine.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/VMPCKSA3Engine.cs.meta
new file mode 100644
index 00000000..21fe52d8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/VMPCKSA3Engine.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 05ccf3686014dfd48981280c5cc5b3b9
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/XSalsa20Engine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/XSalsa20Engine.cs
new file mode 100644
index 00000000..efcaf391
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/XSalsa20Engine.cs
@@ -0,0 +1,68 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ ///
+ /// Implementation of Daniel J. Bernstein's XSalsa20 stream cipher - Salsa20 with an extended nonce.
+ ///
+ ///
+ /// XSalsa20 requires a 256 bit key, and a 192 bit nonce.
+ ///
+ public class XSalsa20Engine
+ : Salsa20Engine
+ {
+ public override string AlgorithmName
+ {
+ get { return "XSalsa20"; }
+ }
+
+ protected override int NonceSize
+ {
+ get { return 24; }
+ }
+
+ ///
+ /// XSalsa20 key generation: process 256 bit input key and 128 bits of the input nonce
+ /// using a core Salsa20 function without input addition to produce 256 bit working key
+ /// and use that with the remaining 64 bits of nonce to initialize a standard Salsa20 engine state.
+ ///
+ protected override void SetKey(byte[] keyBytes, byte[] ivBytes)
+ {
+ if (keyBytes == null)
+ throw new ArgumentException(AlgorithmName + " doesn't support re-init with null key");
+
+ if (keyBytes.Length != 32)
+ throw new ArgumentException(AlgorithmName + " requires a 256 bit key");
+
+ // Set key for HSalsa20
+ base.SetKey(keyBytes, ivBytes);
+
+ // Pack next 64 bits of IV into engine state instead of counter
+ Pack.LE_To_UInt32(ivBytes, 8, engineState, 8, 2);
+
+ // Process engine state to generate Salsa20 key
+ uint[] hsalsa20Out = new uint[engineState.Length];
+ SalsaCore(20, engineState, hsalsa20Out);
+
+ // Set new key, removing addition in last round of salsaCore
+ engineState[1] = hsalsa20Out[0] - engineState[0];
+ engineState[2] = hsalsa20Out[5] - engineState[5];
+ engineState[3] = hsalsa20Out[10] - engineState[10];
+ engineState[4] = hsalsa20Out[15] - engineState[15];
+
+ engineState[11] = hsalsa20Out[6] - engineState[6];
+ engineState[12] = hsalsa20Out[7] - engineState[7];
+ engineState[13] = hsalsa20Out[8] - engineState[8];
+ engineState[14] = hsalsa20Out[9] - engineState[9];
+
+ // Last 64 bits of input IV
+ Pack.LE_To_UInt32(ivBytes, 16, engineState, 6, 2);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/XSalsa20Engine.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/XSalsa20Engine.cs.meta
new file mode 100644
index 00000000..d35fc424
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/XSalsa20Engine.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 2496ed6753462e243b7d54834823fc34
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/XTEAEngine.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/XTEAEngine.cs
new file mode 100644
index 00000000..b2fdaada
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/XTEAEngine.cs
@@ -0,0 +1,170 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
+{
+ /**
+ * An XTEA engine.
+ */
+ public class XteaEngine
+ : IBlockCipher
+ {
+ private const int
+ rounds = 32,
+ block_size = 8,
+// key_size = 16,
+ delta = unchecked((int) 0x9E3779B9);
+
+ /*
+ * the expanded key array of 4 subkeys
+ */
+ private uint[] _S = new uint[4],
+ _sum0 = new uint[32],
+ _sum1 = new uint[32];
+ private bool _initialised, _forEncryption;
+
+ /**
+ * Create an instance of the TEA encryption algorithm
+ * and set some defaults
+ */
+ public XteaEngine()
+ {
+ _initialised = false;
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "XTEA"; }
+ }
+
+ public virtual bool IsPartialBlockOkay
+ {
+ get { return false; }
+ }
+
+ public virtual int GetBlockSize()
+ {
+ return block_size;
+ }
+
+ /**
+ * initialise
+ *
+ * @param forEncryption whether or not we are for encryption.
+ * @param params the parameters required to set up the cipher.
+ * @exception ArgumentException if the params argument is
+ * inappropriate.
+ */
+ public virtual void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ if (!(parameters is KeyParameter))
+ {
+ throw new ArgumentException("invalid parameter passed to TEA init - "
+ + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters));
+ }
+
+ _forEncryption = forEncryption;
+ _initialised = true;
+
+ KeyParameter p = (KeyParameter) parameters;
+
+ setKey(p.GetKey());
+ }
+
+ public virtual int ProcessBlock(
+ byte[] inBytes,
+ int inOff,
+ byte[] outBytes,
+ int outOff)
+ {
+ if (!_initialised)
+ throw new InvalidOperationException(AlgorithmName + " not initialised");
+
+ Check.DataLength(inBytes, inOff, block_size, "input buffer too short");
+ Check.OutputLength(outBytes, outOff, block_size, "output buffer too short");
+
+ return _forEncryption
+ ? encryptBlock(inBytes, inOff, outBytes, outOff)
+ : decryptBlock(inBytes, inOff, outBytes, outOff);
+ }
+
+ public virtual void Reset()
+ {
+ }
+
+ /**
+ * Re-key the cipher.
+ *
+ * @param key the key to be used
+ */
+ private void setKey(
+ byte[] key)
+ {
+ int i, j;
+ for (i = j = 0; i < 4; i++,j+=4)
+ {
+ _S[i] = Pack.BE_To_UInt32(key, j);
+ }
+
+ for (i = j = 0; i < rounds; i++)
+ {
+ _sum0[i] = ((uint)j + _S[j & 3]);
+ j += delta;
+ _sum1[i] = ((uint)j + _S[j >> 11 & 3]);
+ }
+ }
+
+ private int encryptBlock(
+ byte[] inBytes,
+ int inOff,
+ byte[] outBytes,
+ int outOff)
+ {
+ // Pack bytes into integers
+ uint v0 = Pack.BE_To_UInt32(inBytes, inOff);
+ uint v1 = Pack.BE_To_UInt32(inBytes, inOff + 4);
+
+ for (int i = 0; i < rounds; i++)
+ {
+ v0 += ((v1 << 4 ^ v1 >> 5) + v1) ^ _sum0[i];
+ v1 += ((v0 << 4 ^ v0 >> 5) + v0) ^ _sum1[i];
+ }
+
+ Pack.UInt32_To_BE(v0, outBytes, outOff);
+ Pack.UInt32_To_BE(v1, outBytes, outOff + 4);
+
+ return block_size;
+ }
+
+ private int decryptBlock(
+ byte[] inBytes,
+ int inOff,
+ byte[] outBytes,
+ int outOff)
+ {
+ // Pack bytes into integers
+ uint v0 = Pack.BE_To_UInt32(inBytes, inOff);
+ uint v1 = Pack.BE_To_UInt32(inBytes, inOff + 4);
+
+ for (int i = rounds-1; i >= 0; i--)
+ {
+ v1 -= ((v0 << 4 ^ v0 >> 5) + v0) ^ _sum1[i];
+ v0 -= ((v1 << 4 ^ v1 >> 5) + v1) ^ _sum0[i];
+ }
+
+ Pack.UInt32_To_BE(v0, outBytes, outOff);
+ Pack.UInt32_To_BE(v1, outBytes, outOff + 4);
+
+ return block_size;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/XTEAEngine.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/XTEAEngine.cs.meta
new file mode 100644
index 00000000..bfccba88
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/engines/XTEAEngine.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 6051826ba9ea2a74bbbc2efd92b5d977
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators.meta
new file mode 100644
index 00000000..4fee965a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: a0959102436299e4eba93aa086cc6f46
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/BCrypt.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/BCrypt.cs
new file mode 100644
index 00000000..c8a176f3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/BCrypt.cs
@@ -0,0 +1,632 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ /**
+ * Core of password hashing scheme Bcrypt,
+ * designed by Niels Provos and David Mazières,
+ * corresponds to the C reference implementation.
+ *
+ * This implementation does not correspondent to the 1999 published paper
+ * "A Future-Adaptable Password Scheme" of Niels Provos and David Mazières,
+ * see: https://www.usenix.org/legacy/events/usenix99/provos/provos_html/node1.html.
+ * In contrast to the paper, the order of key setup and salt setup is reversed:
+ * state <- ExpandKey(state, 0, key)
+ * state %lt;- ExpandKey(state, 0, salt)
+ * This corresponds to the OpenBSD reference implementation of Bcrypt.
+ *
+ * Note:
+ * There is no successful cryptanalysis (status 2015), but
+ * the amount of memory and the band width of Bcrypt
+ * may be insufficient to effectively prevent attacks
+ * with custom hardware like FPGAs, ASICs
+ *
+ * This implementation uses some parts of Bouncy Castle's BlowfishEngine.
+ *
+ * This implements the raw bcrypt function as defined in the bcrypt specification, not
+ * the crypt encoded version implemented in OpenBSD.
+ *
+ * @param password the password bytes (up to 72 bytes) to use for this invocation.
+ * @param salt the 128 bit salt to use for this invocation.
+ * @param cost the bcrypt cost parameter. The cost of the bcrypt function grows as
+ * 2^cost. Legal values are 4..31 inclusive.
+ * @return the output of the raw bcrypt operation: a 192 bit (24 byte) hash.
+ */
+ public static byte[] Generate(byte[] password, byte[] salt, int cost)
+ {
+ if (password == null)
+ throw new ArgumentNullException("password");
+ if (password.Length > MAX_PASSWORD_BYTES)
+ throw new ArgumentException("BCrypt password must be <= 72 bytes", "password");
+ if (salt == null)
+ throw new ArgumentNullException("salt");
+ if (salt.Length != SALT_SIZE_BYTES)
+ throw new ArgumentException("BCrypt salt must be 128 bits", "salt");
+ if (cost < MIN_COST || cost > MAX_COST)
+ throw new ArgumentException("BCrypt cost must be from 4..31", "cost");
+
+ return new BCrypt().DeriveRawKey(cost, salt, password);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/BCrypt.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/BCrypt.cs.meta
new file mode 100644
index 00000000..4a26076f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/BCrypt.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 3b99a1fd27e8d8940acf6dc195270f8f
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/BaseKdfBytesGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/BaseKdfBytesGenerator.cs
new file mode 100644
index 00000000..ecc20b22
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/BaseKdfBytesGenerator.cs
@@ -0,0 +1,136 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ /**
+ * Basic KDF generator for derived keys and ivs as defined by IEEE P1363a/ISO 18033
+ *
+ * This implementation is based on ISO 18033/P1363a.
+ */
+ public class BaseKdfBytesGenerator
+ : IDerivationFunction
+ {
+ private int counterStart;
+ private IDigest digest;
+ private byte[] shared;
+ private byte[] iv;
+
+ /**
+ * Construct a KDF Parameters generator.
+ *
+ * @param counterStart value of counter.
+ * @param digest the digest to be used as the source of derived keys.
+ */
+ public BaseKdfBytesGenerator(int counterStart, IDigest digest)
+ {
+ this.counterStart = counterStart;
+ this.digest = digest;
+ }
+
+ public virtual void Init(IDerivationParameters parameters)
+ {
+ if (parameters is KdfParameters)
+ {
+ KdfParameters p = (KdfParameters)parameters;
+
+ shared = p.GetSharedSecret();
+ iv = p.GetIV();
+ }
+ else if (parameters is Iso18033KdfParameters)
+ {
+ Iso18033KdfParameters p = (Iso18033KdfParameters)parameters;
+
+ shared = p.GetSeed();
+ iv = null;
+ }
+ else
+ {
+ throw new ArgumentException("KDF parameters required for KDF Generator");
+ }
+ }
+
+ /**
+ * return the underlying digest.
+ */
+ public virtual IDigest Digest
+ {
+ get { return digest; }
+ }
+
+ /**
+ * fill len bytes of the output buffer with bytes generated from
+ * the derivation function.
+ *
+ * @throws ArgumentException if the size of the request will cause an overflow.
+ * @throws DataLengthException if the out buffer is too small.
+ */
+ public virtual int GenerateBytes(byte[] output, int outOff, int length)
+ {
+ if ((output.Length - length) < outOff)
+ throw new DataLengthException("output buffer too small");
+
+ long oBytes = length;
+ int outLen = digest.GetDigestSize();
+
+ //
+ // this is at odds with the standard implementation, the
+ // maximum value should be hBits * (2^32 - 1) where hBits
+ // is the digest output size in bits. We can't have an
+ // array with a long index at the moment...
+ //
+ if (oBytes > ((2L << 32) - 1))
+ throw new ArgumentException("Output length too large");
+
+ int cThreshold = (int)((oBytes + outLen - 1) / outLen);
+
+ byte[] dig = new byte[digest.GetDigestSize()];
+
+ byte[] C = new byte[4];
+ Pack.UInt32_To_BE((uint)counterStart, C, 0);
+
+ uint counterBase = (uint)(counterStart & ~0xFF);
+
+ for (int i = 0; i < cThreshold; i++)
+ {
+ digest.BlockUpdate(shared, 0, shared.Length);
+ digest.BlockUpdate(C, 0, 4);
+
+ if (iv != null)
+ {
+ digest.BlockUpdate(iv, 0, iv.Length);
+ }
+
+ digest.DoFinal(dig, 0);
+
+ if (length > outLen)
+ {
+ Array.Copy(dig, 0, output, outOff, outLen);
+ outOff += outLen;
+ length -= outLen;
+ }
+ else
+ {
+ Array.Copy(dig, 0, output, outOff, length);
+ }
+
+ if (++C[3] == 0)
+ {
+ counterBase += 0x100;
+ Pack.UInt32_To_BE(counterBase, C, 0);
+ }
+ }
+
+ digest.Reset();
+
+ return (int)oBytes;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/BaseKdfBytesGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/BaseKdfBytesGenerator.cs.meta
new file mode 100644
index 00000000..db27dec0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/BaseKdfBytesGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 529254d7f00c94c4eb4a87e22e280ee0
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHBasicKeyPairGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHBasicKeyPairGenerator.cs
new file mode 100644
index 00000000..9455d84c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHBasicKeyPairGenerator.cs
@@ -0,0 +1,42 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ /**
+ * a basic Diffie-Hellman key pair generator.
+ *
+ * This generates keys consistent for use with the basic algorithm for
+ * Diffie-Hellman.
+ */
+ public class DHBasicKeyPairGenerator
+ : IAsymmetricCipherKeyPairGenerator
+ {
+ private DHKeyGenerationParameters param;
+
+ public virtual void Init(
+ KeyGenerationParameters parameters)
+ {
+ this.param = (DHKeyGenerationParameters)parameters;
+ }
+
+ public virtual AsymmetricCipherKeyPair GenerateKeyPair()
+ {
+ DHKeyGeneratorHelper helper = DHKeyGeneratorHelper.Instance;
+ DHParameters dhp = param.Parameters;
+
+ BigInteger x = helper.CalculatePrivate(dhp, param.Random);
+ BigInteger y = helper.CalculatePublic(dhp, x);
+
+ return new AsymmetricCipherKeyPair(
+ new DHPublicKeyParameters(y, dhp),
+ new DHPrivateKeyParameters(x, dhp));
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHBasicKeyPairGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHBasicKeyPairGenerator.cs.meta
new file mode 100644
index 00000000..de466898
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHBasicKeyPairGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: b7a4dfca0f6e38241991e7bc666269d0
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHKeyGeneratorHelper.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHKeyGeneratorHelper.cs
new file mode 100644
index 00000000..3c4cba5b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHKeyGeneratorHelper.cs
@@ -0,0 +1,76 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Multiplier;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ class DHKeyGeneratorHelper
+ {
+ internal static readonly DHKeyGeneratorHelper Instance = new DHKeyGeneratorHelper();
+
+ private DHKeyGeneratorHelper()
+ {
+ }
+
+ internal BigInteger CalculatePrivate(
+ DHParameters dhParams,
+ SecureRandom random)
+ {
+ int limit = dhParams.L;
+
+ if (limit != 0)
+ {
+ int minWeight = limit >> 2;
+ for (;;)
+ {
+ BigInteger x = new BigInteger(limit, random).SetBit(limit - 1);
+ if (WNafUtilities.GetNafWeight(x) >= minWeight)
+ {
+ return x;
+ }
+ }
+ }
+
+ BigInteger min = BigInteger.Two;
+ int m = dhParams.M;
+ if (m != 0)
+ {
+ min = BigInteger.One.ShiftLeft(m - 1);
+ }
+
+ BigInteger q = dhParams.Q;
+ if (q == null)
+ {
+ q = dhParams.P;
+ }
+ BigInteger max = q.Subtract(BigInteger.Two);
+
+ {
+ int minWeight = max.BitLength >> 2;
+ for (;;)
+ {
+ BigInteger x = BigIntegers.CreateRandomInRange(min, max, random);
+ if (WNafUtilities.GetNafWeight(x) >= minWeight)
+ {
+ return x;
+ }
+ }
+ }
+ }
+
+ internal BigInteger CalculatePublic(
+ DHParameters dhParams,
+ BigInteger x)
+ {
+ return dhParams.G.ModPow(x, dhParams.P);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHKeyGeneratorHelper.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHKeyGeneratorHelper.cs.meta
new file mode 100644
index 00000000..709d116e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHKeyGeneratorHelper.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 98272963180479a45b4495273799bb5c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHKeyPairGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHKeyPairGenerator.cs
new file mode 100644
index 00000000..a9eba6e8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHKeyPairGenerator.cs
@@ -0,0 +1,42 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ /**
+ * a Diffie-Hellman key pair generator.
+ *
+ * This generates keys consistent for use in the MTI/A0 key agreement protocol
+ * as described in "Handbook of Applied Cryptography", Pages 516-519.
+ */
+ public class DHKeyPairGenerator
+ : IAsymmetricCipherKeyPairGenerator
+ {
+ private DHKeyGenerationParameters param;
+
+ public virtual void Init(
+ KeyGenerationParameters parameters)
+ {
+ this.param = (DHKeyGenerationParameters)parameters;
+ }
+
+ public virtual AsymmetricCipherKeyPair GenerateKeyPair()
+ {
+ DHKeyGeneratorHelper helper = DHKeyGeneratorHelper.Instance;
+ DHParameters dhp = param.Parameters;
+
+ BigInteger x = helper.CalculatePrivate(dhp, param.Random);
+ BigInteger y = helper.CalculatePublic(dhp, x);
+
+ return new AsymmetricCipherKeyPair(
+ new DHPublicKeyParameters(y, dhp),
+ new DHPrivateKeyParameters(x, dhp));
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHKeyPairGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHKeyPairGenerator.cs.meta
new file mode 100644
index 00000000..82b4e2fa
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHKeyPairGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c6dd5179b7382f74dbd970c11817e3b8
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHParametersGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHParametersGenerator.cs
new file mode 100644
index 00000000..9013d0bf
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHParametersGenerator.cs
@@ -0,0 +1,49 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ public class DHParametersGenerator
+ {
+ private int size;
+ private int certainty;
+ private SecureRandom random;
+
+ public virtual void Init(
+ int size,
+ int certainty,
+ SecureRandom random)
+ {
+ this.size = size;
+ this.certainty = certainty;
+ this.random = random;
+ }
+
+ /**
+ * which Generates the p and g values from the given parameters,
+ * returning the DHParameters object.
+ *
+ * Note: can take a while...
+ */
+ public virtual DHParameters GenerateParameters()
+ {
+ //
+ // find a safe prime p where p = 2*q + 1, where p and q are prime.
+ //
+ BigInteger[] safePrimes = DHParametersHelper.GenerateSafePrimes(size, certainty, random);
+
+ BigInteger p = safePrimes[0];
+ BigInteger q = safePrimes[1];
+ BigInteger g = DHParametersHelper.SelectGenerator(p, q, random);
+
+ return new DHParameters(p, g, q, BigInteger.Two, null);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHParametersGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHParametersGenerator.cs.meta
new file mode 100644
index 00000000..fd27cd09
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHParametersGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0fae909793a7d5c40b20696050343040
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHParametersHelper.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHParametersHelper.cs
new file mode 100644
index 00000000..77cafb64
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHParametersHelper.cs
@@ -0,0 +1,160 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Multiplier;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ internal class DHParametersHelper
+ {
+ private static readonly BigInteger Six = BigInteger.ValueOf(6);
+
+ private static readonly int[][] primeLists = BigInteger.primeLists;
+ private static readonly int[] primeProducts = BigInteger.primeProducts;
+ private static readonly BigInteger[] BigPrimeProducts = ConstructBigPrimeProducts(primeProducts);
+
+ private static BigInteger[] ConstructBigPrimeProducts(int[] primeProducts)
+ {
+ BigInteger[] bpp = new BigInteger[primeProducts.Length];
+ for (int i = 0; i < bpp.Length; ++i)
+ {
+ bpp[i] = BigInteger.ValueOf(primeProducts[i]);
+ }
+ return bpp;
+ }
+
+ /*
+ * Finds a pair of prime BigInteger's {p, q: p = 2q + 1}
+ *
+ * (see: Handbook of Applied Cryptography 4.86)
+ */
+ internal static BigInteger[] GenerateSafePrimes(int size, int certainty, SecureRandom random)
+ {
+ BigInteger p, q;
+ int qLength = size - 1;
+ int minWeight = size >> 2;
+
+ if (size <= 32)
+ {
+ for (;;)
+ {
+ q = new BigInteger(qLength, 2, random);
+
+ p = q.ShiftLeft(1).Add(BigInteger.One);
+
+ if (!p.IsProbablePrime(certainty, true))
+ continue;
+
+ if (certainty > 2 && !q.IsProbablePrime(certainty, true))
+ continue;
+
+ break;
+ }
+ }
+ else
+ {
+ // Note: Modified from Java version for speed
+ for (;;)
+ {
+ q = new BigInteger(qLength, 0, random);
+
+ retry:
+ for (int i = 0; i < primeLists.Length; ++i)
+ {
+ int test = q.Remainder(BigPrimeProducts[i]).IntValue;
+
+ if (i == 0)
+ {
+ int rem3 = test % 3;
+ if (rem3 != 2)
+ {
+ int diff = 2 * rem3 + 2;
+ q = q.Add(BigInteger.ValueOf(diff));
+ test = (test + diff) % primeProducts[i];
+ }
+ }
+
+ int[] primeList = primeLists[i];
+ for (int j = 0; j < primeList.Length; ++j)
+ {
+ int prime = primeList[j];
+ int qRem = test % prime;
+ if (qRem == 0 || qRem == (prime >> 1))
+ {
+ q = q.Add(Six);
+ goto retry;
+ }
+ }
+ }
+
+ if (q.BitLength != qLength)
+ continue;
+
+ if (!q.RabinMillerTest(2, random, true))
+ continue;
+
+ p = q.ShiftLeft(1).Add(BigInteger.One);
+
+ if (!p.RabinMillerTest(certainty, random, true))
+ continue;
+
+ if (certainty > 2 && !q.RabinMillerTest(certainty - 2, random, true))
+ continue;
+
+ /*
+ * Require a minimum weight of the NAF representation, since low-weight primes may be
+ * weak against a version of the number-field-sieve for the discrete-logarithm-problem.
+ *
+ * See "The number field sieve for integers of low weight", Oliver Schirokauer.
+ */
+ if (WNafUtilities.GetNafWeight(p) < minWeight)
+ continue;
+
+ break;
+ }
+ }
+
+ return new BigInteger[] { p, q };
+ }
+
+ /*
+ * Select a high order element of the multiplicative group Zp*
+ *
+ * p and q must be s.t. p = 2*q + 1, where p and q are prime (see generateSafePrimes)
+ */
+ internal static BigInteger SelectGenerator(BigInteger p, BigInteger q, SecureRandom random)
+ {
+ BigInteger pMinusTwo = p.Subtract(BigInteger.Two);
+ BigInteger g;
+
+ /*
+ * (see: Handbook of Applied Cryptography 4.80)
+ */
+// do
+// {
+// g = BigIntegers.CreateRandomInRange(BigInteger.Two, pMinusTwo, random);
+// }
+// while (g.ModPow(BigInteger.Two, p).Equals(BigInteger.One)
+// || g.ModPow(q, p).Equals(BigInteger.One));
+
+ /*
+ * RFC 2631 2.2.1.2 (and see: Handbook of Applied Cryptography 4.81)
+ */
+ do
+ {
+ BigInteger h = BigIntegers.CreateRandomInRange(BigInteger.Two, pMinusTwo, random);
+
+ g = h.ModPow(BigInteger.Two, p);
+ }
+ while (g.Equals(BigInteger.One));
+
+ return g;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHParametersHelper.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHParametersHelper.cs.meta
new file mode 100644
index 00000000..4ac84dcd
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DHParametersHelper.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: d4fdec6c91ff77e41add37910a845fa0
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DesEdeKeyGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DesEdeKeyGenerator.cs
new file mode 100644
index 00000000..f5598056
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DesEdeKeyGenerator.cs
@@ -0,0 +1,71 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ public class DesEdeKeyGenerator
+ : DesKeyGenerator
+ {
+ public DesEdeKeyGenerator()
+ {
+ }
+
+ internal DesEdeKeyGenerator(
+ int defaultStrength)
+ : base(defaultStrength)
+ {
+ }
+
+ /**
+ * initialise the key generator - if strength is set to zero
+ * the key Generated will be 192 bits in size, otherwise
+ * strength can be 128 or 192 (or 112 or 168 if you don't count
+ * parity bits), depending on whether you wish to do 2-key or 3-key
+ * triple DES.
+ *
+ * @param param the parameters to be used for key generation
+ */
+ protected override void engineInit(
+ KeyGenerationParameters parameters)
+ {
+ this.random = parameters.Random;
+ this.strength = (parameters.Strength + 7) / 8;
+
+ if (strength == 0 || strength == (168 / 8))
+ {
+ strength = DesEdeParameters.DesEdeKeyLength;
+ }
+ else if (strength == (112 / 8))
+ {
+ strength = 2 * DesEdeParameters.DesKeyLength;
+ }
+ else if (strength != DesEdeParameters.DesEdeKeyLength
+ && strength != (2 * DesEdeParameters.DesKeyLength))
+ {
+ throw new ArgumentException("DESede key must be "
+ + (DesEdeParameters.DesEdeKeyLength * 8) + " or "
+ + (2 * 8 * DesEdeParameters.DesKeyLength)
+ + " bits long.");
+ }
+ }
+
+ protected override byte[] engineGenerateKey()
+ {
+ byte[] newKey = new byte[strength];
+
+ do
+ {
+ random.NextBytes(newKey);
+ DesEdeParameters.SetOddParity(newKey);
+ }
+ while (DesEdeParameters.IsWeakKey(newKey, 0, newKey.Length) || !DesEdeParameters.IsRealEdeKey(newKey, 0));
+
+ return newKey;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DesEdeKeyGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DesEdeKeyGenerator.cs.meta
new file mode 100644
index 00000000..4488aa9e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DesEdeKeyGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 2aaa0fb6f892b1f46a0b89ffe9d98654
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DesKeyGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DesKeyGenerator.cs
new file mode 100644
index 00000000..845583f3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DesKeyGenerator.cs
@@ -0,0 +1,61 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ public class DesKeyGenerator
+ : CipherKeyGenerator
+ {
+ public DesKeyGenerator()
+ {
+ }
+
+ internal DesKeyGenerator(
+ int defaultStrength)
+ : base(defaultStrength)
+ {
+ }
+
+ /**
+ * initialise the key generator - if strength is set to zero
+ * the key generated will be 64 bits in size, otherwise
+ * strength can be 64 or 56 bits (if you don't count the parity bits).
+ *
+ * @param param the parameters to be used for key generation
+ */
+ protected override void engineInit(
+ KeyGenerationParameters parameters)
+ {
+ base.engineInit(parameters);
+
+ if (strength == 0 || strength == (56 / 8))
+ {
+ strength = DesParameters.DesKeyLength;
+ }
+ else if (strength != DesParameters.DesKeyLength)
+ {
+ throw new ArgumentException(
+ "DES key must be " + (DesParameters.DesKeyLength * 8) + " bits long.");
+ }
+ }
+
+ protected override byte[] engineGenerateKey()
+ {
+ byte[] newKey = new byte[DesParameters.DesKeyLength];
+
+ do
+ {
+ random.NextBytes(newKey);
+ DesParameters.SetOddParity(newKey);
+ }
+ while (DesParameters.IsWeakKey(newKey, 0));
+
+ return newKey;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DesKeyGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DesKeyGenerator.cs.meta
new file mode 100644
index 00000000..6f8f5325
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DesKeyGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 2f5d7742609933942bd3204450aabe4e
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DsaKeyPairGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DsaKeyPairGenerator.cs
new file mode 100644
index 00000000..58dec1b5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DsaKeyPairGenerator.cs
@@ -0,0 +1,76 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Multiplier;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ /**
+ * a DSA key pair generator.
+ *
+ * This Generates DSA keys in line with the method described
+ * in FIPS 186-3 B.1 FFC Key Pair Generation.
+ */
+ public class DsaKeyPairGenerator
+ : IAsymmetricCipherKeyPairGenerator
+ {
+ private static readonly BigInteger One = BigInteger.One;
+
+ private DsaKeyGenerationParameters param;
+
+ public void Init(
+ KeyGenerationParameters parameters)
+ {
+ if (parameters == null)
+ throw new ArgumentNullException("parameters");
+
+ // Note: If we start accepting instances of KeyGenerationParameters,
+ // must apply constraint checking on strength (see DsaParametersGenerator.Init)
+
+ this.param = (DsaKeyGenerationParameters) parameters;
+ }
+
+ public AsymmetricCipherKeyPair GenerateKeyPair()
+ {
+ DsaParameters dsaParams = param.Parameters;
+
+ BigInteger x = GeneratePrivateKey(dsaParams.Q, param.Random);
+ BigInteger y = CalculatePublicKey(dsaParams.P, dsaParams.G, x);
+
+ return new AsymmetricCipherKeyPair(
+ new DsaPublicKeyParameters(y, dsaParams),
+ new DsaPrivateKeyParameters(x, dsaParams));
+ }
+
+ private static BigInteger GeneratePrivateKey(BigInteger q, SecureRandom random)
+ {
+ // B.1.2 Key Pair Generation by Testing Candidates
+ int minWeight = q.BitLength >> 2;
+ for (;;)
+ {
+ // TODO Prefer this method? (change test cases that used fixed random)
+ // B.1.1 Key Pair Generation Using Extra Random Bits
+ //BigInteger x = new BigInteger(q.BitLength + 64, random).Mod(q.Subtract(One)).Add(One);
+
+ BigInteger x = BigIntegers.CreateRandomInRange(One, q.Subtract(One), random);
+ if (WNafUtilities.GetNafWeight(x) >= minWeight)
+ {
+ return x;
+ }
+ }
+ }
+
+ private static BigInteger CalculatePublicKey(BigInteger p, BigInteger g, BigInteger x)
+ {
+ return g.ModPow(x, p);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DsaKeyPairGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DsaKeyPairGenerator.cs.meta
new file mode 100644
index 00000000..0c06ea31
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DsaKeyPairGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 81ed675e8e1609d468d4e8957e891e0e
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DsaParametersGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DsaParametersGenerator.cs
new file mode 100644
index 00000000..26dfca3f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DsaParametersGenerator.cs
@@ -0,0 +1,359 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ /**
+ * Generate suitable parameters for DSA, in line with FIPS 186-2, or FIPS 186-3.
+ */
+ public class DsaParametersGenerator
+ {
+ private IDigest digest;
+ private int L, N;
+ private int certainty;
+ private SecureRandom random;
+ private bool use186_3;
+ private int usageIndex;
+
+ public DsaParametersGenerator()
+ : this(new Sha1Digest())
+ {
+ }
+
+ public DsaParametersGenerator(IDigest digest)
+ {
+ this.digest = digest;
+ }
+
+ /// Initialise the generator
+ /// This form can only be used for older DSA (pre-DSA2) parameters
+ /// the size of keys in bits (from 512 up to 1024, and a multiple of 64)
+ /// measure of robustness of primes (at least 80 for FIPS 186-2 compliance)
+ /// the source of randomness to use
+ public virtual void Init(
+ int size,
+ int certainty,
+ SecureRandom random)
+ {
+ if (!IsValidDsaStrength(size))
+ throw new ArgumentException("size must be from 512 - 1024 and a multiple of 64", "size");
+
+ this.use186_3 = false;
+ this.L = size;
+ this.N = GetDefaultN(size);
+ this.certainty = certainty;
+ this.random = random;
+ }
+
+ /// Initialise the generator for DSA 2
+ /// You must use this Init method if you need to generate parameters for DSA 2 keys
+ /// An instance of DsaParameterGenerationParameters used to configure this generator
+ public virtual void Init(DsaParameterGenerationParameters parameters)
+ {
+ // TODO Should we enforce the minimum 'certainty' values as per C.3 Table C.1?
+ this.use186_3 = true;
+ this.L = parameters.L;
+ this.N = parameters.N;
+ this.certainty = parameters.Certainty;
+ this.random = parameters.Random;
+ this.usageIndex = parameters.UsageIndex;
+
+ if ((L < 1024 || L > 3072) || L % 1024 != 0)
+ throw new ArgumentException("Values must be between 1024 and 3072 and a multiple of 1024", "L");
+ if (L == 1024 && N != 160)
+ throw new ArgumentException("N must be 160 for L = 1024");
+ if (L == 2048 && (N != 224 && N != 256))
+ throw new ArgumentException("N must be 224 or 256 for L = 2048");
+ if (L == 3072 && N != 256)
+ throw new ArgumentException("N must be 256 for L = 3072");
+
+ if (digest.GetDigestSize() * 8 < N)
+ throw new InvalidOperationException("Digest output size too small for value of N");
+ }
+
+ /// Generates a set of DsaParameters
+ /// Can take a while...
+ public virtual DsaParameters GenerateParameters()
+ {
+ return use186_3
+ ? GenerateParameters_FIPS186_3()
+ : GenerateParameters_FIPS186_2();
+ }
+
+ protected virtual DsaParameters GenerateParameters_FIPS186_2()
+ {
+ byte[] seed = new byte[20];
+ byte[] part1 = new byte[20];
+ byte[] part2 = new byte[20];
+ byte[] u = new byte[20];
+ int n = (L - 1) / 160;
+ byte[] w = new byte[L / 8];
+
+ if (!(digest is Sha1Digest))
+ throw new InvalidOperationException("can only use SHA-1 for generating FIPS 186-2 parameters");
+
+ for (;;)
+ {
+ random.NextBytes(seed);
+
+ Hash(digest, seed, part1);
+ Array.Copy(seed, 0, part2, 0, seed.Length);
+ Inc(part2);
+ Hash(digest, part2, part2);
+
+ for (int i = 0; i != u.Length; i++)
+ {
+ u[i] = (byte)(part1[i] ^ part2[i]);
+ }
+
+ u[0] |= (byte)0x80;
+ u[19] |= (byte)0x01;
+
+ BigInteger q = new BigInteger(1, u);
+
+ if (!q.IsProbablePrime(certainty))
+ continue;
+
+ byte[] offset = Arrays.Clone(seed);
+ Inc(offset);
+
+ for (int counter = 0; counter < 4096; ++counter)
+ {
+ for (int k = 0; k < n; k++)
+ {
+ Inc(offset);
+ Hash(digest, offset, part1);
+ Array.Copy(part1, 0, w, w.Length - (k + 1) * part1.Length, part1.Length);
+ }
+
+ Inc(offset);
+ Hash(digest, offset, part1);
+ Array.Copy(part1, part1.Length - ((w.Length - (n) * part1.Length)), w, 0, w.Length - n * part1.Length);
+
+ w[0] |= (byte)0x80;
+
+ BigInteger x = new BigInteger(1, w);
+
+ BigInteger c = x.Mod(q.ShiftLeft(1));
+
+ BigInteger p = x.Subtract(c.Subtract(BigInteger.One));
+
+ if (p.BitLength != L)
+ continue;
+
+ if (p.IsProbablePrime(certainty))
+ {
+ BigInteger g = CalculateGenerator_FIPS186_2(p, q, random);
+
+ return new DsaParameters(p, q, g, new DsaValidationParameters(seed, counter));
+ }
+ }
+ }
+ }
+
+ protected virtual BigInteger CalculateGenerator_FIPS186_2(BigInteger p, BigInteger q, SecureRandom r)
+ {
+ BigInteger e = p.Subtract(BigInteger.One).Divide(q);
+ BigInteger pSub2 = p.Subtract(BigInteger.Two);
+
+ for (;;)
+ {
+ BigInteger h = BigIntegers.CreateRandomInRange(BigInteger.Two, pSub2, r);
+ BigInteger g = h.ModPow(e, p);
+
+ if (g.BitLength > 1)
+ return g;
+ }
+ }
+
+ /**
+ * generate suitable parameters for DSA, in line with
+ * FIPS 186-3 A.1 Generation of the FFC Primes p and q.
+ */
+ protected virtual DsaParameters GenerateParameters_FIPS186_3()
+ {
+// A.1.1.2 Generation of the Probable Primes p and q Using an Approved Hash Function
+ IDigest d = digest;
+ int outlen = d.GetDigestSize() * 8;
+
+// 1. Check that the (L, N) pair is in the list of acceptable (L, N pairs) (see Section 4.2). If
+// the pair is not in the list, then return INVALID.
+ // Note: checked at initialisation
+
+// 2. If (seedlen < N), then return INVALID.
+ // FIXME This should be configurable (must be >= N)
+ int seedlen = N;
+ byte[] seed = new byte[seedlen / 8];
+
+// 3. n = ceiling(L ⁄ outlen) – 1.
+ int n = (L - 1) / outlen;
+
+// 4. b = L – 1 – (n ∗ outlen).
+ int b = (L - 1) % outlen;
+
+ byte[] output = new byte[d.GetDigestSize()];
+ for (;;)
+ {
+// 5. Get an arbitrary sequence of seedlen bits as the domain_parameter_seed.
+ random.NextBytes(seed);
+
+// 6. U = Hash (domain_parameter_seed) mod 2^(N–1).
+ Hash(d, seed, output);
+ BigInteger U = new BigInteger(1, output).Mod(BigInteger.One.ShiftLeft(N - 1));
+
+// 7. q = 2^(N–1) + U + 1 – ( U mod 2).
+ BigInteger q = U.SetBit(0).SetBit(N - 1);
+
+// 8. Test whether or not q is prime as specified in Appendix C.3.
+ // TODO Review C.3 for primality checking
+ if (!q.IsProbablePrime(certainty))
+ {
+// 9. If q is not a prime, then go to step 5.
+ continue;
+ }
+
+// 10. offset = 1.
+ // Note: 'offset' value managed incrementally
+ byte[] offset = Arrays.Clone(seed);
+
+// 11. For counter = 0 to (4L – 1) do
+ int counterLimit = 4 * L;
+ for (int counter = 0; counter < counterLimit; ++counter)
+ {
+// 11.1 For j = 0 to n do
+// Vj = Hash ((domain_parameter_seed + offset + j) mod 2^seedlen).
+// 11.2 W = V0 + (V1 ∗ 2^outlen) + ... + (V^(n–1) ∗ 2^((n–1) ∗ outlen)) + ((Vn mod 2^b) ∗ 2^(n ∗ outlen)).
+ // TODO Assemble w as a byte array
+ BigInteger W = BigInteger.Zero;
+ for (int j = 0, exp = 0; j <= n; ++j, exp += outlen)
+ {
+ Inc(offset);
+ Hash(d, offset, output);
+
+ BigInteger Vj = new BigInteger(1, output);
+ if (j == n)
+ {
+ Vj = Vj.Mod(BigInteger.One.ShiftLeft(b));
+ }
+
+ W = W.Add(Vj.ShiftLeft(exp));
+ }
+
+// 11.3 X = W + 2^(L–1). Comment: 0 ≤ W < 2L–1; hence, 2L–1 ≤ X < 2L.
+ BigInteger X = W.Add(BigInteger.One.ShiftLeft(L - 1));
+
+// 11.4 c = X mod 2q.
+ BigInteger c = X.Mod(q.ShiftLeft(1));
+
+// 11.5 p = X - (c - 1). Comment: p ≡ 1 (mod 2q).
+ BigInteger p = X.Subtract(c.Subtract(BigInteger.One));
+
+ // 11.6 If (p < 2^(L - 1)), then go to step 11.9
+ if (p.BitLength != L)
+ continue;
+
+// 11.7 Test whether or not p is prime as specified in Appendix C.3.
+ // TODO Review C.3 for primality checking
+ if (p.IsProbablePrime(certainty))
+ {
+// 11.8 If p is determined to be prime, then return VALID and the values of p, q and
+// (optionally) the values of domain_parameter_seed and counter.
+ // TODO Make configurable (8-bit unsigned)?
+
+ if (usageIndex >= 0)
+ {
+ BigInteger g = CalculateGenerator_FIPS186_3_Verifiable(d, p, q, seed, usageIndex);
+ if (g != null)
+ return new DsaParameters(p, q, g, new DsaValidationParameters(seed, counter, usageIndex));
+ }
+
+ {
+ BigInteger g = CalculateGenerator_FIPS186_3_Unverifiable(p, q, random);
+
+ return new DsaParameters(p, q, g, new DsaValidationParameters(seed, counter));
+ }
+ }
+
+// 11.9 offset = offset + n + 1. Comment: Increment offset; then, as part of
+// the loop in step 11, increment counter; if
+// counter < 4L, repeat steps 11.1 through 11.8.
+ // Note: 'offset' value already incremented in inner loop
+ }
+// 12. Go to step 5.
+ }
+ }
+
+ protected virtual BigInteger CalculateGenerator_FIPS186_3_Unverifiable(BigInteger p, BigInteger q,
+ SecureRandom r)
+ {
+ return CalculateGenerator_FIPS186_2(p, q, r);
+ }
+
+ protected virtual BigInteger CalculateGenerator_FIPS186_3_Verifiable(IDigest d, BigInteger p, BigInteger q,
+ byte[] seed, int index)
+ {
+ // A.2.3 Verifiable Canonical Generation of the Generator g
+ BigInteger e = p.Subtract(BigInteger.One).Divide(q);
+ byte[] ggen = Hex.Decode("6767656E");
+
+ // 7. U = domain_parameter_seed || "ggen" || index || count.
+ byte[] U = new byte[seed.Length + ggen.Length + 1 + 2];
+ Array.Copy(seed, 0, U, 0, seed.Length);
+ Array.Copy(ggen, 0, U, seed.Length, ggen.Length);
+ U[U.Length - 3] = (byte)index;
+
+ byte[] w = new byte[d.GetDigestSize()];
+ for (int count = 1; count < (1 << 16); ++count)
+ {
+ Inc(U);
+ Hash(d, U, w);
+ BigInteger W = new BigInteger(1, w);
+ BigInteger g = W.ModPow(e, p);
+
+ if (g.CompareTo(BigInteger.Two) >= 0)
+ return g;
+ }
+
+ return null;
+ }
+
+ private static bool IsValidDsaStrength(
+ int strength)
+ {
+ return strength >= 512 && strength <= 1024 && strength % 64 == 0;
+ }
+
+ protected static void Hash(IDigest d, byte[] input, byte[] output)
+ {
+ d.BlockUpdate(input, 0, input.Length);
+ d.DoFinal(output, 0);
+ }
+
+ private static int GetDefaultN(int L)
+ {
+ return L > 1024 ? 256 : 160;
+ }
+
+ protected static void Inc(byte[] buf)
+ {
+ for (int i = buf.Length - 1; i >= 0; --i)
+ {
+ byte b = (byte)(buf[i] + 1);
+ buf[i] = b;
+
+ if (b != 0)
+ break;
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DsaParametersGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DsaParametersGenerator.cs.meta
new file mode 100644
index 00000000..fb0a7bf7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/DsaParametersGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 5d1e4f356c022fc448e391006e5ad3ff
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/ECKeyPairGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/ECKeyPairGenerator.cs
new file mode 100644
index 00000000..6bb89a51
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/ECKeyPairGenerator.cs
@@ -0,0 +1,166 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Sec;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.TeleTrust;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.EC;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Multiplier;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ public class ECKeyPairGenerator
+ : IAsymmetricCipherKeyPairGenerator
+ {
+ private readonly string algorithm;
+
+ private ECDomainParameters parameters;
+ private DerObjectIdentifier publicKeyParamSet;
+ private SecureRandom random;
+
+ public ECKeyPairGenerator()
+ : this("EC")
+ {
+ }
+
+ public ECKeyPairGenerator(
+ string algorithm)
+ {
+ if (algorithm == null)
+ throw new ArgumentNullException("algorithm");
+
+ this.algorithm = ECKeyParameters.VerifyAlgorithmName(algorithm);
+ }
+
+ public void Init(
+ KeyGenerationParameters parameters)
+ {
+ if (parameters is ECKeyGenerationParameters)
+ {
+ ECKeyGenerationParameters ecP = (ECKeyGenerationParameters) parameters;
+
+ this.publicKeyParamSet = ecP.PublicKeyParamSet;
+ this.parameters = ecP.DomainParameters;
+ }
+ else
+ {
+ DerObjectIdentifier oid;
+ switch (parameters.Strength)
+ {
+ case 192:
+ oid = X9ObjectIdentifiers.Prime192v1;
+ break;
+ case 224:
+ oid = SecObjectIdentifiers.SecP224r1;
+ break;
+ case 239:
+ oid = X9ObjectIdentifiers.Prime239v1;
+ break;
+ case 256:
+ oid = X9ObjectIdentifiers.Prime256v1;
+ break;
+ case 384:
+ oid = SecObjectIdentifiers.SecP384r1;
+ break;
+ case 521:
+ oid = SecObjectIdentifiers.SecP521r1;
+ break;
+ default:
+ throw new InvalidParameterException("unknown key size.");
+ }
+
+ X9ECParameters ecps = FindECCurveByOid(oid);
+
+ this.publicKeyParamSet = oid;
+ this.parameters = new ECDomainParameters(
+ ecps.Curve, ecps.G, ecps.N, ecps.H, ecps.GetSeed());
+ }
+
+ this.random = parameters.Random;
+
+ if (this.random == null)
+ {
+ this.random = new SecureRandom();
+ }
+ }
+
+ /**
+ * Given the domain parameters this routine generates an EC key
+ * pair in accordance with X9.62 section 5.2.1 pages 26, 27.
+ */
+ public AsymmetricCipherKeyPair GenerateKeyPair()
+ {
+ BigInteger n = parameters.N;
+ BigInteger d;
+ int minWeight = n.BitLength >> 2;
+
+ for (;;)
+ {
+ d = new BigInteger(n.BitLength, random);
+
+ if (d.CompareTo(BigInteger.Two) < 0 || d.CompareTo(n) >= 0)
+ continue;
+
+ if (WNafUtilities.GetNafWeight(d) < minWeight)
+ continue;
+
+ break;
+ }
+
+ ECPoint q = CreateBasePointMultiplier().Multiply(parameters.G, d);
+
+ if (publicKeyParamSet != null)
+ {
+ return new AsymmetricCipherKeyPair(
+ new ECPublicKeyParameters(algorithm, q, publicKeyParamSet),
+ new ECPrivateKeyParameters(algorithm, d, publicKeyParamSet));
+ }
+
+ return new AsymmetricCipherKeyPair(
+ new ECPublicKeyParameters(algorithm, q, parameters),
+ new ECPrivateKeyParameters(algorithm, d, parameters));
+ }
+
+ protected virtual ECMultiplier CreateBasePointMultiplier()
+ {
+ return new FixedPointCombMultiplier();
+ }
+
+ internal static X9ECParameters FindECCurveByOid(DerObjectIdentifier oid)
+ {
+ // TODO ECGost3410NamedCurves support (returns ECDomainParameters though)
+
+ X9ECParameters ecP = CustomNamedCurves.GetByOid(oid);
+ if (ecP == null)
+ {
+ ecP = ECNamedCurveTable.GetByOid(oid);
+ }
+ return ecP;
+ }
+
+ internal static ECPublicKeyParameters GetCorrespondingPublicKey(
+ ECPrivateKeyParameters privKey)
+ {
+ ECDomainParameters ec = privKey.Parameters;
+ ECPoint q = new FixedPointCombMultiplier().Multiply(ec.G, privKey.D);
+
+ if (privKey.PublicKeyParamSet != null)
+ {
+ return new ECPublicKeyParameters(privKey.AlgorithmName, q, privKey.PublicKeyParamSet);
+ }
+
+ return new ECPublicKeyParameters(privKey.AlgorithmName, q, ec);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/ECKeyPairGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/ECKeyPairGenerator.cs.meta
new file mode 100644
index 00000000..f483b84f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/ECKeyPairGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: dd6193d5b658f3549963a15501652b67
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Ed25519KeyPairGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Ed25519KeyPairGenerator.cs
new file mode 100644
index 00000000..12907cf0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Ed25519KeyPairGenerator.cs
@@ -0,0 +1,29 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ public class Ed25519KeyPairGenerator
+ : IAsymmetricCipherKeyPairGenerator
+ {
+ private SecureRandom random;
+
+ public virtual void Init(KeyGenerationParameters parameters)
+ {
+ this.random = parameters.Random;
+ }
+
+ public virtual AsymmetricCipherKeyPair GenerateKeyPair()
+ {
+ Ed25519PrivateKeyParameters privateKey = new Ed25519PrivateKeyParameters(random);
+ Ed25519PublicKeyParameters publicKey = privateKey.GeneratePublicKey();
+ return new AsymmetricCipherKeyPair(publicKey, privateKey);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Ed25519KeyPairGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Ed25519KeyPairGenerator.cs.meta
new file mode 100644
index 00000000..b5889e72
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Ed25519KeyPairGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: e2a3de68bed278f408115696520ae15f
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Ed448KeyPairGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Ed448KeyPairGenerator.cs
new file mode 100644
index 00000000..d86183d7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Ed448KeyPairGenerator.cs
@@ -0,0 +1,29 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ public class Ed448KeyPairGenerator
+ : IAsymmetricCipherKeyPairGenerator
+ {
+ private SecureRandom random;
+
+ public virtual void Init(KeyGenerationParameters parameters)
+ {
+ this.random = parameters.Random;
+ }
+
+ public virtual AsymmetricCipherKeyPair GenerateKeyPair()
+ {
+ Ed448PrivateKeyParameters privateKey = new Ed448PrivateKeyParameters(random);
+ Ed448PublicKeyParameters publicKey = privateKey.GeneratePublicKey();
+ return new AsymmetricCipherKeyPair(publicKey, privateKey);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Ed448KeyPairGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Ed448KeyPairGenerator.cs.meta
new file mode 100644
index 00000000..26fcf3f7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Ed448KeyPairGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 56076fa04e5259c439c2b244cf9b73c8
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/ElGamalKeyPairGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/ElGamalKeyPairGenerator.cs
new file mode 100644
index 00000000..b9fef7d9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/ElGamalKeyPairGenerator.cs
@@ -0,0 +1,44 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ /**
+ * a ElGamal key pair generator.
+ *
+ * This Generates keys consistent for use with ElGamal as described in
+ * page 164 of "Handbook of Applied Cryptography".
+ */
+ public class ElGamalKeyPairGenerator
+ : IAsymmetricCipherKeyPairGenerator
+ {
+ private ElGamalKeyGenerationParameters param;
+
+ public void Init(
+ KeyGenerationParameters parameters)
+ {
+ this.param = (ElGamalKeyGenerationParameters) parameters;
+ }
+
+ public AsymmetricCipherKeyPair GenerateKeyPair()
+ {
+ DHKeyGeneratorHelper helper = DHKeyGeneratorHelper.Instance;
+ ElGamalParameters egp = param.Parameters;
+ DHParameters dhp = new DHParameters(egp.P, egp.G, null, 0, egp.L);
+
+ BigInteger x = helper.CalculatePrivate(dhp, param.Random);
+ BigInteger y = helper.CalculatePublic(dhp, x);
+
+ return new AsymmetricCipherKeyPair(
+ new ElGamalPublicKeyParameters(y, egp),
+ new ElGamalPrivateKeyParameters(x, egp));
+ }
+ }
+
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/ElGamalKeyPairGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/ElGamalKeyPairGenerator.cs.meta
new file mode 100644
index 00000000..972fe84d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/ElGamalKeyPairGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0d3c646aa86666e4ca77bdb7f900d2df
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/ElGamalParametersGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/ElGamalParametersGenerator.cs
new file mode 100644
index 00000000..234d6f64
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/ElGamalParametersGenerator.cs
@@ -0,0 +1,50 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ public class ElGamalParametersGenerator
+ {
+ private int size;
+ private int certainty;
+ private SecureRandom random;
+
+ public void Init(
+ int size,
+ int certainty,
+ SecureRandom random)
+ {
+ this.size = size;
+ this.certainty = certainty;
+ this.random = random;
+ }
+
+ /**
+ * which Generates the p and g values from the given parameters,
+ * returning the ElGamalParameters object.
+ *
+ * Note: can take a while...
+ *
+ */
+ public ElGamalParameters GenerateParameters()
+ {
+ //
+ // find a safe prime p where p = 2*q + 1, where p and q are prime.
+ //
+ BigInteger[] safePrimes = DHParametersHelper.GenerateSafePrimes(size, certainty, random);
+
+ BigInteger p = safePrimes[0];
+ BigInteger q = safePrimes[1];
+ BigInteger g = DHParametersHelper.SelectGenerator(p, q, random);
+
+ return new ElGamalParameters(p, g);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/ElGamalParametersGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/ElGamalParametersGenerator.cs.meta
new file mode 100644
index 00000000..ec9f323a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/ElGamalParametersGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0463e1119f1f8b94182ba9a9cdf26312
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/GOST3410KeyPairGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/GOST3410KeyPairGenerator.cs
new file mode 100644
index 00000000..eff645be
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/GOST3410KeyPairGenerator.cs
@@ -0,0 +1,86 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Multiplier;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ /**
+ * a GOST3410 key pair generator.
+ * This generates GOST3410 keys in line with the method described
+ * in GOST R 34.10-94.
+ */
+ public class Gost3410KeyPairGenerator
+ : IAsymmetricCipherKeyPairGenerator
+ {
+ private Gost3410KeyGenerationParameters param;
+
+ public void Init(
+ KeyGenerationParameters parameters)
+ {
+ if (parameters is Gost3410KeyGenerationParameters)
+ {
+ this.param = (Gost3410KeyGenerationParameters) parameters;
+ }
+ else
+ {
+ Gost3410KeyGenerationParameters kgp = new Gost3410KeyGenerationParameters(
+ parameters.Random,
+ CryptoProObjectIdentifiers.GostR3410x94CryptoProA);
+
+ if (parameters.Strength != kgp.Parameters.P.BitLength - 1)
+ {
+ // TODO Should we complain?
+ }
+
+ this.param = kgp;
+ }
+ }
+
+ public AsymmetricCipherKeyPair GenerateKeyPair()
+ {
+ SecureRandom random = param.Random;
+ Gost3410Parameters gost3410Params = param.Parameters;
+
+ BigInteger q = gost3410Params.Q, x;
+
+ int minWeight = 64;
+ for (;;)
+ {
+ x = new BigInteger(256, random);
+
+ if (x.SignValue < 1 || x.CompareTo(q) >= 0)
+ continue;
+
+ if (WNafUtilities.GetNafWeight(x) < minWeight)
+ continue;
+
+ break;
+ }
+
+ BigInteger p = gost3410Params.P;
+ BigInteger a = gost3410Params.A;
+
+ // calculate the public key.
+ BigInteger y = a.ModPow(x, p);
+
+ if (param.PublicKeyParamSet != null)
+ {
+ return new AsymmetricCipherKeyPair(
+ new Gost3410PublicKeyParameters(y, param.PublicKeyParamSet),
+ new Gost3410PrivateKeyParameters(x, param.PublicKeyParamSet));
+ }
+
+ return new AsymmetricCipherKeyPair(
+ new Gost3410PublicKeyParameters(y, gost3410Params),
+ new Gost3410PrivateKeyParameters(x, gost3410Params));
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/GOST3410KeyPairGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/GOST3410KeyPairGenerator.cs.meta
new file mode 100644
index 00000000..98223ab3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/GOST3410KeyPairGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 9f3d826c975554e4a92fe8058998f65a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/GOST3410ParametersGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/GOST3410ParametersGenerator.cs
new file mode 100644
index 00000000..cdb80f08
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/GOST3410ParametersGenerator.cs
@@ -0,0 +1,534 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ /**
+ * generate suitable parameters for GOST3410.
+ */
+ public class Gost3410ParametersGenerator
+ {
+ private int size;
+ private int typeproc;
+ private SecureRandom init_random;
+
+ /**
+ * initialise the key generator.
+ *
+ * @param size size of the key
+ * @param typeProcedure type procedure A,B = 1; A',B' - else
+ * @param random random byte source.
+ */
+ public void Init(
+ int size,
+ int typeProcedure,
+ SecureRandom random)
+ {
+ this.size = size;
+ this.typeproc = typeProcedure;
+ this.init_random = random;
+ }
+
+ //Procedure A
+ private int procedure_A(int x0, int c, BigInteger[] pq, int size)
+ {
+ //Verify and perform condition: 065536)
+ {
+ x0 = init_random.NextInt()/32768;
+ }
+
+ while((c<0 || c>65536) || (c/2==0))
+ {
+ c = init_random.NextInt()/32768 + 1;
+ }
+
+ BigInteger C = BigInteger.ValueOf(c);
+ BigInteger constA16 = BigInteger.ValueOf(19381);
+
+ //step1
+ BigInteger[] y = new BigInteger[1]; // begin length = 1
+ y[0] = BigInteger.ValueOf(x0);
+
+ //step 2
+ int[] t = new int[1]; // t - orders; begin length = 1
+ t[0] = size;
+ int s = 0;
+ for (int i=0; t[i]>=17; i++)
+ {
+ // extension array t
+ int[] tmp_t = new int[t.Length + 1]; ///////////////
+ Array.Copy(t,0,tmp_t,0,t.Length); // extension
+ t = new int[tmp_t.Length]; // array t
+ Array.Copy(tmp_t, 0, t, 0, tmp_t.Length); ///////////////
+
+ t[i+1] = t[i]/2;
+ s = i+1;
+ }
+
+ //step3
+ BigInteger[] p = new BigInteger[s+1];
+ p[s] = new BigInteger("8003",16); //set min prime number length 16 bit
+
+ int m = s-1; //step4
+
+ for (int i=0; i t[m])
+ {
+ goto step6; //step 12
+ }
+
+ p[m] = NByLastP.Add(BigInteger.One);
+
+ //step13
+ if (BigInteger.Two.ModPow(NByLastP, p[m]).CompareTo(BigInteger.One) == 0
+ && BigInteger.Two.ModPow(N, p[m]).CompareTo(BigInteger.One) != 0)
+ {
+ break;
+ }
+
+ N = N.Add(BigInteger.Two);
+ }
+
+ if (--m < 0)
+ {
+ pq[0] = p[0];
+ pq[1] = p[1];
+ return y[0].IntValue; //return for procedure B step 2
+ }
+
+ break; //step 14
+ }
+ }
+ return y[0].IntValue;
+ }
+
+ //Procedure A'
+ private long procedure_Aa(long x0, long c, BigInteger[] pq, int size)
+ {
+ //Verify and perform condition: 04294967296L)
+ {
+ x0 = init_random.NextInt()*2;
+ }
+
+ while((c<0 || c>4294967296L) || (c/2==0))
+ {
+ c = init_random.NextInt()*2+1;
+ }
+
+ BigInteger C = BigInteger.ValueOf(c);
+ BigInteger constA32 = BigInteger.ValueOf(97781173);
+
+ //step1
+ BigInteger[] y = new BigInteger[1]; // begin length = 1
+ y[0] = BigInteger.ValueOf(x0);
+
+ //step 2
+ int[] t = new int[1]; // t - orders; begin length = 1
+ t[0] = size;
+ int s = 0;
+ for (int i=0; t[i]>=33; i++)
+ {
+ // extension array t
+ int[] tmp_t = new int[t.Length + 1]; ///////////////
+ Array.Copy(t,0,tmp_t,0,t.Length); // extension
+ t = new int[tmp_t.Length]; // array t
+ Array.Copy(tmp_t, 0, t, 0, tmp_t.Length); ///////////////
+
+ t[i+1] = t[i]/2;
+ s = i+1;
+ }
+
+ //step3
+ BigInteger[] p = new BigInteger[s+1];
+ p[s] = new BigInteger("8000000B",16); //set min prime number length 32 bit
+
+ int m = s-1; //step4
+
+ for (int i=0; i t[m])
+ {
+ goto step6; //step 12
+ }
+
+ p[m] = NByLastP.Add(BigInteger.One);
+
+ //step13
+ if (BigInteger.Two.ModPow(NByLastP, p[m]).CompareTo(BigInteger.One) == 0
+ && BigInteger.Two.ModPow(N, p[m]).CompareTo(BigInteger.One) != 0)
+ {
+ break;
+ }
+
+ N = N.Add(BigInteger.Two);
+ }
+
+ if (--m < 0)
+ {
+ pq[0] = p[0];
+ pq[1] = p[1];
+ return y[0].LongValue; //return for procedure B' step 2
+ }
+
+ break; //step 14
+ }
+ }
+ return y[0].LongValue;
+ }
+
+ //Procedure B
+ private void procedure_B(int x0, int c, BigInteger[] pq)
+ {
+ //Verify and perform condition: 065536)
+ {
+ x0 = init_random.NextInt()/32768;
+ }
+
+ while((c<0 || c>65536) || (c/2==0))
+ {
+ c = init_random.NextInt()/32768 + 1;
+ }
+
+ BigInteger [] qp = new BigInteger[2];
+ BigInteger q = null, Q = null, p = null;
+ BigInteger C = BigInteger.ValueOf(c);
+ BigInteger constA16 = BigInteger.ValueOf(19381);
+
+ //step1
+ x0 = procedure_A(x0, c, qp, 256);
+ q = qp[0];
+
+ //step2
+ x0 = procedure_A(x0, c, qp, 512);
+ Q = qp[0];
+
+ BigInteger[] y = new BigInteger[65];
+ y[0] = BigInteger.ValueOf(x0);
+
+ const int tp = 1024;
+
+ BigInteger qQ = q.Multiply(Q);
+
+step3:
+ for(;;)
+ {
+ //step 3
+ for (int j=0; j<64; j++)
+ {
+ y[j+1] = (y[j].Multiply(constA16).Add(C)).Mod(BigInteger.Two.Pow(16));
+ }
+
+ //step 4
+ BigInteger Y = BigInteger.Zero;
+
+ for (int j=0; j<64; j++)
+ {
+ Y = Y.Add(y[j].ShiftLeft(16*j));
+ }
+
+ y[0] = y[64]; //step 5
+
+ //step 6
+ BigInteger N = BigInteger.One.ShiftLeft(tp-1).Divide(qQ).Add(
+ Y.ShiftLeft(tp-1).Divide(qQ.ShiftLeft(1024)));
+
+ if (N.TestBit(0))
+ {
+ N = N.Add(BigInteger.One);
+ }
+
+ //step 7
+
+ for(;;)
+ {
+ //step 11
+ BigInteger qQN = qQ.Multiply(N);
+
+ if (qQN.BitLength > tp)
+ {
+ goto step3; //step 9
+ }
+
+ p = qQN.Add(BigInteger.One);
+
+ //step10
+ if (BigInteger.Two.ModPow(qQN, p).CompareTo(BigInteger.One) == 0
+ && BigInteger.Two.ModPow(q.Multiply(N), p).CompareTo(BigInteger.One) != 0)
+ {
+ pq[0] = p;
+ pq[1] = q;
+ return;
+ }
+
+ N = N.Add(BigInteger.Two);
+ }
+ }
+ }
+
+ //Procedure B'
+ private void procedure_Bb(long x0, long c, BigInteger[] pq)
+ {
+ //Verify and perform condition: 04294967296L)
+ {
+ x0 = init_random.NextInt()*2;
+ }
+
+ while((c<0 || c>4294967296L) || (c/2==0))
+ {
+ c = init_random.NextInt()*2+1;
+ }
+
+ BigInteger [] qp = new BigInteger[2];
+ BigInteger q = null, Q = null, p = null;
+ BigInteger C = BigInteger.ValueOf(c);
+ BigInteger constA32 = BigInteger.ValueOf(97781173);
+
+ //step1
+ x0 = procedure_Aa(x0, c, qp, 256);
+ q = qp[0];
+
+ //step2
+ x0 = procedure_Aa(x0, c, qp, 512);
+ Q = qp[0];
+
+ BigInteger[] y = new BigInteger[33];
+ y[0] = BigInteger.ValueOf(x0);
+
+ const int tp = 1024;
+
+ BigInteger qQ = q.Multiply(Q);
+
+step3:
+ for(;;)
+ {
+ //step 3
+ for (int j=0; j<32; j++)
+ {
+ y[j+1] = (y[j].Multiply(constA32).Add(C)).Mod(BigInteger.Two.Pow(32));
+ }
+
+ //step 4
+ BigInteger Y = BigInteger.Zero;
+ for (int j=0; j<32; j++)
+ {
+ Y = Y.Add(y[j].ShiftLeft(32*j));
+ }
+
+ y[0] = y[32]; //step 5
+
+ //step 6
+ BigInteger N = BigInteger.One.ShiftLeft(tp-1).Divide(qQ).Add(
+ Y.ShiftLeft(tp-1).Divide(qQ.ShiftLeft(1024)));
+
+ if (N.TestBit(0))
+ {
+ N = N.Add(BigInteger.One);
+ }
+
+ //step 7
+
+ for(;;)
+ {
+ //step 11
+ BigInteger qQN = qQ.Multiply(N);
+
+ if (qQN.BitLength > tp)
+ {
+ goto step3; //step 9
+ }
+
+ p = qQN.Add(BigInteger.One);
+
+ //step10
+ if (BigInteger.Two.ModPow(qQN, p).CompareTo(BigInteger.One) == 0
+ && BigInteger.Two.ModPow(q.Multiply(N), p).CompareTo(BigInteger.One) != 0)
+ {
+ pq[0] = p;
+ pq[1] = q;
+ return;
+ }
+
+ N = N.Add(BigInteger.Two);
+ }
+ }
+ }
+
+
+ /**
+ * Procedure C
+ * procedure generates the a value from the given p,q,
+ * returning the a value.
+ */
+ private BigInteger procedure_C(BigInteger p, BigInteger q)
+ {
+ BigInteger pSub1 = p.Subtract(BigInteger.One);
+ BigInteger pSub1Divq = pSub1.Divide(q);
+
+ for(;;)
+ {
+ BigInteger d = new BigInteger(p.BitLength, init_random);
+
+ // 1 < d < p-1
+ if (d.CompareTo(BigInteger.One) > 0 && d.CompareTo(pSub1) < 0)
+ {
+ BigInteger a = d.ModPow(pSub1Divq, p);
+
+ if (a.CompareTo(BigInteger.One) != 0)
+ {
+ return a;
+ }
+ }
+ }
+ }
+
+ /**
+ * which generates the p , q and a values from the given parameters,
+ * returning the Gost3410Parameters object.
+ */
+ public Gost3410Parameters GenerateParameters()
+ {
+ BigInteger [] pq = new BigInteger[2];
+ BigInteger q = null, p = null, a = null;
+
+ int x0, c;
+ long x0L, cL;
+
+ if (typeproc==1)
+ {
+ x0 = init_random.NextInt();
+ c = init_random.NextInt();
+
+ switch(size)
+ {
+ case 512:
+ procedure_A(x0, c, pq, 512);
+ break;
+ case 1024:
+ procedure_B(x0, c, pq);
+ break;
+ default:
+ throw new ArgumentException("Ooops! key size 512 or 1024 bit.");
+ }
+ p = pq[0]; q = pq[1];
+ a = procedure_C(p, q);
+ //System.out.println("p:"+p.toString(16)+"\n"+"q:"+q.toString(16)+"\n"+"a:"+a.toString(16));
+ //System.out.println("p:"+p+"\n"+"q:"+q+"\n"+"a:"+a);
+ return new Gost3410Parameters(p, q, a, new Gost3410ValidationParameters(x0, c));
+ }
+ else
+ {
+ x0L = init_random.NextLong();
+ cL = init_random.NextLong();
+
+ switch(size)
+ {
+ case 512:
+ procedure_Aa(x0L, cL, pq, 512);
+ break;
+ case 1024:
+ procedure_Bb(x0L, cL, pq);
+ break;
+ default:
+ throw new InvalidOperationException("Ooops! key size 512 or 1024 bit.");
+ }
+ p = pq[0]; q = pq[1];
+ a = procedure_C(p, q);
+ //System.out.println("p:"+p.toString(16)+"\n"+"q:"+q.toString(16)+"\n"+"a:"+a.toString(16));
+ //System.out.println("p:"+p+"\n"+"q:"+q+"\n"+"a:"+a);
+ return new Gost3410Parameters(p, q, a, new Gost3410ValidationParameters(x0L, cL));
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/GOST3410ParametersGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/GOST3410ParametersGenerator.cs.meta
new file mode 100644
index 00000000..e47ad0c0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/GOST3410ParametersGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 55c0c063ba32c654d988998faa5cebbf
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/HKDFBytesGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/HKDFBytesGenerator.cs
new file mode 100644
index 00000000..99b4e5af
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/HKDFBytesGenerator.cs
@@ -0,0 +1,156 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ /**
+ * HMAC-based Extract-and-Expand Key Derivation Function (HKDF) implemented
+ * according to IETF RFC 5869, May 2010 as specified by H. Krawczyk, IBM
+ * Research & P. Eronen, Nokia. It uses a HMac internally to compute de OKM
+ * (output keying material) and is likely to have better security properties
+ * than KDF's based on just a hash function.
+ */
+ public class HkdfBytesGenerator
+ : IDerivationFunction
+ {
+ private HMac hMacHash;
+ private int hashLen;
+
+ private byte[] info;
+ private byte[] currentT;
+
+ private int generatedBytes;
+
+ /**
+ * Creates a HKDFBytesGenerator based on the given hash function.
+ *
+ * @param hash the digest to be used as the source of generatedBytes bytes
+ */
+ public HkdfBytesGenerator(IDigest hash)
+ {
+ this.hMacHash = new HMac(hash);
+ this.hashLen = hash.GetDigestSize();
+ }
+
+ public virtual void Init(IDerivationParameters parameters)
+ {
+ if (!(parameters is HkdfParameters))
+ throw new ArgumentException("HKDF parameters required for HkdfBytesGenerator", "parameters");
+
+ HkdfParameters hkdfParameters = (HkdfParameters)parameters;
+ if (hkdfParameters.SkipExtract)
+ {
+ // use IKM directly as PRK
+ hMacHash.Init(new KeyParameter(hkdfParameters.GetIkm()));
+ }
+ else
+ {
+ hMacHash.Init(Extract(hkdfParameters.GetSalt(), hkdfParameters.GetIkm()));
+ }
+
+ info = hkdfParameters.GetInfo();
+
+ generatedBytes = 0;
+ currentT = new byte[hashLen];
+ }
+
+ /**
+ * Performs the extract part of the key derivation function.
+ *
+ * @param salt the salt to use
+ * @param ikm the input keying material
+ * @return the PRK as KeyParameter
+ */
+ private KeyParameter Extract(byte[] salt, byte[] ikm)
+ {
+ if (salt == null)
+ {
+ // TODO check if hashLen is indeed same as HMAC size
+ hMacHash.Init(new KeyParameter(new byte[hashLen]));
+ }
+ else
+ {
+ hMacHash.Init(new KeyParameter(salt));
+ }
+
+ hMacHash.BlockUpdate(ikm, 0, ikm.Length);
+
+ byte[] prk = new byte[hashLen];
+ hMacHash.DoFinal(prk, 0);
+ return new KeyParameter(prk);
+ }
+
+ /**
+ * Performs the expand part of the key derivation function, using currentT
+ * as input and output buffer.
+ *
+ * @throws DataLengthException if the total number of bytes generated is larger than the one
+ * specified by RFC 5869 (255 * HashLen)
+ */
+ private void ExpandNext()
+ {
+ int n = generatedBytes / hashLen + 1;
+ if (n >= 256)
+ {
+ throw new DataLengthException(
+ "HKDF cannot generate more than 255 blocks of HashLen size");
+ }
+ // special case for T(0): T(0) is empty, so no update
+ if (generatedBytes != 0)
+ {
+ hMacHash.BlockUpdate(currentT, 0, hashLen);
+ }
+ hMacHash.BlockUpdate(info, 0, info.Length);
+ hMacHash.Update((byte)n);
+ hMacHash.DoFinal(currentT, 0);
+ }
+
+ public virtual IDigest Digest
+ {
+ get { return hMacHash.GetUnderlyingDigest(); }
+ }
+
+ public virtual int GenerateBytes(byte[] output, int outOff, int len)
+ {
+ if (generatedBytes + len > 255 * hashLen)
+ {
+ throw new DataLengthException(
+ "HKDF may only be used for 255 * HashLen bytes of output");
+ }
+
+ if (generatedBytes % hashLen == 0)
+ {
+ ExpandNext();
+ }
+
+ // copy what is left in the currentT (1..hash
+ int toGenerate = len;
+ int posInT = generatedBytes % hashLen;
+ int leftInT = hashLen - generatedBytes % hashLen;
+ int toCopy = System.Math.Min(leftInT, toGenerate);
+ Array.Copy(currentT, posInT, output, outOff, toCopy);
+ generatedBytes += toCopy;
+ toGenerate -= toCopy;
+ outOff += toCopy;
+
+ while (toGenerate > 0)
+ {
+ ExpandNext();
+ toCopy = System.Math.Min(hashLen, toGenerate);
+ Array.Copy(currentT, 0, output, outOff, toCopy);
+ generatedBytes += toCopy;
+ toGenerate -= toCopy;
+ outOff += toCopy;
+ }
+
+ return len;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/HKDFBytesGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/HKDFBytesGenerator.cs.meta
new file mode 100644
index 00000000..5e75b8b3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/HKDFBytesGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 60c549f57c0a75c4bad2d81891b9016c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Kdf1BytesGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Kdf1BytesGenerator.cs
new file mode 100644
index 00000000..b99e4e7b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Kdf1BytesGenerator.cs
@@ -0,0 +1,30 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ /**
+ * KFD2 generator for derived keys and ivs as defined by IEEE P1363a/ISO 18033
+ *
+ * This implementation is based on IEEE P1363/ISO 18033.
+ */
+ public class Kdf1BytesGenerator
+ : BaseKdfBytesGenerator
+ {
+ /**
+ * Construct a KDF1 byte generator.
+ *
+ * @param digest the digest to be used as the source of derived keys.
+ */
+ public Kdf1BytesGenerator(IDigest digest)
+ : base(0, digest)
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Kdf1BytesGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Kdf1BytesGenerator.cs.meta
new file mode 100644
index 00000000..84d21c33
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Kdf1BytesGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0d7074bad2d3d06438d11b782fef919d
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Kdf2BytesGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Kdf2BytesGenerator.cs
new file mode 100644
index 00000000..39683b7c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Kdf2BytesGenerator.cs
@@ -0,0 +1,31 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ /**
+ * KDF2 generator for derived keys and ivs as defined by IEEE P1363a/ISO 18033
+ *
+ * This implementation is based on IEEE P1363/ISO 18033.
+ */
+ public class Kdf2BytesGenerator
+ : BaseKdfBytesGenerator
+ {
+ /**
+ * Construct a KDF2 bytes generator. Generates key material
+ * according to IEEE P1363 or ISO 18033 depending on the initialisation.
+ *
+ * @param digest the digest to be used as the source of derived keys.
+ */
+ public Kdf2BytesGenerator(IDigest digest)
+ : base(1, digest)
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Kdf2BytesGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Kdf2BytesGenerator.cs.meta
new file mode 100644
index 00000000..1dbf1175
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Kdf2BytesGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 28a22366b40aeec43b46ed5e13467239
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Mgf1BytesGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Mgf1BytesGenerator.cs
new file mode 100644
index 00000000..b06e9ff6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Mgf1BytesGenerator.cs
@@ -0,0 +1,124 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+#if UNITY_WSA && !UNITY_EDITOR && !ENABLE_IL2CPP
+using System.TypeFix;
+#endif
+using System;
+//using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+//using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ /**
+ * Generator for MGF1 as defined in Pkcs 1v2
+ */
+ public class Mgf1BytesGenerator : IDerivationFunction
+ {
+ private IDigest digest;
+ private byte[] seed;
+ private int hLen;
+
+ /**
+ * @param digest the digest to be used as the source of Generated bytes
+ */
+ public Mgf1BytesGenerator(
+ IDigest digest)
+ {
+ this.digest = digest;
+ this.hLen = digest.GetDigestSize();
+ }
+
+ public void Init(
+ IDerivationParameters parameters)
+ {
+ if (!(typeof(MgfParameters).IsInstanceOfType(parameters)))
+ {
+ throw new ArgumentException("MGF parameters required for MGF1Generator");
+ }
+
+ MgfParameters p = (MgfParameters)parameters;
+
+ seed = p.GetSeed();
+ }
+
+ /**
+ * return the underlying digest.
+ */
+ public IDigest Digest
+ {
+ get
+ {
+ return digest;
+ }
+ }
+
+ /**
+ * int to octet string.
+ */
+ private void ItoOSP(
+ int i,
+ byte[] sp)
+ {
+ sp[0] = (byte)((uint) i >> 24);
+ sp[1] = (byte)((uint) i >> 16);
+ sp[2] = (byte)((uint) i >> 8);
+ sp[3] = (byte)((uint) i >> 0);
+ }
+
+ /**
+ * fill len bytes of the output buffer with bytes Generated from
+ * the derivation function.
+ *
+ * @throws DataLengthException if the out buffer is too small.
+ */
+ public int GenerateBytes(
+ byte[] output,
+ int outOff,
+ int length)
+ {
+ if ((output.Length - length) < outOff)
+ {
+ throw new DataLengthException("output buffer too small");
+ }
+
+ byte[] hashBuf = new byte[hLen];
+ byte[] C = new byte[4];
+ int counter = 0;
+
+ digest.Reset();
+
+ if (length > hLen)
+ {
+ do
+ {
+ ItoOSP(counter, C);
+
+ digest.BlockUpdate(seed, 0, seed.Length);
+ digest.BlockUpdate(C, 0, C.Length);
+ digest.DoFinal(hashBuf, 0);
+
+ Array.Copy(hashBuf, 0, output, outOff + counter * hLen, hLen);
+ }
+ while (++counter < (length / hLen));
+ }
+
+ if ((counter * hLen) < length)
+ {
+ ItoOSP(counter, C);
+
+ digest.BlockUpdate(seed, 0, seed.Length);
+ digest.BlockUpdate(C, 0, C.Length);
+ digest.DoFinal(hashBuf, 0);
+
+ Array.Copy(hashBuf, 0, output, outOff + counter * hLen, length - (counter * hLen));
+ }
+
+ return length;
+ }
+ }
+
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Mgf1BytesGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Mgf1BytesGenerator.cs.meta
new file mode 100644
index 00000000..dcf60b3b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Mgf1BytesGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 31a110c2dc0902d479e2a482d25f7212
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/NaccacheSternKeyPairGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/NaccacheSternKeyPairGenerator.cs
new file mode 100644
index 00000000..8caac625
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/NaccacheSternKeyPairGenerator.cs
@@ -0,0 +1,272 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ /**
+ * Key generation parameters for NaccacheStern cipher. For details on this cipher, please see
+ *
+ * http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf
+ */
+ public class NaccacheSternKeyPairGenerator
+ : IAsymmetricCipherKeyPairGenerator
+ {
+ private static readonly int[] smallPrimes =
+ {
+ 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67,
+ 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149,
+ 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233,
+ 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331,
+ 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431,
+ 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523,
+ 541, 547, 557
+ };
+
+ private NaccacheSternKeyGenerationParameters param;
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator#init(org.bouncycastle.crypto.KeyGenerationParameters)
+ */
+ public void Init(KeyGenerationParameters parameters)
+ {
+ this.param = (NaccacheSternKeyGenerationParameters)parameters;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator#generateKeyPair()
+ */
+ public AsymmetricCipherKeyPair GenerateKeyPair()
+ {
+ int strength = param.Strength;
+ SecureRandom rand = param.Random;
+ int certainty = param.Certainty;
+
+ IList smallPrimes = findFirstPrimes(param.CountSmallPrimes);
+
+ smallPrimes = permuteList(smallPrimes, rand);
+
+ BigInteger u = BigInteger.One;
+ BigInteger v = BigInteger.One;
+
+ for (int i = 0; i < smallPrimes.Count / 2; i++)
+ {
+ u = u.Multiply((BigInteger)smallPrimes[i]);
+ }
+ for (int i = smallPrimes.Count / 2; i < smallPrimes.Count; i++)
+ {
+ v = v.Multiply((BigInteger)smallPrimes[i]);
+ }
+
+ BigInteger sigma = u.Multiply(v);
+
+ // n = (2 a u _p + 1 ) ( 2 b v _q + 1)
+ // -> |n| = strength
+ // |2| = 1 in bits
+ // -> |a| * |b| = |n| - |u| - |v| - |_p| - |_q| - |2| -|2|
+ // remainingStrength = strength - sigma.bitLength() - _p.bitLength() -
+ // _q.bitLength() - 1 -1
+ int remainingStrength = strength - sigma.BitLength - 48;
+ BigInteger a = generatePrime(remainingStrength / 2 + 1, certainty, rand);
+ BigInteger b = generatePrime(remainingStrength / 2 + 1, certainty, rand);
+
+ BigInteger _p;
+ BigInteger _q;
+ BigInteger p;
+ BigInteger q;
+
+ long tries = 0;
+
+ BigInteger _2au = a.Multiply(u).ShiftLeft(1);
+ BigInteger _2bv = b.Multiply(v).ShiftLeft(1);
+
+ for (;;)
+ {
+ tries++;
+
+ _p = generatePrime(24, certainty, rand);
+
+ p = _p.Multiply(_2au).Add(BigInteger.One);
+
+ if (!p.IsProbablePrime(certainty, true))
+ continue;
+
+ for (;;)
+ {
+ _q = generatePrime(24, certainty, rand);
+
+ if (_p.Equals(_q))
+ continue;
+
+ q = _q.Multiply(_2bv).Add(BigInteger.One);
+
+ if (q.IsProbablePrime(certainty, true))
+ break;
+ }
+
+ if (!sigma.Gcd(_p.Multiply(_q)).Equals(BigInteger.One))
+ {
+ //Console.WriteLine("sigma.gcd(_p.mult(_q)) != 1!\n _p: " + _p +"\n _q: "+ _q );
+ continue;
+ }
+
+ if (p.Multiply(q).BitLength < strength)
+ {
+ continue;
+ }
+ break;
+ }
+
+ BigInteger n = p.Multiply(q);
+ BigInteger phi_n = p.Subtract(BigInteger.One).Multiply(q.Subtract(BigInteger.One));
+ BigInteger g;
+ tries = 0;
+
+ for (;;)
+ {
+ // TODO After the first loop, just regenerate one randomly-selected gPart each time?
+ IList gParts = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ for (int ind = 0; ind != smallPrimes.Count; ind++)
+ {
+ BigInteger i = (BigInteger)smallPrimes[ind];
+ BigInteger e = phi_n.Divide(i);
+
+ for (;;)
+ {
+ tries++;
+
+ g = generatePrime(strength, certainty, rand);
+
+ if (!g.ModPow(e, n).Equals(BigInteger.One))
+ {
+ gParts.Add(g);
+ break;
+ }
+ }
+ }
+ g = BigInteger.One;
+ for (int i = 0; i < smallPrimes.Count; i++)
+ {
+ BigInteger gPart = (BigInteger) gParts[i];
+ BigInteger smallPrime = (BigInteger) smallPrimes[i];
+ g = g.Multiply(gPart.ModPow(sigma.Divide(smallPrime), n)).Mod(n);
+ }
+
+ // make sure that g is not divisible by p_i or q_i
+ bool divisible = false;
+ for (int i = 0; i < smallPrimes.Count; i++)
+ {
+ if (g.ModPow(phi_n.Divide((BigInteger)smallPrimes[i]), n).Equals(BigInteger.One))
+ {
+ divisible = true;
+ break;
+ }
+ }
+
+ if (divisible)
+ {
+ continue;
+ }
+
+ // make sure that g has order > phi_n/4
+
+ //if (g.ModPow(phi_n.Divide(BigInteger.ValueOf(4)), n).Equals(BigInteger.One))
+ if (g.ModPow(phi_n.ShiftRight(2), n).Equals(BigInteger.One))
+ {
+ continue;
+ }
+
+ if (g.ModPow(phi_n.Divide(_p), n).Equals(BigInteger.One))
+ {
+ continue;
+ }
+ if (g.ModPow(phi_n.Divide(_q), n).Equals(BigInteger.One))
+ {
+ continue;
+ }
+ if (g.ModPow(phi_n.Divide(a), n).Equals(BigInteger.One))
+ {
+ continue;
+ }
+ if (g.ModPow(phi_n.Divide(b), n).Equals(BigInteger.One))
+ {
+ continue;
+ }
+ break;
+ }
+
+ return new AsymmetricCipherKeyPair(new NaccacheSternKeyParameters(false, g, n, sigma.BitLength),
+ new NaccacheSternPrivateKeyParameters(g, n, sigma.BitLength, smallPrimes, phi_n));
+ }
+
+ private static BigInteger generatePrime(
+ int bitLength,
+ int certainty,
+ SecureRandom rand)
+ {
+ return new BigInteger(bitLength, certainty, rand);
+ }
+
+ /**
+ * Generates a permuted ArrayList from the original one. The original List
+ * is not modified
+ *
+ * @param arr
+ * the ArrayList to be permuted
+ * @param rand
+ * the source of Randomness for permutation
+ * @return a new IList with the permuted elements.
+ */
+ private static IList permuteList(
+ IList arr,
+ SecureRandom rand)
+ {
+ // TODO Create a utility method for generating permutation of first 'n' integers
+
+ IList retval = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(arr.Count);
+
+ foreach (object element in arr)
+ {
+ int index = rand.Next(retval.Count + 1);
+ retval.Insert(index, element);
+ }
+
+ return retval;
+ }
+
+ /**
+ * Finds the first 'count' primes starting with 3
+ *
+ * @param count
+ * the number of primes to find
+ * @return a vector containing the found primes as Integer
+ */
+ private static IList findFirstPrimes(
+ int count)
+ {
+ IList primes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(count);
+
+ for (int i = 0; i != count; i++)
+ {
+ primes.Add(BigInteger.ValueOf(smallPrimes[i]));
+ }
+
+ return primes;
+ }
+
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/NaccacheSternKeyPairGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/NaccacheSternKeyPairGenerator.cs.meta
new file mode 100644
index 00000000..1f71a49c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/NaccacheSternKeyPairGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 720fd0eb1bd2a4048ba38b891037760b
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/OpenBsdBCrypt.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/OpenBsdBCrypt.cs
new file mode 100644
index 00000000..01914ef9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/OpenBsdBCrypt.cs
@@ -0,0 +1,309 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ /**
+ * Password hashing scheme BCrypt,
+ * designed by Niels Provos and David Mazières, using the
+ * String format and the Base64 encoding
+ * of the reference implementation on OpenBSD
+ */
+ public class OpenBsdBCrypt
+ {
+ private static readonly byte[] EncodingTable = // the Bcrypts encoding table for OpenBSD
+ {
+ (byte)'.', (byte)'/', (byte)'A', (byte)'B', (byte)'C', (byte)'D',
+ (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J',
+ (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P',
+ (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V',
+ (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b',
+ (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h',
+ (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
+ (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t',
+ (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
+ (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
+ (byte)'6', (byte)'7', (byte)'8', (byte)'9'
+ };
+
+ /*
+ * set up the decoding table.
+ */
+ private static readonly byte[] DecodingTable = new byte[128];
+ private static readonly string DefaultVersion = "2y";
+ private static readonly ISet AllowedVersions = new HashSet();
+
+ static OpenBsdBCrypt()
+ {
+ // Presently just the Bcrypt versions.
+ AllowedVersions.Add("2a");
+ AllowedVersions.Add("2y");
+ AllowedVersions.Add("2b");
+
+ for (int i = 0; i < DecodingTable.Length; i++)
+ {
+ DecodingTable[i] = (byte)0xff;
+ }
+
+ for (int i = 0; i < EncodingTable.Length; i++)
+ {
+ DecodingTable[EncodingTable[i]] = (byte)i;
+ }
+ }
+
+ public OpenBsdBCrypt()
+ {
+ }
+
+ /**
+ * Creates a 60 character Bcrypt String, including
+ * version, cost factor, salt and hash, separated by '$'
+ *
+ * @param version the version, 2y,2b or 2a. (2a is not backwards compatible.)
+ * @param cost the cost factor, treated as an exponent of 2
+ * @param salt a 16 byte salt
+ * @param password the password
+ * @return a 60 character Bcrypt String
+ */
+ private static string CreateBcryptString(string version, byte[] password, byte[] salt, int cost)
+ {
+ if (!AllowedVersions.Contains(version))
+ throw new ArgumentException("Version " + version + " is not accepted by this implementation.", "version");
+
+ StringBuilder sb = new StringBuilder(60);
+ sb.Append('$');
+ sb.Append(version);
+ sb.Append('$');
+ sb.Append(cost < 10 ? ("0" + cost) : cost.ToString());
+ sb.Append('$');
+ sb.Append(EncodeData(salt));
+
+ byte[] key = BCrypt.Generate(password, salt, cost);
+
+ sb.Append(EncodeData(key));
+
+ return sb.ToString();
+ }
+
+ /**
+ * Creates a 60 character Bcrypt String, including
+ * version, cost factor, salt and hash, separated by '$' using version
+ * '2y'.
+ *
+ * @param cost the cost factor, treated as an exponent of 2
+ * @param salt a 16 byte salt
+ * @param password the password
+ * @return a 60 character Bcrypt String
+ */
+ public static string Generate(char[] password, byte[] salt, int cost)
+ {
+ return Generate(DefaultVersion, password, salt, cost);
+ }
+
+ /**
+ * Creates a 60 character Bcrypt String, including
+ * version, cost factor, salt and hash, separated by '$'
+ *
+ * @param version the version, may be 2b, 2y or 2a. (2a is not backwards compatible.)
+ * @param cost the cost factor, treated as an exponent of 2
+ * @param salt a 16 byte salt
+ * @param password the password
+ * @return a 60 character Bcrypt String
+ */
+ public static string Generate(string version, char[] password, byte[] salt, int cost)
+ {
+ if (!AllowedVersions.Contains(version))
+ throw new ArgumentException("Version " + version + " is not accepted by this implementation.", "version");
+ if (password == null)
+ throw new ArgumentNullException("password");
+ if (salt == null)
+ throw new ArgumentNullException("salt");
+ if (salt.Length != 16)
+ throw new DataLengthException("16 byte salt required: " + salt.Length);
+
+ if (cost < 4 || cost > 31) // Minimum rounds: 16, maximum 2^31
+ throw new ArgumentException("Invalid cost factor.", "cost");
+
+ byte[] psw = Strings.ToUtf8ByteArray(password);
+
+ // 0 termination:
+
+ byte[] tmp = new byte[psw.Length >= 72 ? 72 : psw.Length + 1];
+ int copyLen = System.Math.Min(psw.Length, tmp.Length);
+ Array.Copy(psw, 0, tmp, 0, copyLen);
+
+ Array.Clear(psw, 0, psw.Length);
+
+ string rv = CreateBcryptString(version, tmp, salt, cost);
+
+ Array.Clear(tmp, 0, tmp.Length);
+
+ return rv;
+ }
+
+ /**
+ * Checks if a password corresponds to a 60 character Bcrypt String
+ *
+ * @param bcryptString a 60 character Bcrypt String, including
+ * version, cost factor, salt and hash,
+ * separated by '$'
+ * @param password the password as an array of chars
+ * @return true if the password corresponds to the
+ * Bcrypt String, otherwise false
+ */
+ public static bool CheckPassword(string bcryptString, char[] password)
+ {
+ // validate bcryptString:
+ if (bcryptString.Length != 60)
+ throw new DataLengthException("Bcrypt String length: " + bcryptString.Length + ", 60 required.");
+ if (bcryptString[0] != '$' || bcryptString[3] != '$' || bcryptString[6] != '$')
+ throw new ArgumentException("Invalid Bcrypt String format.", "bcryptString");
+
+ string version = bcryptString.Substring(1, 2);
+ if (!AllowedVersions.Contains(version))
+ throw new ArgumentException("Bcrypt version '" + version + "' is not supported by this implementation", "bcryptString");
+
+ int cost = 0;
+ try
+ {
+ cost = Int32.Parse(bcryptString.Substring(4, 2));
+ }
+ catch (Exception nfe)
+ {
+#if PORTABLE || NETFX_CORE
+ throw new ArgumentException("Invalid cost factor: " + bcryptString.Substring(4, 2), "bcryptString");
+#else
+ throw new ArgumentException("Invalid cost factor: " + bcryptString.Substring(4, 2), "bcryptString", nfe);
+#endif
+ }
+ if (cost < 4 || cost > 31)
+ throw new ArgumentException("Invalid cost factor: " + cost + ", 4 < cost < 31 expected.");
+
+ // check password:
+ if (password == null)
+ throw new ArgumentNullException("Missing password.");
+
+ int start = bcryptString.LastIndexOf('$') + 1, end = bcryptString.Length - 31;
+ byte[] salt = DecodeSaltString(bcryptString.Substring(start, end - start));
+
+ string newBcryptString = Generate(version, password, salt, cost);
+
+ return bcryptString.Equals(newBcryptString);
+ }
+
+ /*
+ * encode the input data producing a Bcrypt base 64 string.
+ *
+ * @param a byte representation of the salt or the password
+ * @return the Bcrypt base64 string
+ */
+ private static string EncodeData(byte[] data)
+ {
+ if (data.Length != 24 && data.Length != 16) // 192 bit key or 128 bit salt expected
+ throw new DataLengthException("Invalid length: " + data.Length + ", 24 for key or 16 for salt expected");
+
+ bool salt = false;
+ if (data.Length == 16)//salt
+ {
+ salt = true;
+ byte[] tmp = new byte[18];// zero padding
+ Array.Copy(data, 0, tmp, 0, data.Length);
+ data = tmp;
+ }
+ else // key
+ {
+ data[data.Length - 1] = (byte)0;
+ }
+
+ MemoryStream mOut = new MemoryStream();
+ int len = data.Length;
+
+ uint a1, a2, a3;
+ int i;
+ for (i = 0; i < len; i += 3)
+ {
+ a1 = data[i];
+ a2 = data[i + 1];
+ a3 = data[i + 2];
+
+ mOut.WriteByte(EncodingTable[(a1 >> 2) & 0x3f]);
+ mOut.WriteByte(EncodingTable[((a1 << 4) | (a2 >> 4)) & 0x3f]);
+ mOut.WriteByte(EncodingTable[((a2 << 2) | (a3 >> 6)) & 0x3f]);
+ mOut.WriteByte(EncodingTable[a3 & 0x3f]);
+ }
+
+ string result = Strings.FromByteArray(mOut.ToArray());
+ int resultLen = salt
+ ? 22 // truncate padding
+ : result.Length - 1;
+
+ return result.Substring(0, resultLen);
+ }
+
+
+ /*
+ * decodes the bcrypt base 64 encoded SaltString
+ *
+ * @param a 22 character Bcrypt base 64 encoded String
+ * @return the 16 byte salt
+ * @exception DataLengthException if the length
+ * of parameter is not 22
+ * @exception InvalidArgumentException if the parameter
+ * contains a value other than from Bcrypts base 64 encoding table
+ */
+ private static byte[] DecodeSaltString(string saltString)
+ {
+ char[] saltChars = saltString.ToCharArray();
+
+ MemoryStream mOut = new MemoryStream(16);
+ byte b1, b2, b3, b4;
+
+ if (saltChars.Length != 22)// bcrypt salt must be 22 (16 bytes)
+ throw new DataLengthException("Invalid base64 salt length: " + saltChars.Length + " , 22 required.");
+
+ // check string for invalid characters:
+ for (int i = 0; i < saltChars.Length; i++)
+ {
+ int value = saltChars[i];
+ if (value > 122 || value < 46 || (value > 57 && value < 65))
+ throw new ArgumentException("Salt string contains invalid character: " + value, "saltString");
+ }
+
+ // Padding: add two '\u0000'
+ char[] tmp = new char[22 + 2];
+ Array.Copy(saltChars, 0, tmp, 0, saltChars.Length);
+ saltChars = tmp;
+
+ int len = saltChars.Length;
+
+ for (int i = 0; i < len; i += 4)
+ {
+ b1 = DecodingTable[saltChars[i]];
+ b2 = DecodingTable[saltChars[i + 1]];
+ b3 = DecodingTable[saltChars[i + 2]];
+ b4 = DecodingTable[saltChars[i + 3]];
+
+ mOut.WriteByte((byte)((b1 << 2) | (b2 >> 4)));
+ mOut.WriteByte((byte)((b2 << 4) | (b3 >> 2)));
+ mOut.WriteByte((byte)((b3 << 6) | b4));
+ }
+
+ byte[] saltBytes = mOut.ToArray();
+
+ // truncate:
+ byte[] tmpSalt = new byte[16];
+ Array.Copy(saltBytes, 0, tmpSalt, 0, tmpSalt.Length);
+ saltBytes = tmpSalt;
+
+ return saltBytes;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/OpenBsdBCrypt.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/OpenBsdBCrypt.cs.meta
new file mode 100644
index 00000000..f72722af
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/OpenBsdBCrypt.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: d1fec56be41cc0b4f86d231a91f025ea
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/OpenSSLPBEParametersGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/OpenSSLPBEParametersGenerator.cs
new file mode 100644
index 00000000..6419bf11
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/OpenSSLPBEParametersGenerator.cs
@@ -0,0 +1,171 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ /**
+ * Generator for PBE derived keys and ivs as usd by OpenSSL.
+ *
+ * The scheme is a simple extension of PKCS 5 V2.0 Scheme 1 using MD5 with an
+ * iteration count of 1.
+ *
+ */
+ public class OpenSslPbeParametersGenerator
+ : PbeParametersGenerator
+ {
+ private readonly IDigest digest = new MD5Digest();
+
+ /**
+ * Construct a OpenSSL Parameters generator.
+ */
+ public OpenSslPbeParametersGenerator()
+ {
+ }
+
+ public override void Init(
+ byte[] password,
+ byte[] salt,
+ int iterationCount)
+ {
+ // Ignore the provided iterationCount
+ base.Init(password, salt, 1);
+ }
+
+ /**
+ * Initialise - note the iteration count for this algorithm is fixed at 1.
+ *
+ * @param password password to use.
+ * @param salt salt to use.
+ */
+ public virtual void Init(
+ byte[] password,
+ byte[] salt)
+ {
+ base.Init(password, salt, 1);
+ }
+
+ /**
+ * the derived key function, the ith hash of the password and the salt.
+ */
+ private byte[] GenerateDerivedKey(
+ int bytesNeeded)
+ {
+ byte[] buf = new byte[digest.GetDigestSize()];
+ byte[] key = new byte[bytesNeeded];
+ int offset = 0;
+
+ for (;;)
+ {
+ digest.BlockUpdate(mPassword, 0, mPassword.Length);
+ digest.BlockUpdate(mSalt, 0, mSalt.Length);
+
+ digest.DoFinal(buf, 0);
+
+ int len = (bytesNeeded > buf.Length) ? buf.Length : bytesNeeded;
+ Array.Copy(buf, 0, key, offset, len);
+ offset += len;
+
+ // check if we need any more
+ bytesNeeded -= len;
+ if (bytesNeeded == 0)
+ {
+ break;
+ }
+
+ // do another round
+ digest.Reset();
+ digest.BlockUpdate(buf, 0, buf.Length);
+ }
+
+ return key;
+ }
+
+ /**
+ * Generate a key parameter derived from the password, salt, and iteration
+ * count we are currently initialised with.
+ *
+ * @param keySize the size of the key we want (in bits)
+ * @return a KeyParameter object.
+ * @exception ArgumentException if the key length larger than the base hash size.
+ */
+ [Obsolete("Use version with 'algorithm' parameter")]
+ public override ICipherParameters GenerateDerivedParameters(
+ int keySize)
+ {
+ return GenerateDerivedMacParameters(keySize);
+ }
+
+ public override ICipherParameters GenerateDerivedParameters(
+ string algorithm,
+ int keySize)
+ {
+ keySize /= 8;
+
+ byte[] dKey = GenerateDerivedKey(keySize);
+
+ return ParameterUtilities.CreateKeyParameter(algorithm, dKey, 0, keySize);
+ }
+
+ /**
+ * Generate a key with initialisation vector parameter derived from
+ * the password, salt, and iteration count we are currently initialised
+ * with.
+ *
+ * @param keySize the size of the key we want (in bits)
+ * @param ivSize the size of the iv we want (in bits)
+ * @return a ParametersWithIV object.
+ * @exception ArgumentException if keySize + ivSize is larger than the base hash size.
+ */
+ [Obsolete("Use version with 'algorithm' parameter")]
+ public override ICipherParameters GenerateDerivedParameters(
+ int keySize,
+ int ivSize)
+ {
+ keySize = keySize / 8;
+ ivSize = ivSize / 8;
+
+ byte[] dKey = GenerateDerivedKey(keySize + ivSize);
+
+ return new ParametersWithIV(new KeyParameter(dKey, 0, keySize), dKey, keySize, ivSize);
+ }
+
+ public override ICipherParameters GenerateDerivedParameters(
+ string algorithm,
+ int keySize,
+ int ivSize)
+ {
+ keySize /= 8;
+ ivSize /= 8;
+
+ byte[] dKey = GenerateDerivedKey(keySize + ivSize);
+ KeyParameter key = ParameterUtilities.CreateKeyParameter(algorithm, dKey, 0, keySize);
+
+ return new ParametersWithIV(key, dKey, keySize, ivSize);
+ }
+
+ /**
+ * Generate a key parameter for use with a MAC derived from the password,
+ * salt, and iteration count we are currently initialised with.
+ *
+ * @param keySize the size of the key we want (in bits)
+ * @return a KeyParameter object.
+ * @exception ArgumentException if the key length larger than the base hash size.
+ */
+ public override ICipherParameters GenerateDerivedMacParameters(
+ int keySize)
+ {
+ keySize = keySize / 8;
+
+ byte[] dKey = GenerateDerivedKey(keySize);
+
+ return new KeyParameter(dKey, 0, keySize);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/OpenSSLPBEParametersGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/OpenSSLPBEParametersGenerator.cs.meta
new file mode 100644
index 00000000..2b81f85b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/OpenSSLPBEParametersGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 227a7f058cce60f4e9f1944112a1e3e9
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Pkcs12ParametersGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Pkcs12ParametersGenerator.cs
new file mode 100644
index 00000000..e7f7467d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Pkcs12ParametersGenerator.cs
@@ -0,0 +1,247 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ /**
+ * Generator for Pbe derived keys and ivs as defined by Pkcs 12 V1.0.
+ *
+ * The document this implementation is based on can be found at
+ *
+ * RSA's Pkcs12 Page
+ *
+ */
+ public class Pkcs12ParametersGenerator
+ : PbeParametersGenerator
+ {
+ public const int KeyMaterial = 1;
+ public const int IVMaterial = 2;
+ public const int MacMaterial = 3;
+
+ private readonly IDigest digest;
+
+ private readonly int u;
+ private readonly int v;
+
+ /**
+ * Construct a Pkcs 12 Parameters generator.
+ *
+ * @param digest the digest to be used as the source of derived keys.
+ * @exception ArgumentException if an unknown digest is passed in.
+ */
+ public Pkcs12ParametersGenerator(
+ IDigest digest)
+ {
+ this.digest = digest;
+
+ u = digest.GetDigestSize();
+ v = digest.GetByteLength();
+ }
+
+ /**
+ * add a + b + 1, returning the result in a. The a value is treated
+ * as a BigInteger of length (b.Length * 8) bits. The result is
+ * modulo 2^b.Length in case of overflow.
+ */
+ private void Adjust(
+ byte[] a,
+ int aOff,
+ byte[] b)
+ {
+ int x = (b[b.Length - 1] & 0xff) + (a[aOff + b.Length - 1] & 0xff) + 1;
+
+ a[aOff + b.Length - 1] = (byte)x;
+ x = (int) ((uint) x >> 8);
+
+ for (int i = b.Length - 2; i >= 0; i--)
+ {
+ x += (b[i] & 0xff) + (a[aOff + i] & 0xff);
+ a[aOff + i] = (byte)x;
+ x = (int) ((uint) x >> 8);
+ }
+ }
+
+ /**
+ * generation of a derived key ala Pkcs12 V1.0.
+ */
+ private byte[] GenerateDerivedKey(
+ int idByte,
+ int n)
+ {
+ byte[] D = new byte[v];
+ byte[] dKey = new byte[n];
+
+ for (int i = 0; i != D.Length; i++)
+ {
+ D[i] = (byte)idByte;
+ }
+
+ byte[] S;
+
+ if ((mSalt != null) && (mSalt.Length != 0))
+ {
+ S = new byte[v * ((mSalt.Length + v - 1) / v)];
+
+ for (int i = 0; i != S.Length; i++)
+ {
+ S[i] = mSalt[i % mSalt.Length];
+ }
+ }
+ else
+ {
+ S = new byte[0];
+ }
+
+ byte[] P;
+
+ if ((mPassword != null) && (mPassword.Length != 0))
+ {
+ P = new byte[v * ((mPassword.Length + v - 1) / v)];
+
+ for (int i = 0; i != P.Length; i++)
+ {
+ P[i] = mPassword[i % mPassword.Length];
+ }
+ }
+ else
+ {
+ P = new byte[0];
+ }
+
+ byte[] I = new byte[S.Length + P.Length];
+
+ Array.Copy(S, 0, I, 0, S.Length);
+ Array.Copy(P, 0, I, S.Length, P.Length);
+
+ byte[] B = new byte[v];
+ int c = (n + u - 1) / u;
+ byte[] A = new byte[u];
+
+ for (int i = 1; i <= c; i++)
+ {
+ digest.BlockUpdate(D, 0, D.Length);
+ digest.BlockUpdate(I, 0, I.Length);
+ digest.DoFinal(A, 0);
+
+ for (int j = 1; j != mIterationCount; j++)
+ {
+ digest.BlockUpdate(A, 0, A.Length);
+ digest.DoFinal(A, 0);
+ }
+
+ for (int j = 0; j != B.Length; j++)
+ {
+ B[j] = A[j % A.Length];
+ }
+
+ for (int j = 0; j != I.Length / v; j++)
+ {
+ Adjust(I, j * v, B);
+ }
+
+ if (i == c)
+ {
+ Array.Copy(A, 0, dKey, (i - 1) * u, dKey.Length - ((i - 1) * u));
+ }
+ else
+ {
+ Array.Copy(A, 0, dKey, (i - 1) * u, A.Length);
+ }
+ }
+
+ return dKey;
+ }
+
+ /**
+ * Generate a key parameter derived from the password, salt, and iteration
+ * count we are currently initialised with.
+ *
+ * @param keySize the size of the key we want (in bits)
+ * @return a KeyParameter object.
+ */
+ public override ICipherParameters GenerateDerivedParameters(
+ int keySize)
+ {
+ keySize /= 8;
+
+ byte[] dKey = GenerateDerivedKey(KeyMaterial, keySize);
+
+ return new KeyParameter(dKey, 0, keySize);
+ }
+
+ public override ICipherParameters GenerateDerivedParameters(
+ string algorithm,
+ int keySize)
+ {
+ keySize /= 8;
+
+ byte[] dKey = GenerateDerivedKey(KeyMaterial, keySize);
+
+ return ParameterUtilities.CreateKeyParameter(algorithm, dKey, 0, keySize);
+ }
+
+ /**
+ * Generate a key with initialisation vector parameter derived from
+ * the password, salt, and iteration count we are currently initialised
+ * with.
+ *
+ * @param keySize the size of the key we want (in bits)
+ * @param ivSize the size of the iv we want (in bits)
+ * @return a ParametersWithIV object.
+ */
+ public override ICipherParameters GenerateDerivedParameters(
+ int keySize,
+ int ivSize)
+ {
+ keySize /= 8;
+ ivSize /= 8;
+
+ byte[] dKey = GenerateDerivedKey(KeyMaterial, keySize);
+
+ byte[] iv = GenerateDerivedKey(IVMaterial, ivSize);
+
+ return new ParametersWithIV(new KeyParameter(dKey, 0, keySize), iv, 0, ivSize);
+ }
+
+ public override ICipherParameters GenerateDerivedParameters(
+ string algorithm,
+ int keySize,
+ int ivSize)
+ {
+ keySize /= 8;
+ ivSize /= 8;
+
+ byte[] dKey = GenerateDerivedKey(KeyMaterial, keySize);
+ KeyParameter key = ParameterUtilities.CreateKeyParameter(algorithm, dKey, 0, keySize);
+
+ byte[] iv = GenerateDerivedKey(IVMaterial, ivSize);
+
+ return new ParametersWithIV(key, iv, 0, ivSize);
+ }
+
+ /**
+ * Generate a key parameter for use with a MAC derived from the password,
+ * salt, and iteration count we are currently initialised with.
+ *
+ * @param keySize the size of the key we want (in bits)
+ * @return a KeyParameter object.
+ */
+ public override ICipherParameters GenerateDerivedMacParameters(
+ int keySize)
+ {
+ keySize /= 8;
+
+ byte[] dKey = GenerateDerivedKey(MacMaterial, keySize);
+
+ return new KeyParameter(dKey, 0, keySize);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Pkcs12ParametersGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Pkcs12ParametersGenerator.cs.meta
new file mode 100644
index 00000000..808d7297
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Pkcs12ParametersGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 80f581c321bf56745a81a710ed7fc4c0
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Pkcs5S1ParametersGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Pkcs5S1ParametersGenerator.cs
new file mode 100644
index 00000000..bf469e6a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Pkcs5S1ParametersGenerator.cs
@@ -0,0 +1,164 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ /**
+ * Generator for Pbe derived keys and ivs as defined by Pkcs 5 V2.0 Scheme 1.
+ * Note this generator is limited to the size of the hash produced by the
+ * digest used to drive it.
+ *
+ * The document this implementation is based on can be found at
+ *
+ * RSA's Pkcs5 Page
+ *
+ */
+ public class Pkcs5S1ParametersGenerator
+ : PbeParametersGenerator
+ {
+ private readonly IDigest digest;
+
+ /**
+ * Construct a Pkcs 5 Scheme 1 Parameters generator.
+ *
+ * @param digest the digest to be used as the source of derived keys.
+ */
+ public Pkcs5S1ParametersGenerator(
+ IDigest digest)
+ {
+ this.digest = digest;
+ }
+
+ /**
+ * the derived key function, the ith hash of the mPassword and the mSalt.
+ */
+ private byte[] GenerateDerivedKey()
+ {
+ byte[] digestBytes = new byte[digest.GetDigestSize()];
+
+ digest.BlockUpdate(mPassword, 0, mPassword.Length);
+ digest.BlockUpdate(mSalt, 0, mSalt.Length);
+
+ digest.DoFinal(digestBytes, 0);
+ for (int i = 1; i < mIterationCount; i++)
+ {
+ digest.BlockUpdate(digestBytes, 0, digestBytes.Length);
+ digest.DoFinal(digestBytes, 0);
+ }
+
+ return digestBytes;
+ }
+
+ /**
+ * Generate a key parameter derived from the mPassword, mSalt, and iteration
+ * count we are currently initialised with.
+ *
+ * @param keySize the size of the key we want (in bits)
+ * @return a KeyParameter object.
+ * @exception ArgumentException if the key length larger than the base hash size.
+ */
+ public override ICipherParameters GenerateDerivedParameters(
+ int keySize)
+ {
+ return GenerateDerivedMacParameters(keySize);
+ }
+
+ public override ICipherParameters GenerateDerivedParameters(
+ string algorithm,
+ int keySize)
+ {
+ keySize /= 8;
+
+ if (keySize > digest.GetDigestSize())
+ {
+ throw new ArgumentException(
+ "Can't Generate a derived key " + keySize + " bytes long.");
+ }
+
+ byte[] dKey = GenerateDerivedKey();
+
+ return ParameterUtilities.CreateKeyParameter(algorithm, dKey, 0, keySize);
+ }
+
+ /**
+ * Generate a key with initialisation vector parameter derived from
+ * the mPassword, mSalt, and iteration count we are currently initialised
+ * with.
+ *
+ * @param keySize the size of the key we want (in bits)
+ * @param ivSize the size of the iv we want (in bits)
+ * @return a ParametersWithIV object.
+ * @exception ArgumentException if keySize + ivSize is larger than the base hash size.
+ */
+ public override ICipherParameters GenerateDerivedParameters(
+ int keySize,
+ int ivSize)
+ {
+ keySize /= 8;
+ ivSize /= 8;
+
+ if ((keySize + ivSize) > digest.GetDigestSize())
+ {
+ throw new ArgumentException(
+ "Can't Generate a derived key " + (keySize + ivSize) + " bytes long.");
+ }
+
+ byte[] dKey = GenerateDerivedKey();
+
+ return new ParametersWithIV(new KeyParameter(dKey, 0, keySize), dKey, keySize, ivSize);
+ }
+
+ public override ICipherParameters GenerateDerivedParameters(
+ string algorithm,
+ int keySize,
+ int ivSize)
+ {
+ keySize /= 8;
+ ivSize /= 8;
+
+ if ((keySize + ivSize) > digest.GetDigestSize())
+ {
+ throw new ArgumentException(
+ "Can't Generate a derived key " + (keySize + ivSize) + " bytes long.");
+ }
+
+ byte[] dKey = GenerateDerivedKey();
+ KeyParameter key = ParameterUtilities.CreateKeyParameter(algorithm, dKey, 0, keySize);
+
+ return new ParametersWithIV(key, dKey, keySize, ivSize);
+ }
+
+ /**
+ * Generate a key parameter for use with a MAC derived from the mPassword,
+ * mSalt, and iteration count we are currently initialised with.
+ *
+ * @param keySize the size of the key we want (in bits)
+ * @return a KeyParameter object.
+ * @exception ArgumentException if the key length larger than the base hash size.
+ */
+ public override ICipherParameters GenerateDerivedMacParameters(
+ int keySize)
+ {
+ keySize /= 8;
+
+ if (keySize > digest.GetDigestSize())
+ {
+ throw new ArgumentException(
+ "Can't Generate a derived key " + keySize + " bytes long.");
+ }
+
+ byte[] dKey = GenerateDerivedKey();
+
+ return new KeyParameter(dKey, 0, keySize);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Pkcs5S1ParametersGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Pkcs5S1ParametersGenerator.cs.meta
new file mode 100644
index 00000000..43f73a70
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Pkcs5S1ParametersGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0c288f7bdb27a2b4ebbfe5e2b74e4e30
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Pkcs5S2ParametersGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Pkcs5S2ParametersGenerator.cs
new file mode 100644
index 00000000..35c5b3e9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Pkcs5S2ParametersGenerator.cs
@@ -0,0 +1,182 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ /**
+ * Generator for Pbe derived keys and ivs as defined by Pkcs 5 V2.0 Scheme 2.
+ * This generator uses a SHA-1 HMac as the calculation function.
+ *
+ * The document this implementation is based on can be found at
+ *
+ * RSA's Pkcs5 Page
+ */
+ public class Pkcs5S2ParametersGenerator
+ : PbeParametersGenerator
+ {
+ private readonly IMac hMac;
+ private readonly byte[] state;
+
+ /**
+ * construct a Pkcs5 Scheme 2 Parameters generator.
+ */
+ public Pkcs5S2ParametersGenerator()
+ : this(new Sha1Digest())
+ {
+ }
+
+ public Pkcs5S2ParametersGenerator(IDigest digest)
+ {
+ this.hMac = new HMac(digest);
+ this.state = new byte[hMac.GetMacSize()];
+ }
+
+ private void F(
+ byte[] S,
+ int c,
+ byte[] iBuf,
+ byte[] outBytes,
+ int outOff)
+ {
+ if (c == 0)
+ throw new ArgumentException("iteration count must be at least 1.");
+
+ if (S != null)
+ {
+ hMac.BlockUpdate(S, 0, S.Length);
+ }
+
+ hMac.BlockUpdate(iBuf, 0, iBuf.Length);
+ hMac.DoFinal(state, 0);
+
+ Array.Copy(state, 0, outBytes, outOff, state.Length);
+
+ for (int count = 1; count < c; ++count)
+ {
+ hMac.BlockUpdate(state, 0, state.Length);
+ hMac.DoFinal(state, 0);
+
+ for (int j = 0; j < state.Length; ++j)
+ {
+ outBytes[outOff + j] ^= state[j];
+ }
+ }
+ }
+
+ private byte[] GenerateDerivedKey(
+ int dkLen)
+ {
+ int hLen = hMac.GetMacSize();
+ int l = (dkLen + hLen - 1) / hLen;
+ byte[] iBuf = new byte[4];
+ byte[] outBytes = new byte[l * hLen];
+ int outPos = 0;
+
+ ICipherParameters param = new KeyParameter(mPassword);
+
+ hMac.Init(param);
+
+ for (int i = 1; i <= l; i++)
+ {
+ // Increment the value in 'iBuf'
+ int pos = 3;
+ while (++iBuf[pos] == 0)
+ {
+ --pos;
+ }
+
+ F(mSalt, mIterationCount, iBuf, outBytes, outPos);
+ outPos += hLen;
+ }
+
+ return outBytes;
+ }
+
+ /**
+ * Generate a key parameter derived from the password, salt, and iteration
+ * count we are currently initialised with.
+ *
+ * @param keySize the size of the key we want (in bits)
+ * @return a KeyParameter object.
+ */
+ public override ICipherParameters GenerateDerivedParameters(
+ int keySize)
+ {
+ return GenerateDerivedMacParameters(keySize);
+ }
+
+ public override ICipherParameters GenerateDerivedParameters(
+ string algorithm,
+ int keySize)
+ {
+ keySize /= 8;
+
+ byte[] dKey = GenerateDerivedKey(keySize);
+
+ return ParameterUtilities.CreateKeyParameter(algorithm, dKey, 0, keySize);
+ }
+
+ /**
+ * Generate a key with initialisation vector parameter derived from
+ * the password, salt, and iteration count we are currently initialised
+ * with.
+ *
+ * @param keySize the size of the key we want (in bits)
+ * @param ivSize the size of the iv we want (in bits)
+ * @return a ParametersWithIV object.
+ */
+ public override ICipherParameters GenerateDerivedParameters(
+ int keySize,
+ int ivSize)
+ {
+ keySize /= 8;
+ ivSize /= 8;
+
+ byte[] dKey = GenerateDerivedKey(keySize + ivSize);
+
+ return new ParametersWithIV(new KeyParameter(dKey, 0, keySize), dKey, keySize, ivSize);
+ }
+
+ public override ICipherParameters GenerateDerivedParameters(
+ string algorithm,
+ int keySize,
+ int ivSize)
+ {
+ keySize /= 8;
+ ivSize /= 8;
+
+ byte[] dKey = GenerateDerivedKey(keySize + ivSize);
+ KeyParameter key = ParameterUtilities.CreateKeyParameter(algorithm, dKey, 0, keySize);
+
+ return new ParametersWithIV(key, dKey, keySize, ivSize);
+ }
+
+ /**
+ * Generate a key parameter for use with a MAC derived from the password,
+ * salt, and iteration count we are currently initialised with.
+ *
+ * @param keySize the size of the key we want (in bits)
+ * @return a KeyParameter object.
+ */
+ public override ICipherParameters GenerateDerivedMacParameters(
+ int keySize)
+ {
+ keySize /= 8;
+
+ byte[] dKey = GenerateDerivedKey(keySize);
+
+ return new KeyParameter(dKey, 0, keySize);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Pkcs5S2ParametersGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Pkcs5S2ParametersGenerator.cs.meta
new file mode 100644
index 00000000..b1b7451f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Pkcs5S2ParametersGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 059cb4d08d9b8cc49b1a842639d86b27
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Poly1305KeyGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Poly1305KeyGenerator.cs
new file mode 100644
index 00000000..9f337248
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Poly1305KeyGenerator.cs
@@ -0,0 +1,120 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ ///
+ /// Generates keys for the Poly1305 MAC.
+ ///
+ ///
+ /// Poly1305 keys are 256 bit keys consisting of a 128 bit secret key used for the underlying block
+ /// cipher followed by a 128 bit {@code r} value used for the polynomial portion of the Mac.
+ /// The {@code r} value has a specific format with some bits required to be cleared, resulting in an
+ /// effective 106 bit key.
+ /// A separately generated 256 bit key can be modified to fit the Poly1305 key format by using the
+ /// {@link #clamp(byte[])} method to clear the required bits.
+ ///
+ ///
+ public class Poly1305KeyGenerator
+ : CipherKeyGenerator
+ {
+ private const byte R_MASK_LOW_2 = (byte)0xFC;
+ private const byte R_MASK_HIGH_4 = (byte)0x0F;
+
+ ///
+ /// Initialises the key generator.
+ ///
+ ///
+ /// Poly1305 keys are always 256 bits, so the key length in the provided parameters is ignored.
+ ///
+ protected override void engineInit(KeyGenerationParameters param)
+ {
+ // Poly1305 keys are always 256 bits
+ this.random = param.Random;
+ this.strength = 32;
+ }
+
+ ///
+ /// Generates a 256 bit key in the format required for Poly1305 - e.g.
+ /// k[0] ... k[15], r[0] ... r[15] with the required bits in r cleared
+ /// as per .
+ ///
+ protected override byte[] engineGenerateKey()
+ {
+ byte[] key = base.engineGenerateKey();
+ Clamp(key);
+ return key;
+ }
+
+ ///
+ /// Modifies an existing 32 byte key value to comply with the requirements of the Poly1305 key by
+ /// clearing required bits in the r (second 16 bytes) portion of the key.
+ /// Specifically:
+ ///
+ ///
r[3], r[7], r[11], r[15] have top four bits clear (i.e., are {0, 1, . . . , 15})
+ ///
r[4], r[8], r[12] have bottom two bits clear (i.e., are in {0, 4, 8, . . . , 252})
+ ///
+ ///
+ /// a 32 byte key value k[0] ... k[15], r[0] ... r[15]
+ public static void Clamp(byte[] key)
+ {
+ /*
+ * Key is k[0] ... k[15], r[0] ... r[15] as per poly1305_aes_clamp in ref impl.
+ */
+ if (key.Length != 32)
+ throw new ArgumentException("Poly1305 key must be 256 bits.");
+
+ /*
+ * r[3], r[7], r[11], r[15] have top four bits clear (i.e., are {0, 1, . . . , 15})
+ */
+ key[3] &= R_MASK_HIGH_4;
+ key[7] &= R_MASK_HIGH_4;
+ key[11] &= R_MASK_HIGH_4;
+ key[15] &= R_MASK_HIGH_4;
+
+ /*
+ * r[4], r[8], r[12] have bottom two bits clear (i.e., are in {0, 4, 8, . . . , 252}).
+ */
+ key[4] &= R_MASK_LOW_2;
+ key[8] &= R_MASK_LOW_2;
+ key[12] &= R_MASK_LOW_2;
+ }
+
+ ///
+ /// Checks a 32 byte key for compliance with the Poly1305 key requirements, e.g.
+ /// k[0] ... k[15], r[0] ... r[15] with the required bits in r cleared
+ /// as per .
+ ///
+ /// Key.
+ /// if the key is of the wrong length, or has invalid bits set
+ /// in the r portion of the key.
+ public static void CheckKey(byte[] key)
+ {
+ if (key.Length != 32)
+ throw new ArgumentException("Poly1305 key must be 256 bits.");
+
+ CheckMask(key[3], R_MASK_HIGH_4);
+ CheckMask(key[7], R_MASK_HIGH_4);
+ CheckMask(key[11], R_MASK_HIGH_4);
+ CheckMask(key[15], R_MASK_HIGH_4);
+
+ CheckMask(key[4], R_MASK_LOW_2);
+ CheckMask(key[8], R_MASK_LOW_2);
+ CheckMask(key[12], R_MASK_LOW_2);
+ }
+
+ private static void CheckMask(byte b, byte mask)
+ {
+ if ((b & (~mask)) != 0)
+ throw new ArgumentException("Invalid format for r portion of Poly1305 key.");
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Poly1305KeyGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Poly1305KeyGenerator.cs.meta
new file mode 100644
index 00000000..5ab35d84
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/Poly1305KeyGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 5da95a369948e924eaed42d18e10729a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/RSABlindingFactorGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/RSABlindingFactorGenerator.cs
new file mode 100644
index 00000000..89d8a588
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/RSABlindingFactorGenerator.cs
@@ -0,0 +1,73 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ /**
+ * Generate a random factor suitable for use with RSA blind signatures
+ * as outlined in Chaum's blinding and unblinding as outlined in
+ * "Handbook of Applied Cryptography", page 475.
+ */
+ public class RsaBlindingFactorGenerator
+ {
+ private RsaKeyParameters key;
+ private SecureRandom random;
+
+ /**
+ * Initialise the factor generator
+ *
+ * @param param the necessary RSA key parameters.
+ */
+ public void Init(
+ ICipherParameters param)
+ {
+ if (param is ParametersWithRandom)
+ {
+ ParametersWithRandom rParam = (ParametersWithRandom)param;
+
+ key = (RsaKeyParameters)rParam.Parameters;
+ random = rParam.Random;
+ }
+ else
+ {
+ key = (RsaKeyParameters)param;
+ random = new SecureRandom();
+ }
+
+ if (key.IsPrivate)
+ throw new ArgumentException("generator requires RSA public key");
+ }
+
+ /**
+ * Generate a suitable blind factor for the public key the generator was initialised with.
+ *
+ * @return a random blind factor
+ */
+ public BigInteger GenerateBlindingFactor()
+ {
+ if (key == null)
+ throw new InvalidOperationException("generator not initialised");
+
+ BigInteger m = key.Modulus;
+ int length = m.BitLength - 1; // must be less than m.BitLength
+ BigInteger factor;
+ BigInteger gcd;
+
+ do
+ {
+ factor = new BigInteger(length, random);
+ gcd = factor.Gcd(m);
+ }
+ while (factor.SignValue == 0 || factor.Equals(BigInteger.One) || !gcd.Equals(BigInteger.One));
+
+ return factor;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/RSABlindingFactorGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/RSABlindingFactorGenerator.cs.meta
new file mode 100644
index 00000000..6e491f7d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/RSABlindingFactorGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: bf74dd7003cd2824f9339e01e58b2e7f
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/RsaKeyPairGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/RsaKeyPairGenerator.cs
new file mode 100644
index 00000000..577c769b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/RsaKeyPairGenerator.cs
@@ -0,0 +1,167 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Multiplier;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ /**
+ * an RSA key pair generator.
+ */
+ public class RsaKeyPairGenerator
+ : IAsymmetricCipherKeyPairGenerator
+ {
+ private static readonly int[] SPECIAL_E_VALUES = new int[]{ 3, 5, 17, 257, 65537 };
+ private static readonly int SPECIAL_E_HIGHEST = SPECIAL_E_VALUES[SPECIAL_E_VALUES.Length - 1];
+ private static readonly int SPECIAL_E_BITS = BigInteger.ValueOf(SPECIAL_E_HIGHEST).BitLength;
+
+ protected static readonly BigInteger One = BigInteger.One;
+ protected static readonly BigInteger DefaultPublicExponent = BigInteger.ValueOf(0x10001);
+ protected const int DefaultTests = 100;
+
+ protected RsaKeyGenerationParameters parameters;
+
+ public virtual void Init(
+ KeyGenerationParameters parameters)
+ {
+ if (parameters is RsaKeyGenerationParameters)
+ {
+ this.parameters = (RsaKeyGenerationParameters)parameters;
+ }
+ else
+ {
+ this.parameters = new RsaKeyGenerationParameters(
+ DefaultPublicExponent, parameters.Random, parameters.Strength, DefaultTests);
+ }
+ }
+
+ public virtual AsymmetricCipherKeyPair GenerateKeyPair()
+ {
+ for (;;)
+ {
+ //
+ // p and q values should have a length of half the strength in bits
+ //
+ int strength = parameters.Strength;
+ int pBitlength = (strength + 1) / 2;
+ int qBitlength = strength - pBitlength;
+ int mindiffbits = strength / 3;
+ int minWeight = strength >> 2;
+
+ BigInteger e = parameters.PublicExponent;
+
+ // TODO Consider generating safe primes for p, q (see DHParametersHelper.generateSafePrimes)
+ // (then p-1 and q-1 will not consist of only small factors - see "Pollard's algorithm")
+
+ BigInteger p = ChooseRandomPrime(pBitlength, e);
+ BigInteger q, n;
+
+ //
+ // generate a modulus of the required length
+ //
+ for (;;)
+ {
+ q = ChooseRandomPrime(qBitlength, e);
+
+ // p and q should not be too close together (or equal!)
+ BigInteger diff = q.Subtract(p).Abs();
+ if (diff.BitLength < mindiffbits)
+ continue;
+
+ //
+ // calculate the modulus
+ //
+ n = p.Multiply(q);
+
+ if (n.BitLength != strength)
+ {
+ //
+ // if we get here our primes aren't big enough, make the largest
+ // of the two p and try again
+ //
+ p = p.Max(q);
+ continue;
+ }
+
+ /*
+ * Require a minimum weight of the NAF representation, since low-weight composites may
+ * be weak against a version of the number-field-sieve for factoring.
+ *
+ * See "The number field sieve for integers of low weight", Oliver Schirokauer.
+ */
+ if (WNafUtilities.GetNafWeight(n) < minWeight)
+ {
+ p = ChooseRandomPrime(pBitlength, e);
+ continue;
+ }
+
+ break;
+ }
+
+ if (p.CompareTo(q) < 0)
+ {
+ BigInteger tmp = p;
+ p = q;
+ q = tmp;
+ }
+
+ BigInteger pSub1 = p.Subtract(One);
+ BigInteger qSub1 = q.Subtract(One);
+ //BigInteger phi = pSub1.Multiply(qSub1);
+ BigInteger gcd = pSub1.Gcd(qSub1);
+ BigInteger lcm = pSub1.Divide(gcd).Multiply(qSub1);
+
+ //
+ // calculate the private exponent
+ //
+ BigInteger d = e.ModInverse(lcm);
+
+ if (d.BitLength <= qBitlength)
+ continue;
+
+ //
+ // calculate the CRT factors
+ //
+ BigInteger dP = d.Remainder(pSub1);
+ BigInteger dQ = d.Remainder(qSub1);
+ BigInteger qInv = q.ModInverse(p);
+
+ return new AsymmetricCipherKeyPair(
+ new RsaKeyParameters(false, n, e),
+ new RsaPrivateCrtKeyParameters(n, e, d, p, q, dP, dQ, qInv));
+ }
+ }
+
+ /// Choose a random prime value for use with RSA
+ /// the bit-length of the returned prime
+ /// the RSA public exponent
+ /// a prime p, with (p-1) relatively prime to e
+ protected virtual BigInteger ChooseRandomPrime(int bitlength, BigInteger e)
+ {
+ bool eIsKnownOddPrime = (e.BitLength <= SPECIAL_E_BITS) && Arrays.Contains(SPECIAL_E_VALUES, e.IntValue);
+
+ for (;;)
+ {
+ BigInteger p = new BigInteger(bitlength, 1, parameters.Random);
+
+ if (p.Mod(e).Equals(One))
+ continue;
+
+ if (!p.IsProbablePrime(parameters.Certainty, true))
+ continue;
+
+ if (!eIsKnownOddPrime && !e.Gcd(p.Subtract(One)).Equals(One))
+ continue;
+
+ return p;
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/RsaKeyPairGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/RsaKeyPairGenerator.cs.meta
new file mode 100644
index 00000000..84cef2b6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/RsaKeyPairGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: d11ab5e345ab24647ab0356dc7f92e64
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/SCrypt.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/SCrypt.cs
new file mode 100644
index 00000000..ed168743
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/SCrypt.cs
@@ -0,0 +1,186 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Diagnostics;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ /// Implementation of the scrypt a password-based key derivation function.
+ ///
+ /// Scrypt was created by Colin Percival and is specified in
+ /// draft-josefsson-scrypt-kd.
+ ///
+ public class SCrypt
+ {
+ /// Generate a key using the scrypt key derivation function.
+ /// the bytes of the pass phrase.
+ /// the salt to use for this invocation.
+ /// CPU/Memory cost parameter. Must be larger than 1, a power of 2 and less than
+ /// 2^(128 * r / 8).
+ /// the block size, must be >= 1.
+ /// Parallelization parameter. Must be a positive integer less than or equal to
+ /// Int32.MaxValue / (128 * r * 8).
+ /// the length of the key to generate.
+ /// the generated key.
+ public static byte[] Generate(byte[] P, byte[] S, int N, int r, int p, int dkLen)
+ {
+ if (P == null)
+ throw new ArgumentNullException("Passphrase P must be provided.");
+ if (S == null)
+ throw new ArgumentNullException("Salt S must be provided.");
+ if (N <= 1 || !IsPowerOf2(N))
+ throw new ArgumentException("Cost parameter N must be > 1 and a power of 2.");
+ // Only value of r that cost (as an int) could be exceeded for is 1
+ if (r == 1 && N >= 65536)
+ throw new ArgumentException("Cost parameter N must be > 1 and < 65536.");
+ if (r < 1)
+ throw new ArgumentException("Block size r must be >= 1.");
+ int maxParallel = Int32.MaxValue / (128 * r * 8);
+ if (p < 1 || p > maxParallel)
+ {
+ throw new ArgumentException("Parallelisation parameter p must be >= 1 and <= " + maxParallel
+ + " (based on block size r of " + r + ")");
+ }
+ if (dkLen < 1)
+ throw new ArgumentException("Generated key length dkLen must be >= 1.");
+
+ return MFcrypt(P, S, N, r, p, dkLen);
+ }
+
+ private static byte[] MFcrypt(byte[] P, byte[] S, int N, int r, int p, int dkLen)
+ {
+ int MFLenBytes = r * 128;
+ byte[] bytes = SingleIterationPBKDF2(P, S, p * MFLenBytes);
+
+ uint[] B = null;
+
+ try
+ {
+ int BLen = bytes.Length >> 2;
+ B = new uint[BLen];
+
+ Pack.LE_To_UInt32(bytes, 0, B);
+
+ int MFLenWords = MFLenBytes >> 2;
+ for (int BOff = 0; BOff < BLen; BOff += MFLenWords)
+ {
+ // TODO These can be done in parallel threads
+ SMix(B, BOff, N, r);
+ }
+
+ Pack.UInt32_To_LE(B, bytes, 0);
+
+ return SingleIterationPBKDF2(P, bytes, dkLen);
+ }
+ finally
+ {
+ ClearAll(bytes, B);
+ }
+ }
+
+ private static byte[] SingleIterationPBKDF2(byte[] P, byte[] S, int dkLen)
+ {
+ PbeParametersGenerator pGen = new Pkcs5S2ParametersGenerator(new Sha256Digest());
+ pGen.Init(P, S, 1);
+ KeyParameter key = (KeyParameter)pGen.GenerateDerivedMacParameters(dkLen * 8);
+ return key.GetKey();
+ }
+
+ private static void SMix(uint[] B, int BOff, int N, int r)
+ {
+ int BCount = r * 32;
+
+ uint[] blockX1 = new uint[16];
+ uint[] blockX2 = new uint[16];
+ uint[] blockY = new uint[BCount];
+
+ uint[] X = new uint[BCount];
+ uint[][] V = new uint[N][];
+
+ try
+ {
+ Array.Copy(B, BOff, X, 0, BCount);
+
+ for (int i = 0; i < N; ++i)
+ {
+ V[i] = (uint[])X.Clone();
+ BlockMix(X, blockX1, blockX2, blockY, r);
+ }
+
+ uint mask = (uint)N - 1;
+ for (int i = 0; i < N; ++i)
+ {
+ uint j = X[BCount - 16] & mask;
+ Xor(X, V[j], 0, X);
+ BlockMix(X, blockX1, blockX2, blockY, r);
+ }
+
+ Array.Copy(X, 0, B, BOff, BCount);
+ }
+ finally
+ {
+ ClearAll(V);
+ ClearAll(X, blockX1, blockX2, blockY);
+ }
+ }
+
+ private static void BlockMix(uint[] B, uint[] X1, uint[] X2, uint[] Y, int r)
+ {
+ Array.Copy(B, B.Length - 16, X1, 0, 16);
+
+ int BOff = 0, YOff = 0, halfLen = B.Length >> 1;
+
+ for (int i = 2 * r; i > 0; --i)
+ {
+ Xor(X1, B, BOff, X2);
+
+ Salsa20Engine.SalsaCore(8, X2, X1);
+ Array.Copy(X1, 0, Y, YOff, 16);
+
+ YOff = halfLen + BOff - YOff;
+ BOff += 16;
+ }
+
+ Array.Copy(Y, 0, B, 0, Y.Length);
+ }
+
+ private static void Xor(uint[] a, uint[] b, int bOff, uint[] output)
+ {
+ for (int i = output.Length - 1; i >= 0; --i)
+ {
+ output[i] = a[i] ^ b[bOff + i];
+ }
+ }
+
+ private static void Clear(Array array)
+ {
+ if (array != null)
+ {
+ Array.Clear(array, 0, array.Length);
+ }
+ }
+
+ private static void ClearAll(params Array[] arrays)
+ {
+ foreach (Array array in arrays)
+ {
+ Clear(array);
+ }
+ }
+
+ // note: we know X is non-zero
+ private static bool IsPowerOf2(int x)
+ {
+ Debug.Assert(x != 0);
+
+ return (x & (x - 1)) == 0;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/SCrypt.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/SCrypt.cs.meta
new file mode 100644
index 00000000..9444d8e8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/SCrypt.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c8823cf014ab23d449745f5379eb32e6
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/X25519KeyPairGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/X25519KeyPairGenerator.cs
new file mode 100644
index 00000000..8dc6cc99
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/X25519KeyPairGenerator.cs
@@ -0,0 +1,29 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ public class X25519KeyPairGenerator
+ : IAsymmetricCipherKeyPairGenerator
+ {
+ private SecureRandom random;
+
+ public virtual void Init(KeyGenerationParameters parameters)
+ {
+ this.random = parameters.Random;
+ }
+
+ public virtual AsymmetricCipherKeyPair GenerateKeyPair()
+ {
+ X25519PrivateKeyParameters privateKey = new X25519PrivateKeyParameters(random);
+ X25519PublicKeyParameters publicKey = privateKey.GeneratePublicKey();
+ return new AsymmetricCipherKeyPair(publicKey, privateKey);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/X25519KeyPairGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/X25519KeyPairGenerator.cs.meta
new file mode 100644
index 00000000..42ec38da
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/X25519KeyPairGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c6529992521da3f47a1b632f2b203fb1
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/X448KeyPairGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/X448KeyPairGenerator.cs
new file mode 100644
index 00000000..d2f9b091
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/X448KeyPairGenerator.cs
@@ -0,0 +1,29 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
+{
+ public class X448KeyPairGenerator
+ : IAsymmetricCipherKeyPairGenerator
+ {
+ private SecureRandom random;
+
+ public virtual void Init(KeyGenerationParameters parameters)
+ {
+ this.random = parameters.Random;
+ }
+
+ public virtual AsymmetricCipherKeyPair GenerateKeyPair()
+ {
+ X448PrivateKeyParameters privateKey = new X448PrivateKeyParameters(random);
+ X448PublicKeyParameters publicKey = privateKey.GeneratePublicKey();
+ return new AsymmetricCipherKeyPair(publicKey, privateKey);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/X448KeyPairGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/X448KeyPairGenerator.cs.meta
new file mode 100644
index 00000000..fb9f90e4
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/generators/X448KeyPairGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 4a6f36d86b2007d4ca27dea499f0770a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io.meta
new file mode 100644
index 00000000..a861b3ea
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 0d16b3ea73dbb9648b5c61af890ff3fc
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/CipherStream.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/CipherStream.cs
new file mode 100644
index 00000000..3a8bb46e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/CipherStream.cs
@@ -0,0 +1,256 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Diagnostics;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.IO
+{
+ public class CipherStream
+ : Stream
+ {
+ internal Stream stream;
+ internal IBufferedCipher inCipher, outCipher;
+ private byte[] mInBuf;
+ private int mInPos;
+ private bool inStreamEnded;
+
+ public CipherStream(
+ Stream stream,
+ IBufferedCipher readCipher,
+ IBufferedCipher writeCipher)
+ {
+ this.stream = stream;
+
+ if (readCipher != null)
+ {
+ this.inCipher = readCipher;
+ mInBuf = null;
+ }
+
+ if (writeCipher != null)
+ {
+ this.outCipher = writeCipher;
+ }
+ }
+
+ public IBufferedCipher ReadCipher
+ {
+ get { return inCipher; }
+ }
+
+ public IBufferedCipher WriteCipher
+ {
+ get { return outCipher; }
+ }
+
+ public override int ReadByte()
+ {
+ if (inCipher == null)
+ return stream.ReadByte();
+
+ if (mInBuf == null || mInPos >= mInBuf.Length)
+ {
+ if (!FillInBuf())
+ return -1;
+ }
+
+ return mInBuf[mInPos++];
+ }
+
+ public override int Read(
+ byte[] buffer,
+ int offset,
+ int count)
+ {
+ if (inCipher == null)
+ return stream.Read(buffer, offset, count);
+
+ int num = 0;
+ while (num < count)
+ {
+ if (mInBuf == null || mInPos >= mInBuf.Length)
+ {
+ if (!FillInBuf())
+ break;
+ }
+
+ int numToCopy = System.Math.Min(count - num, mInBuf.Length - mInPos);
+ Array.Copy(mInBuf, mInPos, buffer, offset + num, numToCopy);
+ mInPos += numToCopy;
+ num += numToCopy;
+ }
+
+ return num;
+ }
+
+ private bool FillInBuf()
+ {
+ if (inStreamEnded)
+ return false;
+
+ mInPos = 0;
+
+ do
+ {
+ mInBuf = ReadAndProcessBlock();
+ }
+ while (!inStreamEnded && mInBuf == null);
+
+ return mInBuf != null;
+ }
+
+ private byte[] ReadAndProcessBlock()
+ {
+ int blockSize = inCipher.GetBlockSize();
+ int readSize = (blockSize == 0) ? 256 : blockSize;
+
+ byte[] block = new byte[readSize];
+ int numRead = 0;
+ do
+ {
+ int count = stream.Read(block, numRead, block.Length - numRead);
+ if (count < 1)
+ {
+ inStreamEnded = true;
+ break;
+ }
+ numRead += count;
+ }
+ while (numRead < block.Length);
+
+ Debug.Assert(inStreamEnded || numRead == block.Length);
+
+ byte[] bytes = inStreamEnded
+ ? inCipher.DoFinal(block, 0, numRead)
+ : inCipher.ProcessBytes(block);
+
+ if (bytes != null && bytes.Length == 0)
+ {
+ bytes = null;
+ }
+
+ return bytes;
+ }
+
+ public override void Write(
+ byte[] buffer,
+ int offset,
+ int count)
+ {
+ Debug.Assert(buffer != null);
+ Debug.Assert(0 <= offset && offset <= buffer.Length);
+ Debug.Assert(count >= 0);
+
+ int end = offset + count;
+
+ Debug.Assert(0 <= end && end <= buffer.Length);
+
+ if (outCipher == null)
+ {
+ stream.Write(buffer, offset, count);
+ return;
+ }
+
+ byte[] data = outCipher.ProcessBytes(buffer, offset, count);
+ if (data != null)
+ {
+ stream.Write(data, 0, data.Length);
+ }
+ }
+
+ public override void WriteByte(
+ byte b)
+ {
+ if (outCipher == null)
+ {
+ stream.WriteByte(b);
+ return;
+ }
+
+ byte[] data = outCipher.ProcessByte(b);
+ if (data != null)
+ {
+ stream.Write(data, 0, data.Length);
+ }
+ }
+
+ public override bool CanRead
+ {
+ get { return stream.CanRead && (inCipher != null); }
+ }
+
+ public override bool CanWrite
+ {
+ get { return stream.CanWrite && (outCipher != null); }
+ }
+
+ public override bool CanSeek
+ {
+ get { return false; }
+ }
+
+ public sealed override long Length
+ {
+ get { throw new NotSupportedException(); }
+ }
+
+ public sealed override long Position
+ {
+ get { throw new NotSupportedException(); }
+ set { throw new NotSupportedException(); }
+ }
+
+#if PORTABLE || NETFX_CORE
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ if (outCipher != null)
+ {
+ byte[] data = outCipher.DoFinal();
+ stream.Write(data, 0, data.Length);
+ stream.Flush();
+ }
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(stream);
+ }
+ base.Dispose(disposing);
+ }
+#else
+ public override void Close()
+ {
+ if (outCipher != null)
+ {
+ byte[] data = outCipher.DoFinal();
+ stream.Write(data, 0, data.Length);
+ stream.Flush();
+ }
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(stream);
+ base.Close();
+ }
+#endif
+
+ public override void Flush()
+ {
+ // Note: outCipher.DoFinal is only called during Close()
+ stream.Flush();
+ }
+
+ public sealed override long Seek(
+ long offset,
+ SeekOrigin origin)
+ {
+ throw new NotSupportedException();
+ }
+
+ public sealed override void SetLength(
+ long length)
+ {
+ throw new NotSupportedException();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/CipherStream.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/CipherStream.cs.meta
new file mode 100644
index 00000000..e99f9f7c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/CipherStream.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: f14ba4986c39a4548a143fe9ea9858a8
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/DigestSink.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/DigestSink.cs
new file mode 100644
index 00000000..e5017da1
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/DigestSink.cs
@@ -0,0 +1,39 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.IO
+{
+ public class DigestSink
+ : BaseOutputStream
+ {
+ private readonly IDigest mDigest;
+
+ public DigestSink(IDigest digest)
+ {
+ this.mDigest = digest;
+ }
+
+ public virtual IDigest Digest
+ {
+ get { return mDigest; }
+ }
+
+ public override void WriteByte(byte b)
+ {
+ mDigest.Update(b);
+ }
+
+ public override void Write(byte[] buf, int off, int len)
+ {
+ if (len > 0)
+ {
+ mDigest.BlockUpdate(buf, off, len);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/DigestSink.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/DigestSink.cs.meta
new file mode 100644
index 00000000..a0e844cb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/DigestSink.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 19c2c27df57824948a6439d7aff3cdaf
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/DigestStream.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/DigestStream.cs
new file mode 100644
index 00000000..f6aa9a1e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/DigestStream.cs
@@ -0,0 +1,155 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.IO
+{
+ public class DigestStream
+ : Stream
+ {
+ protected readonly Stream stream;
+ protected readonly IDigest inDigest;
+ protected readonly IDigest outDigest;
+
+ public DigestStream(
+ Stream stream,
+ IDigest readDigest,
+ IDigest writeDigest)
+ {
+ this.stream = stream;
+ this.inDigest = readDigest;
+ this.outDigest = writeDigest;
+ }
+
+ public virtual IDigest ReadDigest()
+ {
+ return inDigest;
+ }
+
+ public virtual IDigest WriteDigest()
+ {
+ return outDigest;
+ }
+
+ public override int Read(
+ byte[] buffer,
+ int offset,
+ int count)
+ {
+ int n = stream.Read(buffer, offset, count);
+ if (inDigest != null)
+ {
+ if (n > 0)
+ {
+ inDigest.BlockUpdate(buffer, offset, n);
+ }
+ }
+ return n;
+ }
+
+ public override int ReadByte()
+ {
+ int b = stream.ReadByte();
+ if (inDigest != null)
+ {
+ if (b >= 0)
+ {
+ inDigest.Update((byte)b);
+ }
+ }
+ return b;
+ }
+
+ public override void Write(
+ byte[] buffer,
+ int offset,
+ int count)
+ {
+ if (outDigest != null)
+ {
+ if (count > 0)
+ {
+ outDigest.BlockUpdate(buffer, offset, count);
+ }
+ }
+ stream.Write(buffer, offset, count);
+ }
+
+ public override void WriteByte(
+ byte b)
+ {
+ if (outDigest != null)
+ {
+ outDigest.Update(b);
+ }
+ stream.WriteByte(b);
+ }
+
+ public override bool CanRead
+ {
+ get { return stream.CanRead; }
+ }
+
+ public override bool CanWrite
+ {
+ get { return stream.CanWrite; }
+ }
+
+ public override bool CanSeek
+ {
+ get { return stream.CanSeek; }
+ }
+
+ public override long Length
+ {
+ get { return stream.Length; }
+ }
+
+ public override long Position
+ {
+ get { return stream.Position; }
+ set { stream.Position = value; }
+ }
+
+#if PORTABLE || NETFX_CORE
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(stream);
+ }
+ base.Dispose(disposing);
+ }
+#else
+ public override void Close()
+ {
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(stream);
+ base.Close();
+ }
+#endif
+
+ public override void Flush()
+ {
+ stream.Flush();
+ }
+
+ public override long Seek(
+ long offset,
+ SeekOrigin origin)
+ {
+ return stream.Seek(offset, origin);
+ }
+
+ public override void SetLength(
+ long length)
+ {
+ stream.SetLength(length);
+ }
+ }
+}
+
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/DigestStream.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/DigestStream.cs.meta
new file mode 100644
index 00000000..858722a2
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/DigestStream.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 97329c855262a8c4c96ebe6fb56f4ffb
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/MacSink.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/MacSink.cs
new file mode 100644
index 00000000..0dbbf520
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/MacSink.cs
@@ -0,0 +1,39 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.IO
+{
+ public class MacSink
+ : BaseOutputStream
+ {
+ private readonly IMac mMac;
+
+ public MacSink(IMac mac)
+ {
+ this.mMac = mac;
+ }
+
+ public virtual IMac Mac
+ {
+ get { return mMac; }
+ }
+
+ public override void WriteByte(byte b)
+ {
+ mMac.Update(b);
+ }
+
+ public override void Write(byte[] buf, int off, int len)
+ {
+ if (len > 0)
+ {
+ mMac.BlockUpdate(buf, off, len);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/MacSink.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/MacSink.cs.meta
new file mode 100644
index 00000000..a30fc66f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/MacSink.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0411a8b05f7e5e3419bd1ab8a1630319
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/MacStream.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/MacStream.cs
new file mode 100644
index 00000000..b11fc1f6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/MacStream.cs
@@ -0,0 +1,154 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.IO
+{
+ public class MacStream
+ : Stream
+ {
+ protected readonly Stream stream;
+ protected readonly IMac inMac;
+ protected readonly IMac outMac;
+
+ public MacStream(
+ Stream stream,
+ IMac readMac,
+ IMac writeMac)
+ {
+ this.stream = stream;
+ this.inMac = readMac;
+ this.outMac = writeMac;
+ }
+
+ public virtual IMac ReadMac()
+ {
+ return inMac;
+ }
+
+ public virtual IMac WriteMac()
+ {
+ return outMac;
+ }
+
+ public override int Read(
+ byte[] buffer,
+ int offset,
+ int count)
+ {
+ int n = stream.Read(buffer, offset, count);
+ if (inMac != null)
+ {
+ if (n > 0)
+ {
+ inMac.BlockUpdate(buffer, offset, n);
+ }
+ }
+ return n;
+ }
+
+ public override int ReadByte()
+ {
+ int b = stream.ReadByte();
+ if (inMac != null)
+ {
+ if (b >= 0)
+ {
+ inMac.Update((byte)b);
+ }
+ }
+ return b;
+ }
+
+ public override void Write(
+ byte[] buffer,
+ int offset,
+ int count)
+ {
+ if (outMac != null)
+ {
+ if (count > 0)
+ {
+ outMac.BlockUpdate(buffer, offset, count);
+ }
+ }
+ stream.Write(buffer, offset, count);
+ }
+
+ public override void WriteByte(byte b)
+ {
+ if (outMac != null)
+ {
+ outMac.Update(b);
+ }
+ stream.WriteByte(b);
+ }
+
+ public override bool CanRead
+ {
+ get { return stream.CanRead; }
+ }
+
+ public override bool CanWrite
+ {
+ get { return stream.CanWrite; }
+ }
+
+ public override bool CanSeek
+ {
+ get { return stream.CanSeek; }
+ }
+
+ public override long Length
+ {
+ get { return stream.Length; }
+ }
+
+ public override long Position
+ {
+ get { return stream.Position; }
+ set { stream.Position = value; }
+ }
+
+#if PORTABLE || NETFX_CORE
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(stream);
+ }
+ base.Dispose(disposing);
+ }
+#else
+ public override void Close()
+ {
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(stream);
+ base.Close();
+ }
+#endif
+
+ public override void Flush()
+ {
+ stream.Flush();
+ }
+
+ public override long Seek(
+ long offset,
+ SeekOrigin origin)
+ {
+ return stream.Seek(offset,origin);
+ }
+
+ public override void SetLength(
+ long length)
+ {
+ stream.SetLength(length);
+ }
+ }
+}
+
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/MacStream.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/MacStream.cs.meta
new file mode 100644
index 00000000..9ac7a7b9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/MacStream.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 89f7b5360e5fde147bf149b2788714da
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/SignerSink.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/SignerSink.cs
new file mode 100644
index 00000000..2f6b2866
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/SignerSink.cs
@@ -0,0 +1,39 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.IO
+{
+ public class SignerSink
+ : BaseOutputStream
+ {
+ private readonly ISigner mSigner;
+
+ public SignerSink(ISigner signer)
+ {
+ this.mSigner = signer;
+ }
+
+ public virtual ISigner Signer
+ {
+ get { return mSigner; }
+ }
+
+ public override void WriteByte(byte b)
+ {
+ mSigner.Update(b);
+ }
+
+ public override void Write(byte[] buf, int off, int len)
+ {
+ if (len > 0)
+ {
+ mSigner.BlockUpdate(buf, off, len);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/SignerSink.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/SignerSink.cs.meta
new file mode 100644
index 00000000..3f353298
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/SignerSink.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 23cf4ec0649ecd8418e9723ca65f3bdd
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/SignerStream.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/SignerStream.cs
new file mode 100644
index 00000000..3d3ea750
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/SignerStream.cs
@@ -0,0 +1,155 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.IO
+{
+ public class SignerStream
+ : Stream
+ {
+ protected readonly Stream stream;
+ protected readonly ISigner inSigner;
+ protected readonly ISigner outSigner;
+
+ public SignerStream(
+ Stream stream,
+ ISigner readSigner,
+ ISigner writeSigner)
+ {
+ this.stream = stream;
+ this.inSigner = readSigner;
+ this.outSigner = writeSigner;
+ }
+
+ public virtual ISigner ReadSigner()
+ {
+ return inSigner;
+ }
+
+ public virtual ISigner WriteSigner()
+ {
+ return outSigner;
+ }
+
+ public override int Read(
+ byte[] buffer,
+ int offset,
+ int count)
+ {
+ int n = stream.Read(buffer, offset, count);
+ if (inSigner != null)
+ {
+ if (n > 0)
+ {
+ inSigner.BlockUpdate(buffer, offset, n);
+ }
+ }
+ return n;
+ }
+
+ public override int ReadByte()
+ {
+ int b = stream.ReadByte();
+ if (inSigner != null)
+ {
+ if (b >= 0)
+ {
+ inSigner.Update((byte)b);
+ }
+ }
+ return b;
+ }
+
+ public override void Write(
+ byte[] buffer,
+ int offset,
+ int count)
+ {
+ if (outSigner != null)
+ {
+ if (count > 0)
+ {
+ outSigner.BlockUpdate(buffer, offset, count);
+ }
+ }
+ stream.Write(buffer, offset, count);
+ }
+
+ public override void WriteByte(
+ byte b)
+ {
+ if (outSigner != null)
+ {
+ outSigner.Update(b);
+ }
+ stream.WriteByte(b);
+ }
+
+ public override bool CanRead
+ {
+ get { return stream.CanRead; }
+ }
+
+ public override bool CanWrite
+ {
+ get { return stream.CanWrite; }
+ }
+
+ public override bool CanSeek
+ {
+ get { return stream.CanSeek; }
+ }
+
+ public override long Length
+ {
+ get { return stream.Length; }
+ }
+
+ public override long Position
+ {
+ get { return stream.Position; }
+ set { stream.Position = value; }
+ }
+
+#if PORTABLE || NETFX_CORE
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(stream);
+ }
+ base.Dispose(disposing);
+ }
+#else
+ public override void Close()
+ {
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(stream);
+ base.Close();
+ }
+#endif
+
+ public override void Flush()
+ {
+ stream.Flush();
+ }
+
+ public override long Seek(
+ long offset,
+ SeekOrigin origin)
+ {
+ return stream.Seek(offset, origin);
+ }
+
+ public override void SetLength(
+ long length)
+ {
+ stream.SetLength(length);
+ }
+ }
+}
+
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/SignerStream.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/SignerStream.cs.meta
new file mode 100644
index 00000000..71b5e1af
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/io/SignerStream.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 1e402c2b637c2e546a7ac4336b548998
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs.meta
new file mode 100644
index 00000000..f3ebb3bc
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 3d929d360f5bba5429128c0fce7c78e9
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/CMac.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/CMac.cs
new file mode 100644
index 00000000..10c19f21
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/CMac.cs
@@ -0,0 +1,261 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Paddings;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs
+{
+ /**
+ * CMAC - as specified at www.nuee.nagoya-u.ac.jp/labs/tiwata/omac/omac.html
+ *
+ * CMAC is analogous to OMAC1 - see also en.wikipedia.org/wiki/CMAC
+ *
+ * CMAC is a NIST recomendation - see
+ * csrc.nist.gov/CryptoToolkit/modes/800-38_Series_Publications/SP800-38B.pdf
+ *
+ * CMAC/OMAC1 is a blockcipher-based message authentication code designed and
+ * analyzed by Tetsu Iwata and Kaoru Kurosawa.
+ *
+ * CMAC/OMAC1 is a simple variant of the CBC MAC (Cipher Block Chaining Message
+ * Authentication Code). OMAC stands for One-Key CBC MAC.
+ *
+ * It supports 128- or 64-bits block ciphers, with any key size, and returns
+ * a MAC with dimension less or equal to the block size of the underlying
+ * cipher.
+ *
+ */
+ public class CMac
+ : IMac
+ {
+ private const byte CONSTANT_128 = (byte)0x87;
+ private const byte CONSTANT_64 = (byte)0x1b;
+
+ private byte[] ZEROES;
+
+ private byte[] mac;
+
+ private byte[] buf;
+ private int bufOff;
+ private IBlockCipher cipher;
+
+ private int macSize;
+
+ private byte[] L, Lu, Lu2;
+
+ /**
+ * create a standard MAC based on a CBC block cipher (64 or 128 bit block).
+ * This will produce an authentication code the length of the block size
+ * of the cipher.
+ *
+ * @param cipher the cipher to be used as the basis of the MAC generation.
+ */
+ public CMac(
+ IBlockCipher cipher)
+ : this(cipher, cipher.GetBlockSize() * 8)
+ {
+ }
+
+ /**
+ * create a standard MAC based on a block cipher with the size of the
+ * MAC been given in bits.
+ *
+ * Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
+ * or 16 bits if being used as a data authenticator (FIPS Publication 113),
+ * and in general should be less than the size of the block cipher as it reduces
+ * the chance of an exhaustive attack (see Handbook of Applied Cryptography).
+ *
+ * @param cipher the cipher to be used as the basis of the MAC generation.
+ * @param macSizeInBits the size of the MAC in bits, must be a multiple of 8 and @lt;= 128.
+ */
+ public CMac(
+ IBlockCipher cipher,
+ int macSizeInBits)
+ {
+ if ((macSizeInBits % 8) != 0)
+ throw new ArgumentException("MAC size must be multiple of 8");
+
+ if (macSizeInBits > (cipher.GetBlockSize() * 8))
+ {
+ throw new ArgumentException(
+ "MAC size must be less or equal to "
+ + (cipher.GetBlockSize() * 8));
+ }
+
+ if (cipher.GetBlockSize() != 8 && cipher.GetBlockSize() != 16)
+ {
+ throw new ArgumentException(
+ "Block size must be either 64 or 128 bits");
+ }
+
+ this.cipher = new CbcBlockCipher(cipher);
+ this.macSize = macSizeInBits / 8;
+
+ mac = new byte[cipher.GetBlockSize()];
+
+ buf = new byte[cipher.GetBlockSize()];
+
+ ZEROES = new byte[cipher.GetBlockSize()];
+
+ bufOff = 0;
+ }
+
+ public string AlgorithmName
+ {
+ get { return cipher.AlgorithmName; }
+ }
+
+ private static int ShiftLeft(byte[] block, byte[] output)
+ {
+ int i = block.Length;
+ uint bit = 0;
+ while (--i >= 0)
+ {
+ uint b = block[i];
+ output[i] = (byte)((b << 1) | bit);
+ bit = (b >> 7) & 1;
+ }
+ return (int)bit;
+ }
+
+ private static byte[] DoubleLu(byte[] input)
+ {
+ byte[] ret = new byte[input.Length];
+ int carry = ShiftLeft(input, ret);
+ int xor = input.Length == 16 ? CONSTANT_128 : CONSTANT_64;
+
+ /*
+ * NOTE: This construction is an attempt at a constant-time implementation.
+ */
+ ret[input.Length - 1] ^= (byte)(xor >> ((1 - carry) << 3));
+
+ return ret;
+ }
+
+ public void Init(
+ ICipherParameters parameters)
+ {
+ if (parameters is KeyParameter)
+ {
+ cipher.Init(true, parameters);
+
+ //initializes the L, Lu, Lu2 numbers
+ L = new byte[ZEROES.Length];
+ cipher.ProcessBlock(ZEROES, 0, L, 0);
+ Lu = DoubleLu(L);
+ Lu2 = DoubleLu(Lu);
+ }
+ else if (parameters != null)
+ {
+ // CMAC mode does not permit IV to underlying CBC mode
+ throw new ArgumentException("CMac mode only permits key to be set.", "parameters");
+ }
+
+ Reset();
+ }
+
+ public int GetMacSize()
+ {
+ return macSize;
+ }
+
+ public void Update(
+ byte input)
+ {
+ if (bufOff == buf.Length)
+ {
+ cipher.ProcessBlock(buf, 0, mac, 0);
+ bufOff = 0;
+ }
+
+ buf[bufOff++] = input;
+ }
+
+ public void BlockUpdate(
+ byte[] inBytes,
+ int inOff,
+ int len)
+ {
+ if (len < 0)
+ throw new ArgumentException("Can't have a negative input length!");
+
+ int blockSize = cipher.GetBlockSize();
+ int gapLen = blockSize - bufOff;
+
+ if (len > gapLen)
+ {
+ Array.Copy(inBytes, inOff, buf, bufOff, gapLen);
+
+ cipher.ProcessBlock(buf, 0, mac, 0);
+
+ bufOff = 0;
+ len -= gapLen;
+ inOff += gapLen;
+
+ while (len > blockSize)
+ {
+ cipher.ProcessBlock(inBytes, inOff, mac, 0);
+
+ len -= blockSize;
+ inOff += blockSize;
+ }
+ }
+
+ Array.Copy(inBytes, inOff, buf, bufOff, len);
+
+ bufOff += len;
+ }
+
+ public int DoFinal(
+ byte[] outBytes,
+ int outOff)
+ {
+ int blockSize = cipher.GetBlockSize();
+
+ byte[] lu;
+ if (bufOff == blockSize)
+ {
+ lu = Lu;
+ }
+ else
+ {
+ new ISO7816d4Padding().AddPadding(buf, bufOff);
+ lu = Lu2;
+ }
+
+ for (int i = 0; i < mac.Length; i++)
+ {
+ buf[i] ^= lu[i];
+ }
+
+ cipher.ProcessBlock(buf, 0, mac, 0);
+
+ Array.Copy(mac, 0, outBytes, outOff, macSize);
+
+ Reset();
+
+ return macSize;
+ }
+
+ /**
+ * Reset the mac generator.
+ */
+ public void Reset()
+ {
+ /*
+ * clean the buffer.
+ */
+ Array.Clear(buf, 0, buf.Length);
+ bufOff = 0;
+
+ /*
+ * Reset the underlying cipher.
+ */
+ cipher.Reset();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/CMac.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/CMac.cs.meta
new file mode 100644
index 00000000..7f4f2d55
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/CMac.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 147ba6faf8894394bb4ede3ad60aa6ca
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/CbcBlockCipherMac.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/CbcBlockCipherMac.cs
new file mode 100644
index 00000000..1b0c82cf
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/CbcBlockCipherMac.cs
@@ -0,0 +1,213 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Paddings;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs
+{
+ /**
+ * standard CBC Block Cipher MAC - if no padding is specified the default of
+ * pad of zeroes is used.
+ */
+ public class CbcBlockCipherMac
+ : IMac
+ {
+ private byte[] buf;
+ private int bufOff;
+ private IBlockCipher cipher;
+ private IBlockCipherPadding padding;
+ private int macSize;
+
+ /**
+ * create a standard MAC based on a CBC block cipher. This will produce an
+ * authentication code half the length of the block size of the cipher.
+ *
+ * @param cipher the cipher to be used as the basis of the MAC generation.
+ */
+ public CbcBlockCipherMac(
+ IBlockCipher cipher)
+ : this(cipher, (cipher.GetBlockSize() * 8) / 2, null)
+ {
+ }
+
+ /**
+ * create a standard MAC based on a CBC block cipher. This will produce an
+ * authentication code half the length of the block size of the cipher.
+ *
+ * @param cipher the cipher to be used as the basis of the MAC generation.
+ * @param padding the padding to be used to complete the last block.
+ */
+ public CbcBlockCipherMac(
+ IBlockCipher cipher,
+ IBlockCipherPadding padding)
+ : this(cipher, (cipher.GetBlockSize() * 8) / 2, padding)
+ {
+ }
+
+ /**
+ * create a standard MAC based on a block cipher with the size of the
+ * MAC been given in bits. This class uses CBC mode as the basis for the
+ * MAC generation.
+ *
+ * Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
+ * or 16 bits if being used as a data authenticator (FIPS Publication 113),
+ * and in general should be less than the size of the block cipher as it reduces
+ * the chance of an exhaustive attack (see Handbook of Applied Cryptography).
+ *
+ * @param cipher the cipher to be used as the basis of the MAC generation.
+ * @param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
+ */
+ public CbcBlockCipherMac(
+ IBlockCipher cipher,
+ int macSizeInBits)
+ : this(cipher, macSizeInBits, null)
+ {
+ }
+
+ /**
+ * create a standard MAC based on a block cipher with the size of the
+ * MAC been given in bits. This class uses CBC mode as the basis for the
+ * MAC generation.
+ *
+ * Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
+ * or 16 bits if being used as a data authenticator (FIPS Publication 113),
+ * and in general should be less than the size of the block cipher as it reduces
+ * the chance of an exhaustive attack (see Handbook of Applied Cryptography).
+ *
+ * @param cipher the cipher to be used as the basis of the MAC generation.
+ * @param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
+ * @param padding the padding to be used to complete the last block.
+ */
+ public CbcBlockCipherMac(
+ IBlockCipher cipher,
+ int macSizeInBits,
+ IBlockCipherPadding padding)
+ {
+ if ((macSizeInBits % 8) != 0)
+ throw new ArgumentException("MAC size must be multiple of 8");
+
+ this.cipher = new CbcBlockCipher(cipher);
+ this.padding = padding;
+ this.macSize = macSizeInBits / 8;
+
+ buf = new byte[cipher.GetBlockSize()];
+ bufOff = 0;
+ }
+
+ public string AlgorithmName
+ {
+ get { return cipher.AlgorithmName; }
+ }
+
+ public void Init(
+ ICipherParameters parameters)
+ {
+ Reset();
+
+ cipher.Init(true, parameters);
+ }
+
+ public int GetMacSize()
+ {
+ return macSize;
+ }
+
+ public void Update(
+ byte input)
+ {
+ if (bufOff == buf.Length)
+ {
+ cipher.ProcessBlock(buf, 0, buf, 0);
+ bufOff = 0;
+ }
+
+ buf[bufOff++] = input;
+ }
+
+ public void BlockUpdate(
+ byte[] input,
+ int inOff,
+ int len)
+ {
+ if (len < 0)
+ throw new ArgumentException("Can't have a negative input length!");
+
+ int blockSize = cipher.GetBlockSize();
+ int gapLen = blockSize - bufOff;
+
+ if (len > gapLen)
+ {
+ Array.Copy(input, inOff, buf, bufOff, gapLen);
+
+ cipher.ProcessBlock(buf, 0, buf, 0);
+
+ bufOff = 0;
+ len -= gapLen;
+ inOff += gapLen;
+
+ while (len > blockSize)
+ {
+ cipher.ProcessBlock(input, inOff, buf, 0);
+
+ len -= blockSize;
+ inOff += blockSize;
+ }
+ }
+
+ Array.Copy(input, inOff, buf, bufOff, len);
+
+ bufOff += len;
+ }
+
+ public int DoFinal(
+ byte[] output,
+ int outOff)
+ {
+ int blockSize = cipher.GetBlockSize();
+
+ if (padding == null)
+ {
+ // pad with zeroes
+ while (bufOff < blockSize)
+ {
+ buf[bufOff++] = 0;
+ }
+ }
+ else
+ {
+ if (bufOff == blockSize)
+ {
+ cipher.ProcessBlock(buf, 0, buf, 0);
+ bufOff = 0;
+ }
+
+ padding.AddPadding(buf, bufOff);
+ }
+
+ cipher.ProcessBlock(buf, 0, buf, 0);
+
+ Array.Copy(buf, 0, output, outOff, macSize);
+
+ Reset();
+
+ return macSize;
+ }
+
+ /**
+ * Reset the mac generator.
+ */
+ public void Reset()
+ {
+ // Clear the buffer.
+ Array.Clear(buf, 0, buf.Length);
+ bufOff = 0;
+
+ // Reset the underlying cipher.
+ cipher.Reset();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/CbcBlockCipherMac.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/CbcBlockCipherMac.cs.meta
new file mode 100644
index 00000000..8babb16c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/CbcBlockCipherMac.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 85bfc6f3c7c846946b5e385bca692356
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/CfbBlockCipherMac.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/CfbBlockCipherMac.cs
new file mode 100644
index 00000000..9bfa80b6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/CfbBlockCipherMac.cs
@@ -0,0 +1,372 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Paddings;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs
+{
+ /**
+ * implements a Cipher-FeedBack (CFB) mode on top of a simple cipher.
+ */
+ class MacCFBBlockCipher
+ : IBlockCipher
+ {
+ private byte[] IV;
+ private byte[] cfbV;
+ private byte[] cfbOutV;
+
+ private readonly int blockSize;
+ private readonly IBlockCipher cipher;
+
+ /**
+ * Basic constructor.
+ *
+ * @param cipher the block cipher to be used as the basis of the
+ * feedback mode.
+ * @param blockSize the block size in bits (note: a multiple of 8)
+ */
+ public MacCFBBlockCipher(
+ IBlockCipher cipher,
+ int bitBlockSize)
+ {
+ this.cipher = cipher;
+ this.blockSize = bitBlockSize / 8;
+
+ this.IV = new byte[cipher.GetBlockSize()];
+ this.cfbV = new byte[cipher.GetBlockSize()];
+ this.cfbOutV = new byte[cipher.GetBlockSize()];
+ }
+
+ /**
+ * Initialise the cipher and, possibly, the initialisation vector (IV).
+ * If an IV isn't passed as part of the parameter, the IV will be all zeros.
+ * An IV which is too short is handled in FIPS compliant fashion.
+ *
+ * @param param the key and other data required by the cipher.
+ * @exception ArgumentException if the parameters argument is
+ * inappropriate.
+ */
+ public void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ if (parameters is ParametersWithIV)
+ {
+ ParametersWithIV ivParam = (ParametersWithIV)parameters;
+ byte[] iv = ivParam.GetIV();
+
+ if (iv.Length < IV.Length)
+ {
+ Array.Copy(iv, 0, IV, IV.Length - iv.Length, iv.Length);
+ }
+ else
+ {
+ Array.Copy(iv, 0, IV, 0, IV.Length);
+ }
+
+ parameters = ivParam.Parameters;
+ }
+
+ Reset();
+
+ cipher.Init(true, parameters);
+ }
+
+ /**
+ * return the algorithm name and mode.
+ *
+ * @return the name of the underlying algorithm followed by "/CFB"
+ * and the block size in bits.
+ */
+ public string AlgorithmName
+ {
+ get { return cipher.AlgorithmName + "/CFB" + (blockSize * 8); }
+ }
+
+ public bool IsPartialBlockOkay
+ {
+ get { return true; }
+ }
+
+ /**
+ * return the block size we are operating at.
+ *
+ * @return the block size we are operating at (in bytes).
+ */
+ public int GetBlockSize()
+ {
+ return blockSize;
+ }
+
+ /**
+ * Process one block of input from the array in and write it to
+ * the out array.
+ *
+ * @param in the array containing the input data.
+ * @param inOff offset into the in array the data starts at.
+ * @param out the array the output data will be copied into.
+ * @param outOff the offset into the out array the output will start at.
+ * @exception DataLengthException if there isn't enough data in in, or
+ * space in out.
+ * @exception InvalidOperationException if the cipher isn't initialised.
+ * @return the number of bytes processed and produced.
+ */
+ public int ProcessBlock(
+ byte[] input,
+ int inOff,
+ byte[] outBytes,
+ int outOff)
+ {
+ if ((inOff + blockSize) > input.Length)
+ throw new DataLengthException("input buffer too short");
+
+ if ((outOff + blockSize) > outBytes.Length)
+ throw new DataLengthException("output buffer too short");
+
+ cipher.ProcessBlock(cfbV, 0, cfbOutV, 0);
+
+ //
+ // XOR the cfbV with the plaintext producing the cipher text
+ //
+ for (int i = 0; i < blockSize; i++)
+ {
+ outBytes[outOff + i] = (byte)(cfbOutV[i] ^ input[inOff + i]);
+ }
+
+ //
+ // change over the input block.
+ //
+ Array.Copy(cfbV, blockSize, cfbV, 0, cfbV.Length - blockSize);
+ Array.Copy(outBytes, outOff, cfbV, cfbV.Length - blockSize, blockSize);
+
+ return blockSize;
+ }
+
+ /**
+ * reset the chaining vector back to the IV and reset the underlying
+ * cipher.
+ */
+ public void Reset()
+ {
+ IV.CopyTo(cfbV, 0);
+
+ cipher.Reset();
+ }
+
+ public void GetMacBlock(
+ byte[] mac)
+ {
+ cipher.ProcessBlock(cfbV, 0, mac, 0);
+ }
+ }
+
+ public class CfbBlockCipherMac
+ : IMac
+ {
+ private byte[] mac;
+ private byte[] Buffer;
+ private int bufOff;
+ private MacCFBBlockCipher cipher;
+ private IBlockCipherPadding padding;
+ private int macSize;
+
+ /**
+ * create a standard MAC based on a CFB block cipher. This will produce an
+ * authentication code half the length of the block size of the cipher, with
+ * the CFB mode set to 8 bits.
+ *
+ * @param cipher the cipher to be used as the basis of the MAC generation.
+ */
+ public CfbBlockCipherMac(
+ IBlockCipher cipher)
+ : this(cipher, 8, (cipher.GetBlockSize() * 8) / 2, null)
+ {
+ }
+
+ /**
+ * create a standard MAC based on a CFB block cipher. This will produce an
+ * authentication code half the length of the block size of the cipher, with
+ * the CFB mode set to 8 bits.
+ *
+ * @param cipher the cipher to be used as the basis of the MAC generation.
+ * @param padding the padding to be used.
+ */
+ public CfbBlockCipherMac(
+ IBlockCipher cipher,
+ IBlockCipherPadding padding)
+ : this(cipher, 8, (cipher.GetBlockSize() * 8) / 2, padding)
+ {
+ }
+
+ /**
+ * create a standard MAC based on a block cipher with the size of the
+ * MAC been given in bits. This class uses CFB mode as the basis for the
+ * MAC generation.
+ *
+ * Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
+ * or 16 bits if being used as a data authenticator (FIPS Publication 113),
+ * and in general should be less than the size of the block cipher as it reduces
+ * the chance of an exhaustive attack (see Handbook of Applied Cryptography).
+ *
+ * @param cipher the cipher to be used as the basis of the MAC generation.
+ * @param cfbBitSize the size of an output block produced by the CFB mode.
+ * @param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
+ */
+ public CfbBlockCipherMac(
+ IBlockCipher cipher,
+ int cfbBitSize,
+ int macSizeInBits)
+ : this(cipher, cfbBitSize, macSizeInBits, null)
+ {
+ }
+
+ /**
+ * create a standard MAC based on a block cipher with the size of the
+ * MAC been given in bits. This class uses CFB mode as the basis for the
+ * MAC generation.
+ *
+ * Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
+ * or 16 bits if being used as a data authenticator (FIPS Publication 113),
+ * and in general should be less than the size of the block cipher as it reduces
+ * the chance of an exhaustive attack (see Handbook of Applied Cryptography).
+ *
+ * @param cipher the cipher to be used as the basis of the MAC generation.
+ * @param cfbBitSize the size of an output block produced by the CFB mode.
+ * @param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
+ * @param padding a padding to be used.
+ */
+ public CfbBlockCipherMac(
+ IBlockCipher cipher,
+ int cfbBitSize,
+ int macSizeInBits,
+ IBlockCipherPadding padding)
+ {
+ if ((macSizeInBits % 8) != 0)
+ throw new ArgumentException("MAC size must be multiple of 8");
+
+ mac = new byte[cipher.GetBlockSize()];
+
+ this.cipher = new MacCFBBlockCipher(cipher, cfbBitSize);
+ this.padding = padding;
+ this.macSize = macSizeInBits / 8;
+
+ Buffer = new byte[this.cipher.GetBlockSize()];
+ bufOff = 0;
+ }
+
+ public string AlgorithmName
+ {
+ get { return cipher.AlgorithmName; }
+ }
+
+ public void Init(
+ ICipherParameters parameters)
+ {
+ Reset();
+
+ cipher.Init(true, parameters);
+ }
+
+ public int GetMacSize()
+ {
+ return macSize;
+ }
+
+ public void Update(
+ byte input)
+ {
+ if (bufOff == Buffer.Length)
+ {
+ cipher.ProcessBlock(Buffer, 0, mac, 0);
+ bufOff = 0;
+ }
+
+ Buffer[bufOff++] = input;
+ }
+
+ public void BlockUpdate(
+ byte[] input,
+ int inOff,
+ int len)
+ {
+ if (len < 0)
+ throw new ArgumentException("Can't have a negative input length!");
+
+ int blockSize = cipher.GetBlockSize();
+ int resultLen = 0;
+ int gapLen = blockSize - bufOff;
+
+ if (len > gapLen)
+ {
+ Array.Copy(input, inOff, Buffer, bufOff, gapLen);
+
+ resultLen += cipher.ProcessBlock(Buffer, 0, mac, 0);
+
+ bufOff = 0;
+ len -= gapLen;
+ inOff += gapLen;
+
+ while (len > blockSize)
+ {
+ resultLen += cipher.ProcessBlock(input, inOff, mac, 0);
+
+ len -= blockSize;
+ inOff += blockSize;
+ }
+ }
+
+ Array.Copy(input, inOff, Buffer, bufOff, len);
+
+ bufOff += len;
+ }
+
+ public int DoFinal(
+ byte[] output,
+ int outOff)
+ {
+ int blockSize = cipher.GetBlockSize();
+
+ // pad with zeroes
+ if (this.padding == null)
+ {
+ while (bufOff < blockSize)
+ {
+ Buffer[bufOff++] = 0;
+ }
+ }
+ else
+ {
+ padding.AddPadding(Buffer, bufOff);
+ }
+
+ cipher.ProcessBlock(Buffer, 0, mac, 0);
+
+ cipher.GetMacBlock(mac);
+
+ Array.Copy(mac, 0, output, outOff, macSize);
+
+ Reset();
+
+ return macSize;
+ }
+
+ /**
+ * Reset the mac generator.
+ */
+ public void Reset()
+ {
+ // Clear the buffer.
+ Array.Clear(Buffer, 0, Buffer.Length);
+ bufOff = 0;
+
+ // Reset the underlying cipher.
+ cipher.Reset();
+ }
+ }
+
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/CfbBlockCipherMac.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/CfbBlockCipherMac.cs.meta
new file mode 100644
index 00000000..3baab491
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/CfbBlockCipherMac.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 3fc42df051ecc104680ab4efa67051c1
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/DSTU7564Mac.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/DSTU7564Mac.cs
new file mode 100644
index 00000000..0041617d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/DSTU7564Mac.cs
@@ -0,0 +1,147 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs
+{
+ ///
+ /// Implementation of DSTU7564 mac mode
+ ///
+ public class Dstu7564Mac
+ : IMac
+ {
+ private Dstu7564Digest engine;
+ private int macSize;
+
+ private ulong inputLength;
+
+ byte[] paddedKey;
+ byte[] invertedKey;
+
+ public string AlgorithmName
+ {
+ get { return "DSTU7564Mac"; }
+ }
+
+ public Dstu7564Mac(int macSizeBits)
+ {
+ engine = new Dstu7564Digest(macSizeBits);
+ macSize = macSizeBits / 8;
+ }
+
+ public void Init(ICipherParameters parameters)
+ {
+ if (parameters is KeyParameter)
+ {
+ byte[] key = ((KeyParameter)parameters).GetKey();
+
+ invertedKey = new byte[key.Length];
+
+ paddedKey = PadKey(key);
+
+ for (int byteIndex = 0; byteIndex < invertedKey.Length; byteIndex++)
+ {
+ invertedKey[byteIndex] = (byte)(key[byteIndex] ^ (byte)0xFF);
+ }
+ }
+ else
+ {
+ throw new ArgumentException("Bad parameter passed");
+ }
+
+ engine.BlockUpdate(paddedKey, 0, paddedKey.Length);
+ }
+
+ public int GetMacSize()
+ {
+ return macSize;
+ }
+
+ public void BlockUpdate(byte[] input, int inOff, int len)
+ {
+ Check.DataLength(input, inOff, len, "Input buffer too short");
+
+ if (paddedKey == null)
+ throw new InvalidOperationException(AlgorithmName + " not initialised");
+
+ engine.BlockUpdate(input, inOff, len);
+ inputLength += (ulong)len;
+ }
+
+ public void Update(byte input)
+ {
+ engine.Update(input);
+ inputLength++;
+ }
+
+ public int DoFinal(byte[] output, int outOff)
+ {
+ Check.OutputLength(output, outOff, macSize, "Output buffer too short");
+
+ if (paddedKey == null)
+ throw new InvalidOperationException(AlgorithmName + " not initialised");
+
+ Pad();
+
+ engine.BlockUpdate(invertedKey, 0, invertedKey.Length);
+
+ inputLength = 0;
+
+ return engine.DoFinal(output, outOff);
+ }
+
+ public void Reset()
+ {
+ inputLength = 0;
+ engine.Reset();
+ if (paddedKey != null)
+ {
+ engine.BlockUpdate(paddedKey, 0, paddedKey.Length);
+ }
+ }
+
+ private void Pad()
+ {
+ int extra = engine.GetByteLength() - (int)(inputLength % (ulong)engine.GetByteLength());
+ if (extra < 13) // terminator byte + 96 bits of length
+ {
+ extra += engine.GetByteLength();
+ }
+
+ byte[] padded = new byte[extra];
+
+ padded[0] = (byte)0x80; // Defined in standard;
+
+ // Defined in standard;
+ Pack.UInt64_To_LE(inputLength * 8, padded, padded.Length - 12);
+
+ engine.BlockUpdate(padded, 0, padded.Length);
+ }
+
+ private byte[] PadKey(byte[] input)
+ {
+ int paddedLen = ((input.Length + engine.GetByteLength() - 1) / engine.GetByteLength()) * engine.GetByteLength();
+
+ int extra = engine.GetByteLength() - (int)(input.Length % engine.GetByteLength());
+ if (extra < 13) // terminator byte + 96 bits of length
+ {
+ paddedLen += engine.GetByteLength();
+ }
+
+ byte[] padded = new byte[paddedLen];
+
+ Array.Copy(input, 0, padded, 0, input.Length);
+
+ padded[input.Length] = (byte)0x80; // Defined in standard;
+ Pack.UInt32_To_LE((uint)(input.Length * 8), padded, padded.Length - 12); // Defined in standard;
+
+ return padded;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/DSTU7564Mac.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/DSTU7564Mac.cs.meta
new file mode 100644
index 00000000..11c3be29
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/DSTU7564Mac.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: f3df87f14e95d97499b6682f752537fd
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/DSTU7624Mac.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/DSTU7624Mac.cs
new file mode 100644
index 00000000..af26c5d0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/DSTU7624Mac.cs
@@ -0,0 +1,164 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs
+{
+ /**
+ * implementation of DSTU 7624 MAC
+ */
+ public class Dstu7624Mac : IMac
+ {
+ private int macSize;
+
+ private Dstu7624Engine engine;
+ private int blockSize;
+
+ private byte[] c, cTemp, kDelta;
+ private byte[] buf;
+ private int bufOff;
+
+ public Dstu7624Mac(int blockSizeBits, int q)
+ {
+ engine = new Dstu7624Engine(blockSizeBits);
+
+ blockSize = blockSizeBits / 8;
+
+ macSize = q / 8;
+
+ c = new byte[blockSize];
+
+ cTemp = new byte[blockSize];
+
+ kDelta = new byte[blockSize];
+ buf = new byte[blockSize];
+ }
+
+ public void Init(ICipherParameters parameters)
+ {
+ if (parameters is KeyParameter)
+ {
+ engine.Init(true, (KeyParameter)parameters);
+
+ engine.ProcessBlock(kDelta, 0, kDelta, 0);
+ }
+ else
+ {
+ throw new ArgumentException("invalid parameter passed to Dstu7624Mac init - "
+ + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters));
+ }
+ }
+
+ public string AlgorithmName
+ {
+ get { return "Dstu7624Mac"; }
+ }
+
+ public int GetMacSize()
+ {
+ return macSize;
+ }
+
+ public void Update(byte input)
+ {
+ if (bufOff == buf.Length)
+ {
+ processBlock(buf, 0);
+ bufOff = 0;
+ }
+
+ buf[bufOff++] = input;
+ }
+
+ public void BlockUpdate(byte[] input, int inOff, int len)
+ {
+ if (len < 0)
+ {
+ throw new ArgumentException(
+ "Can't have a negative input length!");
+ }
+
+ int blockSize = engine.GetBlockSize();
+ int gapLen = blockSize - bufOff;
+
+ if (len > gapLen)
+ {
+ Array.Copy(input, inOff, buf, bufOff, gapLen);
+
+ processBlock(buf, 0);
+
+ bufOff = 0;
+ len -= gapLen;
+ inOff += gapLen;
+
+ while (len > blockSize)
+ {
+ processBlock(input, inOff);
+
+ len -= blockSize;
+ inOff += blockSize;
+ }
+ }
+
+ Array.Copy(input, inOff, buf, bufOff, len);
+
+ bufOff += len;
+ }
+
+ private void processBlock(byte[] input, int inOff)
+ {
+ Xor(c, 0, input, inOff, cTemp);
+
+ engine.ProcessBlock(cTemp, 0, c, 0);
+ }
+
+ private void Xor(byte[] c, int cOff, byte[] input, int inOff, byte[] xorResult)
+ {
+ for (int byteIndex = 0; byteIndex < blockSize; byteIndex++)
+ {
+ xorResult[byteIndex] = (byte)(c[byteIndex + cOff] ^ input[byteIndex + inOff]);
+ }
+ }
+
+ public int DoFinal(byte[] output, int outOff)
+ {
+ if (bufOff % buf.Length != 0)
+ {
+ throw new DataLengthException("Input must be a multiple of blocksize");
+ }
+
+ //Last block
+ Xor(c, 0, buf, 0, cTemp);
+ Xor(cTemp, 0, kDelta, 0, c);
+ engine.ProcessBlock(c, 0, c, 0);
+
+ if (macSize + outOff > output.Length)
+ {
+ throw new DataLengthException("Output buffer too short");
+ }
+
+ Array.Copy(c, 0, output, outOff, macSize);
+
+ return macSize;
+ }
+
+ public void Reset()
+ {
+ Arrays.Fill(c, (byte)0x00);
+ Arrays.Fill(cTemp, (byte)0x00);
+ Arrays.Fill(kDelta, (byte)0x00);
+ Arrays.Fill(buf, (byte)0x00);
+ engine.Reset();
+ engine.ProcessBlock(kDelta, 0, kDelta, 0);
+ bufOff = 0;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/DSTU7624Mac.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/DSTU7624Mac.cs.meta
new file mode 100644
index 00000000..f5044f25
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/DSTU7624Mac.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 1ef86dfb559e6e34c97d13a961c01118
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/GMac.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/GMac.cs
new file mode 100644
index 00000000..ba0389c0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/GMac.cs
@@ -0,0 +1,116 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs
+{
+ ///
+ /// The GMAC specialisation of Galois/Counter mode (GCM) detailed in NIST Special Publication
+ /// 800-38D.
+ ///
+ ///
+ /// GMac is an invocation of the GCM mode where no data is encrypted (i.e. all input data to the Mac
+ /// is processed as additional authenticated data with the underlying GCM block cipher).
+ ///
+ public class GMac
+ : IMac
+ {
+ private readonly GcmBlockCipher cipher;
+ private readonly int macSizeBits;
+
+ ///
+ /// Creates a GMAC based on the operation of a block cipher in GCM mode.
+ ///
+ ///
+ /// This will produce an authentication code the length of the block size of the cipher.
+ ///
+ /// the cipher to be used in GCM mode to generate the MAC.
+ public GMac(GcmBlockCipher cipher)
+ : this(cipher, 128)
+ {
+ }
+
+ ///
+ /// Creates a GMAC based on the operation of a 128 bit block cipher in GCM mode.
+ ///
+ ///
+ /// This will produce an authentication code the length of the block size of the cipher.
+ ///
+ /// the cipher to be used in GCM mode to generate the MAC.
+ /// the mac size to generate, in bits. Must be a multiple of 8, between 32 and 128 (inclusive).
+ /// Sizes less than 96 are not recommended, but are supported for specialized applications.
+ public GMac(GcmBlockCipher cipher, int macSizeBits)
+ {
+ this.cipher = cipher;
+ this.macSizeBits = macSizeBits;
+ }
+
+ ///
+ /// Initialises the GMAC - requires a
+ /// providing a and a nonce.
+ ///
+ public void Init(ICipherParameters parameters)
+ {
+ if (parameters is ParametersWithIV)
+ {
+ ParametersWithIV param = (ParametersWithIV)parameters;
+
+ byte[] iv = param.GetIV();
+ KeyParameter keyParam = (KeyParameter)param.Parameters;
+
+ // GCM is always operated in encrypt mode to calculate MAC
+ cipher.Init(true, new AeadParameters(keyParam, macSizeBits, iv));
+ }
+ else
+ {
+ throw new ArgumentException("GMAC requires ParametersWithIV");
+ }
+ }
+
+ public string AlgorithmName
+ {
+ get { return cipher.GetUnderlyingCipher().AlgorithmName + "-GMAC"; }
+ }
+
+ public int GetMacSize()
+ {
+ return macSizeBits / 8;
+ }
+
+ public void Update(byte input)
+ {
+ cipher.ProcessAadByte(input);
+ }
+
+ public void BlockUpdate(byte[] input, int inOff, int len)
+ {
+ cipher.ProcessAadBytes(input, inOff, len);
+ }
+
+ public int DoFinal(byte[] output, int outOff)
+ {
+ try
+ {
+ return cipher.DoFinal(output, outOff);
+ }
+ catch (InvalidCipherTextException e)
+ {
+ // Impossible in encrypt mode
+ throw new InvalidOperationException(e.ToString());
+ }
+ }
+
+ public void Reset()
+ {
+ cipher.Reset();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/GMac.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/GMac.cs.meta
new file mode 100644
index 00000000..d9eaa7b9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/GMac.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ff10578c84beafb499d22468085654d4
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/GOST28147Mac.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/GOST28147Mac.cs
new file mode 100644
index 00000000..0d5adddd
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/GOST28147Mac.cs
@@ -0,0 +1,319 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs
+{
+ /**
+ * implementation of GOST 28147-89 MAC
+ */
+ public class Gost28147Mac : IMac
+ {
+ private const int blockSize = 8;
+ private const int macSize = 4;
+ private int bufOff;
+ private byte[] buf;
+ private byte[] mac;
+ private bool firstStep = true;
+ private int[] workingKey;
+ private byte[] macIV = null;
+
+ //
+ // This is default S-box - E_A.
+ private byte[] S =
+ {
+ 0x9,0x6,0x3,0x2,0x8,0xB,0x1,0x7,0xA,0x4,0xE,0xF,0xC,0x0,0xD,0x5,
+ 0x3,0x7,0xE,0x9,0x8,0xA,0xF,0x0,0x5,0x2,0x6,0xC,0xB,0x4,0xD,0x1,
+ 0xE,0x4,0x6,0x2,0xB,0x3,0xD,0x8,0xC,0xF,0x5,0xA,0x0,0x7,0x1,0x9,
+ 0xE,0x7,0xA,0xC,0xD,0x1,0x3,0x9,0x0,0x2,0xB,0x4,0xF,0x8,0x5,0x6,
+ 0xB,0x5,0x1,0x9,0x8,0xD,0xF,0x0,0xE,0x4,0x2,0x3,0xC,0x7,0xA,0x6,
+ 0x3,0xA,0xD,0xC,0x1,0x2,0x0,0xB,0x7,0x5,0x9,0x4,0x8,0xF,0xE,0x6,
+ 0x1,0xD,0x2,0x9,0x7,0xA,0x6,0x0,0x8,0xC,0x4,0x5,0xF,0x3,0xB,0xE,
+ 0xB,0xA,0xF,0x5,0x0,0xC,0xE,0x8,0x6,0x2,0x3,0x9,0x1,0x7,0xD,0x4
+ };
+
+ public Gost28147Mac()
+ {
+ mac = new byte[blockSize];
+ buf = new byte[blockSize];
+ bufOff = 0;
+ }
+
+ private static int[] GenerateWorkingKey(
+ byte[] userKey)
+ {
+ if (userKey.Length != 32)
+ throw new ArgumentException("Key length invalid. Key needs to be 32 byte - 256 bit!!!");
+
+ int[] key = new int[8];
+ for(int i=0; i!=8; i++)
+ {
+ key[i] = bytesToint(userKey,i*4);
+ }
+
+ return key;
+ }
+
+ public void Init(
+ ICipherParameters parameters)
+ {
+ Reset();
+ buf = new byte[blockSize];
+ macIV = null;
+ if (parameters is ParametersWithSBox)
+ {
+ ParametersWithSBox param = (ParametersWithSBox)parameters;
+
+ //
+ // Set the S-Box
+ //
+ param.GetSBox().CopyTo(this.S, 0);
+
+ //
+ // set key if there is one
+ //
+ if (param.Parameters != null)
+ {
+ workingKey = GenerateWorkingKey(((KeyParameter)param.Parameters).GetKey());
+ }
+ }
+ else if (parameters is KeyParameter)
+ {
+ workingKey = GenerateWorkingKey(((KeyParameter)parameters).GetKey());
+ }
+ else if (parameters is ParametersWithIV)
+ {
+ ParametersWithIV p = (ParametersWithIV)parameters;
+
+ workingKey = GenerateWorkingKey(((KeyParameter)p.Parameters).GetKey());
+ Array.Copy(p.GetIV(), 0, mac, 0, mac.Length);
+ macIV = p.GetIV(); // don't skip the initial CM5Func
+ }
+ else
+ {
+ throw new ArgumentException("invalid parameter passed to Gost28147 init - "
+ + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters));
+ }
+ }
+
+ public string AlgorithmName
+ {
+ get { return "Gost28147Mac"; }
+ }
+
+ public int GetMacSize()
+ {
+ return macSize;
+ }
+
+ private int gost28147_mainStep(int n1, int key)
+ {
+ int cm = (key + n1); // CM1
+
+ // S-box replacing
+
+ int om = S[ 0 + ((cm >> (0 * 4)) & 0xF)] << (0 * 4);
+ om += S[ 16 + ((cm >> (1 * 4)) & 0xF)] << (1 * 4);
+ om += S[ 32 + ((cm >> (2 * 4)) & 0xF)] << (2 * 4);
+ om += S[ 48 + ((cm >> (3 * 4)) & 0xF)] << (3 * 4);
+ om += S[ 64 + ((cm >> (4 * 4)) & 0xF)] << (4 * 4);
+ om += S[ 80 + ((cm >> (5 * 4)) & 0xF)] << (5 * 4);
+ om += S[ 96 + ((cm >> (6 * 4)) & 0xF)] << (6 * 4);
+ om += S[112 + ((cm >> (7 * 4)) & 0xF)] << (7 * 4);
+
+// return om << 11 | om >>> (32-11); // 11-leftshift
+ int omLeft = om << 11;
+ int omRight = (int)(((uint) om) >> (32 - 11)); // Note: Casts required to get unsigned bit rotation
+
+ return omLeft | omRight;
+ }
+
+ private void gost28147MacFunc(
+ int[] workingKey,
+ byte[] input,
+ int inOff,
+ byte[] output,
+ int outOff)
+ {
+ int N1, N2, tmp; //tmp -> for saving N1
+ N1 = bytesToint(input, inOff);
+ N2 = bytesToint(input, inOff + 4);
+
+ for (int k = 0; k < 2; k++) // 1-16 steps
+ {
+ for (int j = 0; j < 8; j++)
+ {
+ tmp = N1;
+ N1 = N2 ^ gost28147_mainStep(N1, workingKey[j]); // CM2
+ N2 = tmp;
+ }
+ }
+
+ intTobytes(N1, output, outOff);
+ intTobytes(N2, output, outOff + 4);
+ }
+
+ //array of bytes to type int
+ private static int bytesToint(
+ byte[] input,
+ int inOff)
+ {
+ return (int)((input[inOff + 3] << 24) & 0xff000000) + ((input[inOff + 2] << 16) & 0xff0000)
+ + ((input[inOff + 1] << 8) & 0xff00) + (input[inOff] & 0xff);
+ }
+
+ //int to array of bytes
+ private static void intTobytes(
+ int num,
+ byte[] output,
+ int outOff)
+ {
+ output[outOff + 3] = (byte)(num >> 24);
+ output[outOff + 2] = (byte)(num >> 16);
+ output[outOff + 1] = (byte)(num >> 8);
+ output[outOff] = (byte)num;
+ }
+
+ private static byte[] CM5func(
+ byte[] buf,
+ int bufOff,
+ byte[] mac)
+ {
+ byte[] sum = new byte[buf.Length - bufOff];
+
+ Array.Copy(buf, bufOff, sum, 0, mac.Length);
+
+ for (int i = 0; i != mac.Length; i++)
+ {
+ sum[i] = (byte)(sum[i] ^ mac[i]);
+ }
+
+ return sum;
+ }
+
+ public void Update(
+ byte input)
+ {
+ if (bufOff == buf.Length)
+ {
+ byte[] sumbuf = new byte[buf.Length];
+ Array.Copy(buf, 0, sumbuf, 0, mac.Length);
+
+ if (firstStep)
+ {
+ firstStep = false;
+ if (macIV != null)
+ {
+ sumbuf = CM5func(buf, 0, macIV);
+ }
+ }
+ else
+ {
+ sumbuf = CM5func(buf, 0, mac);
+ }
+
+ gost28147MacFunc(workingKey, sumbuf, 0, mac, 0);
+ bufOff = 0;
+ }
+
+ buf[bufOff++] = input;
+ }
+
+ public void BlockUpdate(
+ byte[] input,
+ int inOff,
+ int len)
+ {
+ if (len < 0)
+ throw new ArgumentException("Can't have a negative input length!");
+
+ int gapLen = blockSize - bufOff;
+
+ if (len > gapLen)
+ {
+ Array.Copy(input, inOff, buf, bufOff, gapLen);
+
+ byte[] sumbuf = new byte[buf.Length];
+ Array.Copy(buf, 0, sumbuf, 0, mac.Length);
+
+ if (firstStep)
+ {
+ firstStep = false;
+ if (macIV != null)
+ {
+ sumbuf = CM5func(buf, 0, macIV);
+ }
+ }
+ else
+ {
+ sumbuf = CM5func(buf, 0, mac);
+ }
+
+ gost28147MacFunc(workingKey, sumbuf, 0, mac, 0);
+
+ bufOff = 0;
+ len -= gapLen;
+ inOff += gapLen;
+
+ while (len > blockSize)
+ {
+ sumbuf = CM5func(input, inOff, mac);
+ gost28147MacFunc(workingKey, sumbuf, 0, mac, 0);
+
+ len -= blockSize;
+ inOff += blockSize;
+ }
+ }
+
+ Array.Copy(input, inOff, buf, bufOff, len);
+
+ bufOff += len;
+ }
+
+ public int DoFinal(
+ byte[] output,
+ int outOff)
+ {
+ //padding with zero
+ while (bufOff < blockSize)
+ {
+ buf[bufOff++] = 0;
+ }
+
+ byte[] sumbuf = new byte[buf.Length];
+ Array.Copy(buf, 0, sumbuf, 0, mac.Length);
+
+ if (firstStep)
+ {
+ firstStep = false;
+ }
+ else
+ {
+ sumbuf = CM5func(buf, 0, mac);
+ }
+
+ gost28147MacFunc(workingKey, sumbuf, 0, mac, 0);
+
+ Array.Copy(mac, (mac.Length/2)-macSize, output, outOff, macSize);
+
+ Reset();
+
+ return macSize;
+ }
+
+ public void Reset()
+ {
+ // Clear the buffer.
+ Array.Clear(buf, 0, buf.Length);
+ bufOff = 0;
+
+ firstStep = true;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/GOST28147Mac.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/GOST28147Mac.cs.meta
new file mode 100644
index 00000000..9d6814cd
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/GOST28147Mac.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a1a6f75281759774dbe9f4409f241a2b
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/HMac.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/HMac.cs
new file mode 100644
index 00000000..e50a2f71
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/HMac.cs
@@ -0,0 +1,158 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs
+{
+ /**
+ * HMAC implementation based on RFC2104
+ *
+ * H(K XOR opad, H(K XOR ipad, text))
+ */
+ public class HMac
+ : IMac
+ {
+ private const byte IPAD = (byte)0x36;
+ private const byte OPAD = (byte)0x5C;
+
+ private readonly IDigest digest;
+ private readonly int digestSize;
+ private readonly int blockLength;
+ private IMemoable ipadState;
+ private IMemoable opadState;
+
+ private readonly byte[] inputPad;
+ private readonly byte[] outputBuf;
+
+ public HMac(IDigest digest)
+ {
+ this.digest = digest;
+ this.digestSize = digest.GetDigestSize();
+ this.blockLength = digest.GetByteLength();
+ this.inputPad = new byte[blockLength];
+ this.outputBuf = new byte[blockLength + digestSize];
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return digest.AlgorithmName + "/HMAC"; }
+ }
+
+ public virtual IDigest GetUnderlyingDigest()
+ {
+ return digest;
+ }
+
+ public virtual void Init(ICipherParameters parameters)
+ {
+ digest.Reset();
+
+ byte[] key = ((KeyParameter)parameters).GetKey();
+ int keyLength = key.Length;
+
+ if (keyLength > blockLength)
+ {
+ digest.BlockUpdate(key, 0, keyLength);
+ digest.DoFinal(inputPad, 0);
+
+ keyLength = digestSize;
+ }
+ else
+ {
+ Array.Copy(key, 0, inputPad, 0, keyLength);
+ }
+
+ Array.Clear(inputPad, keyLength, blockLength - keyLength);
+ Array.Copy(inputPad, 0, outputBuf, 0, blockLength);
+
+ XorPad(inputPad, blockLength, IPAD);
+ XorPad(outputBuf, blockLength, OPAD);
+
+ if (digest is IMemoable)
+ {
+ opadState = ((IMemoable)digest).Copy();
+
+ ((IDigest)opadState).BlockUpdate(outputBuf, 0, blockLength);
+ }
+
+ digest.BlockUpdate(inputPad, 0, inputPad.Length);
+
+ if (digest is IMemoable)
+ {
+ ipadState = ((IMemoable)digest).Copy();
+ }
+ }
+
+ public virtual int GetMacSize()
+ {
+ return digestSize;
+ }
+
+ public virtual void Update(byte input)
+ {
+ digest.Update(input);
+ }
+
+ public virtual void BlockUpdate(byte[] input, int inOff, int len)
+ {
+ digest.BlockUpdate(input, inOff, len);
+ }
+
+ public virtual int DoFinal(byte[] output, int outOff)
+ {
+ digest.DoFinal(outputBuf, blockLength);
+
+ if (opadState != null)
+ {
+ ((IMemoable)digest).Reset(opadState);
+ digest.BlockUpdate(outputBuf, blockLength, digest.GetDigestSize());
+ }
+ else
+ {
+ digest.BlockUpdate(outputBuf, 0, outputBuf.Length);
+ }
+
+ int len = digest.DoFinal(output, outOff);
+
+ Array.Clear(outputBuf, blockLength, digestSize);
+
+ if (ipadState != null)
+ {
+ ((IMemoable)digest).Reset(ipadState);
+ }
+ else
+ {
+ digest.BlockUpdate(inputPad, 0, inputPad.Length);
+ }
+
+ return len;
+ }
+
+ /**
+ * Reset the mac generator.
+ */
+ public virtual void Reset()
+ {
+ // Reset underlying digest
+ digest.Reset();
+
+ // Initialise the digest
+ digest.BlockUpdate(inputPad, 0, inputPad.Length);
+ }
+
+ private static void XorPad(byte[] pad, int len, byte n)
+ {
+ for (int i = 0; i < len; ++i)
+ {
+ pad[i] ^= n;
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/HMac.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/HMac.cs.meta
new file mode 100644
index 00000000..78867a2f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/HMac.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ff9c8a587cf6ee843b4bc5fadb67a117
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/ISO9797Alg3Mac.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/ISO9797Alg3Mac.cs
new file mode 100644
index 00000000..31d8d91e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/ISO9797Alg3Mac.cs
@@ -0,0 +1,279 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Paddings;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs
+{
+ /**
+ * DES based CBC Block Cipher MAC according to ISO9797, algorithm 3 (ANSI X9.19 Retail MAC)
+ *
+ * This could as well be derived from CBCBlockCipherMac, but then the property mac in the base
+ * class must be changed to protected
+ */
+ public class ISO9797Alg3Mac : IMac
+ {
+ private byte[] mac;
+ private byte[] buf;
+ private int bufOff;
+ private IBlockCipher cipher;
+ private IBlockCipherPadding padding;
+ private int macSize;
+ private KeyParameter lastKey2;
+ private KeyParameter lastKey3;
+
+ /**
+ * create a Retail-MAC based on a CBC block cipher. This will produce an
+ * authentication code of the length of the block size of the cipher.
+ *
+ * @param cipher the cipher to be used as the basis of the MAC generation. This must
+ * be DESEngine.
+ */
+ public ISO9797Alg3Mac(
+ IBlockCipher cipher)
+ : this(cipher, cipher.GetBlockSize() * 8, null)
+ {
+ }
+
+ /**
+ * create a Retail-MAC based on a CBC block cipher. This will produce an
+ * authentication code of the length of the block size of the cipher.
+ *
+ * @param cipher the cipher to be used as the basis of the MAC generation.
+ * @param padding the padding to be used to complete the last block.
+ */
+ public ISO9797Alg3Mac(
+ IBlockCipher cipher,
+ IBlockCipherPadding padding)
+ : this(cipher, cipher.GetBlockSize() * 8, padding)
+ {
+ }
+
+ /**
+ * create a Retail-MAC based on a block cipher with the size of the
+ * MAC been given in bits. This class uses single DES CBC mode as the basis for the
+ * MAC generation.
+ *
+ * Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
+ * or 16 bits if being used as a data authenticator (FIPS Publication 113),
+ * and in general should be less than the size of the block cipher as it reduces
+ * the chance of an exhaustive attack (see Handbook of Applied Cryptography).
+ *
+ * @param cipher the cipher to be used as the basis of the MAC generation.
+ * @param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
+ */
+ public ISO9797Alg3Mac(
+ IBlockCipher cipher,
+ int macSizeInBits)
+ : this(cipher, macSizeInBits, null)
+ {
+ }
+
+ /**
+ * create a standard MAC based on a block cipher with the size of the
+ * MAC been given in bits. This class uses single DES CBC mode as the basis for the
+ * MAC generation. The final block is decrypted and then encrypted using the
+ * middle and right part of the key.
+ *
+ * Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
+ * or 16 bits if being used as a data authenticator (FIPS Publication 113),
+ * and in general should be less than the size of the block cipher as it reduces
+ * the chance of an exhaustive attack (see Handbook of Applied Cryptography).
+ *
+ * @param cipher the cipher to be used as the basis of the MAC generation.
+ * @param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
+ * @param padding the padding to be used to complete the last block.
+ */
+ public ISO9797Alg3Mac(
+ IBlockCipher cipher,
+ int macSizeInBits,
+ IBlockCipherPadding padding)
+ {
+ if ((macSizeInBits % 8) != 0)
+ throw new ArgumentException("MAC size must be multiple of 8");
+
+ if (!(cipher is DesEngine))
+ throw new ArgumentException("cipher must be instance of DesEngine");
+
+ this.cipher = new CbcBlockCipher(cipher);
+ this.padding = padding;
+ this.macSize = macSizeInBits / 8;
+
+ mac = new byte[cipher.GetBlockSize()];
+ buf = new byte[cipher.GetBlockSize()];
+ bufOff = 0;
+ }
+
+ public string AlgorithmName
+ {
+ get { return "ISO9797Alg3"; }
+ }
+
+ public void Init(
+ ICipherParameters parameters)
+ {
+ Reset();
+
+ if (!(parameters is KeyParameter || parameters is ParametersWithIV))
+ throw new ArgumentException("parameters must be an instance of KeyParameter or ParametersWithIV");
+
+ // KeyParameter must contain a double or triple length DES key,
+ // however the underlying cipher is a single DES. The middle and
+ // right key are used only in the final step.
+
+ KeyParameter kp;
+ if (parameters is KeyParameter)
+ {
+ kp = (KeyParameter)parameters;
+ }
+ else
+ {
+ kp = (KeyParameter)((ParametersWithIV)parameters).Parameters;
+ }
+
+ KeyParameter key1;
+ byte[] keyvalue = kp.GetKey();
+
+ if (keyvalue.Length == 16)
+ { // Double length DES key
+ key1 = new KeyParameter(keyvalue, 0, 8);
+ this.lastKey2 = new KeyParameter(keyvalue, 8, 8);
+ this.lastKey3 = key1;
+ }
+ else if (keyvalue.Length == 24)
+ { // Triple length DES key
+ key1 = new KeyParameter(keyvalue, 0, 8);
+ this.lastKey2 = new KeyParameter(keyvalue, 8, 8);
+ this.lastKey3 = new KeyParameter(keyvalue, 16, 8);
+ }
+ else
+ {
+ throw new ArgumentException("Key must be either 112 or 168 bit long");
+ }
+
+ if (parameters is ParametersWithIV)
+ {
+ cipher.Init(true, new ParametersWithIV(key1, ((ParametersWithIV)parameters).GetIV()));
+ }
+ else
+ {
+ cipher.Init(true, key1);
+ }
+ }
+
+ public int GetMacSize()
+ {
+ return macSize;
+ }
+
+ public void Update(
+ byte input)
+ {
+ if (bufOff == buf.Length)
+ {
+ cipher.ProcessBlock(buf, 0, mac, 0);
+ bufOff = 0;
+ }
+
+ buf[bufOff++] = input;
+ }
+
+ public void BlockUpdate(
+ byte[] input,
+ int inOff,
+ int len)
+ {
+ if (len < 0)
+ throw new ArgumentException("Can't have a negative input length!");
+
+ int blockSize = cipher.GetBlockSize();
+ int resultLen = 0;
+ int gapLen = blockSize - bufOff;
+
+ if (len > gapLen)
+ {
+ Array.Copy(input, inOff, buf, bufOff, gapLen);
+
+ resultLen += cipher.ProcessBlock(buf, 0, mac, 0);
+
+ bufOff = 0;
+ len -= gapLen;
+ inOff += gapLen;
+
+ while (len > blockSize)
+ {
+ resultLen += cipher.ProcessBlock(input, inOff, mac, 0);
+
+ len -= blockSize;
+ inOff += blockSize;
+ }
+ }
+
+ Array.Copy(input, inOff, buf, bufOff, len);
+
+ bufOff += len;
+ }
+
+ public int DoFinal(
+ byte[] output,
+ int outOff)
+ {
+ int blockSize = cipher.GetBlockSize();
+
+ if (padding == null)
+ {
+ // pad with zeroes
+ while (bufOff < blockSize)
+ {
+ buf[bufOff++] = 0;
+ }
+ }
+ else
+ {
+ if (bufOff == blockSize)
+ {
+ cipher.ProcessBlock(buf, 0, mac, 0);
+ bufOff = 0;
+ }
+
+ padding.AddPadding(buf, bufOff);
+ }
+
+ cipher.ProcessBlock(buf, 0, mac, 0);
+
+ // Added to code from base class
+ DesEngine deseng = new DesEngine();
+
+ deseng.Init(false, this.lastKey2);
+ deseng.ProcessBlock(mac, 0, mac, 0);
+
+ deseng.Init(true, this.lastKey3);
+ deseng.ProcessBlock(mac, 0, mac, 0);
+ // ****
+
+ Array.Copy(mac, 0, output, outOff, macSize);
+
+ Reset();
+
+ return macSize;
+ }
+
+ /**
+ * Reset the mac generator.
+ */
+ public void Reset()
+ {
+ Array.Clear(buf, 0, buf.Length);
+ bufOff = 0;
+
+ // reset the underlying cipher.
+ cipher.Reset();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/ISO9797Alg3Mac.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/ISO9797Alg3Mac.cs.meta
new file mode 100644
index 00000000..d00aad9d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/ISO9797Alg3Mac.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ba1bf157d949c9a40b850fc633d073cb
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/Poly1305.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/Poly1305.cs
new file mode 100644
index 00000000..f0ab17b6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/Poly1305.cs
@@ -0,0 +1,297 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs
+{
+
+ ///
+ /// Poly1305 message authentication code, designed by D. J. Bernstein.
+ ///
+ ///
+ /// Poly1305 computes a 128-bit (16 bytes) authenticator, using a 128 bit nonce and a 256 bit key
+ /// consisting of a 128 bit key applied to an underlying cipher, and a 128 bit key (with 106
+ /// effective key bits) used in the authenticator.
+ ///
+ /// The polynomial calculation in this implementation is adapted from the public domain poly1305-donna-unrolled C implementation
+ /// by Andrew M (@floodyberry).
+ ///
+ ///
+ public class Poly1305
+ : IMac
+ {
+ private const int BlockSize = 16;
+
+ private readonly IBlockCipher cipher;
+
+ private readonly byte[] singleByte = new byte[1];
+
+ // Initialised state
+
+ /** Polynomial key */
+ private uint r0, r1, r2, r3, r4;
+
+ /** Precomputed 5 * r[1..4] */
+ private uint s1, s2, s3, s4;
+
+ /** Encrypted nonce */
+ private uint k0, k1, k2, k3;
+
+ // Accumulating state
+
+ /** Current block of buffered input */
+ private byte[] currentBlock = new byte[BlockSize];
+
+ /** Current offset in input buffer */
+ private int currentBlockOffset = 0;
+
+ /** Polynomial accumulator */
+ private uint h0, h1, h2, h3, h4;
+
+ /**
+ * Constructs a Poly1305 MAC, where the key passed to init() will be used directly.
+ */
+ public Poly1305()
+ {
+ this.cipher = null;
+ }
+
+ /**
+ * Constructs a Poly1305 MAC, using a 128 bit block cipher.
+ */
+ public Poly1305(IBlockCipher cipher)
+ {
+ if (cipher.GetBlockSize() != BlockSize)
+ {
+ throw new ArgumentException("Poly1305 requires a 128 bit block cipher.");
+ }
+ this.cipher = cipher;
+ }
+
+ ///
+ /// Initialises the Poly1305 MAC.
+ ///
+ /// a {@link ParametersWithIV} containing a 128 bit nonce and a {@link KeyParameter} with
+ /// a 256 bit key complying to the {@link Poly1305KeyGenerator Poly1305 key format}.
+ public void Init(ICipherParameters parameters)
+ {
+ byte[] nonce = null;
+
+ if (cipher != null)
+ {
+ if (!(parameters is ParametersWithIV))
+ throw new ArgumentException("Poly1305 requires an IV when used with a block cipher.", "parameters");
+
+ ParametersWithIV ivParams = (ParametersWithIV)parameters;
+ nonce = ivParams.GetIV();
+ parameters = ivParams.Parameters;
+ }
+
+ if (!(parameters is KeyParameter))
+ throw new ArgumentException("Poly1305 requires a key.");
+
+ KeyParameter keyParams = (KeyParameter)parameters;
+
+ SetKey(keyParams.GetKey(), nonce);
+
+ Reset();
+ }
+
+ private void SetKey(byte[] key, byte[] nonce)
+ {
+ if (key.Length != 32)
+ throw new ArgumentException("Poly1305 key must be 256 bits.");
+
+ if (cipher != null && (nonce == null || nonce.Length != BlockSize))
+ throw new ArgumentException("Poly1305 requires a 128 bit IV.");
+
+ // Extract r portion of key (and "clamp" the values)
+ uint t0 = Pack.LE_To_UInt32(key, 0);
+ uint t1 = Pack.LE_To_UInt32(key, 4);
+ uint t2 = Pack.LE_To_UInt32(key, 8);
+ uint t3 = Pack.LE_To_UInt32(key, 12);
+
+ // NOTE: The masks perform the key "clamping" implicitly
+ r0 = t0 & 0x03FFFFFFU;
+ r1 = ((t0 >> 26) | (t1 << 6)) & 0x03FFFF03U;
+ r2 = ((t1 >> 20) | (t2 << 12)) & 0x03FFC0FFU;
+ r3 = ((t2 >> 14) | (t3 << 18)) & 0x03F03FFFU;
+ r4 = (t3 >> 8) & 0x000FFFFFU;
+
+ // Precompute multipliers
+ s1 = r1 * 5;
+ s2 = r2 * 5;
+ s3 = r3 * 5;
+ s4 = r4 * 5;
+
+ byte[] kBytes;
+ int kOff;
+
+ if (cipher == null)
+ {
+ kBytes = key;
+ kOff = BlockSize;
+ }
+ else
+ {
+ // Compute encrypted nonce
+ kBytes = new byte[BlockSize];
+ kOff = 0;
+
+ cipher.Init(true, new KeyParameter(key, BlockSize, BlockSize));
+ cipher.ProcessBlock(nonce, 0, kBytes, 0);
+ }
+
+ k0 = Pack.LE_To_UInt32(kBytes, kOff + 0);
+ k1 = Pack.LE_To_UInt32(kBytes, kOff + 4);
+ k2 = Pack.LE_To_UInt32(kBytes, kOff + 8);
+ k3 = Pack.LE_To_UInt32(kBytes, kOff + 12);
+ }
+
+ public string AlgorithmName
+ {
+ get { return cipher == null ? "Poly1305" : "Poly1305-" + cipher.AlgorithmName; }
+ }
+
+ public int GetMacSize()
+ {
+ return BlockSize;
+ }
+
+ public void Update(byte input)
+ {
+ singleByte[0] = input;
+ BlockUpdate(singleByte, 0, 1);
+ }
+
+ public void BlockUpdate(byte[] input, int inOff, int len)
+ {
+ int copied = 0;
+ while (len > copied)
+ {
+ if (currentBlockOffset == BlockSize)
+ {
+ ProcessBlock();
+ currentBlockOffset = 0;
+ }
+
+ int toCopy = System.Math.Min((len - copied), BlockSize - currentBlockOffset);
+ Array.Copy(input, copied + inOff, currentBlock, currentBlockOffset, toCopy);
+ copied += toCopy;
+ currentBlockOffset += toCopy;
+ }
+
+ }
+
+ private void ProcessBlock()
+ {
+ if (currentBlockOffset < BlockSize)
+ {
+ currentBlock[currentBlockOffset] = 1;
+ for (int i = currentBlockOffset + 1; i < BlockSize; i++)
+ {
+ currentBlock[i] = 0;
+ }
+ }
+
+ ulong t0 = Pack.LE_To_UInt32(currentBlock, 0);
+ ulong t1 = Pack.LE_To_UInt32(currentBlock, 4);
+ ulong t2 = Pack.LE_To_UInt32(currentBlock, 8);
+ ulong t3 = Pack.LE_To_UInt32(currentBlock, 12);
+
+ h0 += (uint)(t0 & 0x3ffffffU);
+ h1 += (uint)((((t1 << 32) | t0) >> 26) & 0x3ffffff);
+ h2 += (uint)((((t2 << 32) | t1) >> 20) & 0x3ffffff);
+ h3 += (uint)((((t3 << 32) | t2) >> 14) & 0x3ffffff);
+ h4 += (uint)(t3 >> 8);
+
+ if (currentBlockOffset == BlockSize)
+ {
+ h4 += (1 << 24);
+ }
+
+ ulong tp0 = mul32x32_64(h0,r0) + mul32x32_64(h1,s4) + mul32x32_64(h2,s3) + mul32x32_64(h3,s2) + mul32x32_64(h4,s1);
+ ulong tp1 = mul32x32_64(h0,r1) + mul32x32_64(h1,r0) + mul32x32_64(h2,s4) + mul32x32_64(h3,s3) + mul32x32_64(h4,s2);
+ ulong tp2 = mul32x32_64(h0,r2) + mul32x32_64(h1,r1) + mul32x32_64(h2,r0) + mul32x32_64(h3,s4) + mul32x32_64(h4,s3);
+ ulong tp3 = mul32x32_64(h0,r3) + mul32x32_64(h1,r2) + mul32x32_64(h2,r1) + mul32x32_64(h3,r0) + mul32x32_64(h4,s4);
+ ulong tp4 = mul32x32_64(h0,r4) + mul32x32_64(h1,r3) + mul32x32_64(h2,r2) + mul32x32_64(h3,r1) + mul32x32_64(h4,r0);
+
+ h0 = (uint)tp0 & 0x3ffffff; tp1 += (tp0 >> 26);
+ h1 = (uint)tp1 & 0x3ffffff; tp2 += (tp1 >> 26);
+ h2 = (uint)tp2 & 0x3ffffff; tp3 += (tp2 >> 26);
+ h3 = (uint)tp3 & 0x3ffffff; tp4 += (tp3 >> 26);
+ h4 = (uint)tp4 & 0x3ffffff;
+ h0 += (uint)(tp4 >> 26) * 5;
+ h1 += (h0 >> 26); h0 &= 0x3ffffff;
+ }
+
+ public int DoFinal(byte[] output, int outOff)
+ {
+ Check.DataLength(output, outOff, BlockSize, "Output buffer is too short.");
+
+ if (currentBlockOffset > 0)
+ {
+ // Process padded block
+ ProcessBlock();
+ }
+
+ h1 += (h0 >> 26); h0 &= 0x3ffffff;
+ h2 += (h1 >> 26); h1 &= 0x3ffffff;
+ h3 += (h2 >> 26); h2 &= 0x3ffffff;
+ h4 += (h3 >> 26); h3 &= 0x3ffffff;
+ h0 += (h4 >> 26) * 5; h4 &= 0x3ffffff;
+ h1 += (h0 >> 26); h0 &= 0x3ffffff;
+
+ uint g0, g1, g2, g3, g4, b;
+ g0 = h0 + 5; b = g0 >> 26; g0 &= 0x3ffffff;
+ g1 = h1 + b; b = g1 >> 26; g1 &= 0x3ffffff;
+ g2 = h2 + b; b = g2 >> 26; g2 &= 0x3ffffff;
+ g3 = h3 + b; b = g3 >> 26; g3 &= 0x3ffffff;
+ g4 = h4 + b - (1 << 26);
+
+ b = (g4 >> 31) - 1;
+ uint nb = ~b;
+ h0 = (h0 & nb) | (g0 & b);
+ h1 = (h1 & nb) | (g1 & b);
+ h2 = (h2 & nb) | (g2 & b);
+ h3 = (h3 & nb) | (g3 & b);
+ h4 = (h4 & nb) | (g4 & b);
+
+ ulong f0, f1, f2, f3;
+ f0 = ((h0 ) | (h1 << 26)) + (ulong)k0;
+ f1 = ((h1 >> 6 ) | (h2 << 20)) + (ulong)k1;
+ f2 = ((h2 >> 12) | (h3 << 14)) + (ulong)k2;
+ f3 = ((h3 >> 18) | (h4 << 8 )) + (ulong)k3;
+
+ Pack.UInt32_To_LE((uint)f0, output, outOff);
+ f1 += (f0 >> 32);
+ Pack.UInt32_To_LE((uint)f1, output, outOff + 4);
+ f2 += (f1 >> 32);
+ Pack.UInt32_To_LE((uint)f2, output, outOff + 8);
+ f3 += (f2 >> 32);
+ Pack.UInt32_To_LE((uint)f3, output, outOff + 12);
+
+ Reset();
+ return BlockSize;
+ }
+
+ public void Reset()
+ {
+ currentBlockOffset = 0;
+
+ h0 = h1 = h2 = h3 = h4 = 0;
+ }
+
+ private static ulong mul32x32_64(uint i1, uint i2)
+ {
+ return ((ulong)i1) * i2;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/Poly1305.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/Poly1305.cs.meta
new file mode 100644
index 00000000..fd42df6a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/Poly1305.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 741547bc11f330d47b607e905832b385
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/SipHash.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/SipHash.cs
new file mode 100644
index 00000000..74f7e8de
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/SipHash.cs
@@ -0,0 +1,203 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs
+{
+ ///
+ /// Implementation of SipHash as specified in "SipHash: a fast short-input PRF", by Jean-Philippe
+ /// Aumasson and Daniel J. Bernstein (https://131002.net/siphash/siphash.pdf).
+ ///
+ ///
+ /// "SipHash is a family of PRFs SipHash-c-d where the integer parameters c and d are the number of
+ /// compression rounds and the number of finalization rounds. A compression round is identical to a
+ /// finalization round and this round function is called SipRound. Given a 128-bit key k and a
+ /// (possibly empty) byte string m, SipHash-c-d returns a 64-bit value..."
+ ///
+ public class SipHash
+ : IMac
+ {
+ protected readonly int c, d;
+
+ protected long k0, k1;
+ protected long v0, v1, v2, v3;
+
+ protected long m = 0;
+ protected int wordPos = 0;
+ protected int wordCount = 0;
+
+ /// SipHash-2-4
+ public SipHash()
+ : this(2, 4)
+ {
+ }
+
+ /// SipHash-c-d
+ /// the number of compression rounds
+ /// the number of finalization rounds
+ public SipHash(int c, int d)
+ {
+ this.c = c;
+ this.d = d;
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "SipHash-" + c + "-" + d; }
+ }
+
+ public virtual int GetMacSize()
+ {
+ return 8;
+ }
+
+ public virtual void Init(ICipherParameters parameters)
+ {
+ KeyParameter keyParameter = parameters as KeyParameter;
+ if (keyParameter == null)
+ throw new ArgumentException("must be an instance of KeyParameter", "parameters");
+ byte[] key = keyParameter.GetKey();
+ if (key.Length != 16)
+ throw new ArgumentException("must be a 128-bit key", "parameters");
+
+ this.k0 = (long)Pack.LE_To_UInt64(key, 0);
+ this.k1 = (long)Pack.LE_To_UInt64(key, 8);
+
+ Reset();
+ }
+
+ public virtual void Update(byte input)
+ {
+ m = (long)(((ulong)m >> 8) | ((ulong)input << 56));
+
+ if (++wordPos == 8)
+ {
+ ProcessMessageWord();
+ wordPos = 0;
+ }
+ }
+
+ public virtual void BlockUpdate(byte[] input, int offset, int length)
+ {
+ int i = 0, fullWords = length & ~7;
+ if (wordPos == 0)
+ {
+ for (; i < fullWords; i += 8)
+ {
+ m = (long)Pack.LE_To_UInt64(input, offset + i);
+ ProcessMessageWord();
+ }
+ for (; i < length; ++i)
+ {
+ m = (long)(((ulong)m >> 8) | ((ulong)input[offset + i] << 56));
+ }
+ wordPos = length - fullWords;
+ }
+ else
+ {
+ int bits = wordPos << 3;
+ for (; i < fullWords; i += 8)
+ {
+ ulong n = Pack.LE_To_UInt64(input, offset + i);
+ m = (long)((n << bits) | ((ulong)m >> -bits));
+ ProcessMessageWord();
+ m = (long)n;
+ }
+ for (; i < length; ++i)
+ {
+ m = (long)(((ulong)m >> 8) | ((ulong)input[offset + i] << 56));
+
+ if (++wordPos == 8)
+ {
+ ProcessMessageWord();
+ wordPos = 0;
+ }
+ }
+ }
+ }
+
+ public virtual long DoFinal()
+ {
+ // NOTE: 2 distinct shifts to avoid "64-bit shift" when wordPos == 0
+ m = (long)((ulong)m >> ((7 - wordPos) << 3));
+ m = (long)((ulong)m >> 8);
+ m = (long)((ulong)m | ((ulong)((wordCount << 3) + wordPos) << 56));
+
+ ProcessMessageWord();
+
+ v2 ^= 0xffL;
+
+ ApplySipRounds(d);
+
+ long result = v0 ^ v1 ^ v2 ^ v3;
+
+ Reset();
+
+ return result;
+ }
+
+ public virtual int DoFinal(byte[] output, int outOff)
+ {
+ long result = DoFinal();
+ Pack.UInt64_To_LE((ulong)result, output, outOff);
+ return 8;
+ }
+
+ public virtual void Reset()
+ {
+ v0 = k0 ^ 0x736f6d6570736575L;
+ v1 = k1 ^ 0x646f72616e646f6dL;
+ v2 = k0 ^ 0x6c7967656e657261L;
+ v3 = k1 ^ 0x7465646279746573L;
+
+ m = 0;
+ wordPos = 0;
+ wordCount = 0;
+ }
+
+ protected virtual void ProcessMessageWord()
+ {
+ ++wordCount;
+ v3 ^= m;
+ ApplySipRounds(c);
+ v0 ^= m;
+ }
+
+ protected virtual void ApplySipRounds(int n)
+ {
+ long r0 = v0, r1 = v1, r2 = v2, r3 = v3;
+
+ for (int r = 0; r < n; ++r)
+ {
+ r0 += r1;
+ r2 += r3;
+ r1 = RotateLeft(r1, 13);
+ r3 = RotateLeft(r3, 16);
+ r1 ^= r0;
+ r3 ^= r2;
+ r0 = RotateLeft(r0, 32);
+ r2 += r1;
+ r0 += r3;
+ r1 = RotateLeft(r1, 17);
+ r3 = RotateLeft(r3, 21);
+ r1 ^= r2;
+ r3 ^= r0;
+ r2 = RotateLeft(r2, 32);
+ }
+
+ v0 = r0; v1 = r1; v2 = r2; v3 = r3;
+ }
+
+ protected static long RotateLeft(long x, int n)
+ {
+ ulong ux = (ulong)x;
+ ux = (ux << n) | (ux >> -n);
+ return (long)ux;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/SipHash.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/SipHash.cs.meta
new file mode 100644
index 00000000..e9857af6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/SipHash.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: b0bbbba09da03b8439fc20b05469327b
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/SkeinMac.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/SkeinMac.cs
new file mode 100644
index 00000000..3daaf469
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/SkeinMac.cs
@@ -0,0 +1,122 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs
+{
+
+ ///
+ /// Implementation of the Skein parameterised MAC function in 256, 512 and 1024 bit block sizes,
+ /// based on the Threefish tweakable block cipher.
+ ///
+ ///
+ /// This is the 1.3 version of Skein defined in the Skein hash function submission to the NIST SHA-3
+ /// competition in October 2010.
+ ///
+ /// Skein was designed by Niels Ferguson - Stefan Lucks - Bruce Schneier - Doug Whiting - Mihir
+ /// Bellare - Tadayoshi Kohno - Jon Callas - Jesse Walker.
+ ///
+ ///
+ ///
+ public class SkeinMac
+ : IMac
+ {
+ ///
+ /// 256 bit block size - Skein-256
+ ///
+ public const int SKEIN_256 = SkeinEngine.SKEIN_256;
+ ///
+ /// 512 bit block size - Skein-512
+ ///
+ public const int SKEIN_512 = SkeinEngine.SKEIN_512;
+ ///
+ /// 1024 bit block size - Skein-1024
+ ///
+ public const int SKEIN_1024 = SkeinEngine.SKEIN_1024;
+
+ private readonly SkeinEngine engine;
+
+ ///
+ /// Constructs a Skein MAC with an internal state size and output size.
+ ///
+ /// the internal state size in bits - one of or
+ /// .
+ /// the output/MAC size to produce in bits, which must be an integral number of
+ /// bytes.
+ public SkeinMac(int stateSizeBits, int digestSizeBits)
+ {
+ this.engine = new SkeinEngine(stateSizeBits, digestSizeBits);
+ }
+
+ public SkeinMac(SkeinMac mac)
+ {
+ this.engine = new SkeinEngine(mac.engine);
+ }
+
+ public string AlgorithmName
+ {
+ get { return "Skein-MAC-" + (engine.BlockSize * 8) + "-" + (engine.OutputSize * 8); }
+ }
+
+ ///
+ /// Optionally initialises the Skein digest with the provided parameters.
+ ///
+ /// See for details on the parameterisation of the Skein hash function.
+ /// the parameters to apply to this engine, or null to use no parameters.
+ public void Init(ICipherParameters parameters)
+ {
+ SkeinParameters skeinParameters;
+ if (parameters is SkeinParameters)
+ {
+ skeinParameters = (SkeinParameters)parameters;
+ }
+ else if (parameters is KeyParameter)
+ {
+ skeinParameters = new SkeinParameters.Builder().SetKey(((KeyParameter)parameters).GetKey()).Build();
+ }
+ else
+ {
+ throw new ArgumentException("Invalid parameter passed to Skein MAC init - "
+ + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters));
+ }
+ if (skeinParameters.GetKey() == null)
+ {
+ throw new ArgumentException("Skein MAC requires a key parameter.");
+ }
+ engine.Init(skeinParameters);
+ }
+
+ public int GetMacSize()
+ {
+ return engine.OutputSize;
+ }
+
+ public void Reset()
+ {
+ engine.Reset();
+ }
+
+ public void Update(byte inByte)
+ {
+ engine.Update(inByte);
+ }
+
+ public void BlockUpdate(byte[] input, int inOff, int len)
+ {
+ engine.Update(input, inOff, len);
+ }
+
+ public int DoFinal(byte[] output, int outOff)
+ {
+ return engine.DoFinal(output, outOff);
+ }
+
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/SkeinMac.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/SkeinMac.cs.meta
new file mode 100644
index 00000000..20755db2
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/SkeinMac.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: af48cc87590fd7a4d9bb38522bbd59bc
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/VMPCMac.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/VMPCMac.cs
new file mode 100644
index 00000000..03c08830
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/VMPCMac.cs
@@ -0,0 +1,177 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs
+{
+ public class VmpcMac
+ : IMac
+ {
+ private byte g;
+
+ private byte n = 0;
+ private byte[] P = null;
+ private byte s = 0;
+
+ private byte[] T;
+ private byte[] workingIV;
+
+ private byte[] workingKey;
+
+ private byte x1, x2, x3, x4;
+
+ public virtual int DoFinal(byte[] output, int outOff)
+ {
+ // Execute the Post-Processing Phase
+ for (int r = 1; r < 25; r++)
+ {
+ s = P[(s + P[n & 0xff]) & 0xff];
+
+ x4 = P[(x4 + x3 + r) & 0xff];
+ x3 = P[(x3 + x2 + r) & 0xff];
+ x2 = P[(x2 + x1 + r) & 0xff];
+ x1 = P[(x1 + s + r) & 0xff];
+ T[g & 0x1f] = (byte) (T[g & 0x1f] ^ x1);
+ T[(g + 1) & 0x1f] = (byte) (T[(g + 1) & 0x1f] ^ x2);
+ T[(g + 2) & 0x1f] = (byte) (T[(g + 2) & 0x1f] ^ x3);
+ T[(g + 3) & 0x1f] = (byte) (T[(g + 3) & 0x1f] ^ x4);
+ g = (byte) ((g + 4) & 0x1f);
+
+ byte temp = P[n & 0xff];
+ P[n & 0xff] = P[s & 0xff];
+ P[s & 0xff] = temp;
+ n = (byte) ((n + 1) & 0xff);
+ }
+
+ // Input T to the IV-phase of the VMPC KSA
+ for (int m = 0; m < 768; m++)
+ {
+ s = P[(s + P[m & 0xff] + T[m & 0x1f]) & 0xff];
+ byte temp = P[m & 0xff];
+ P[m & 0xff] = P[s & 0xff];
+ P[s & 0xff] = temp;
+ }
+
+ // Store 20 new outputs of the VMPC Stream Cipher input table M
+ byte[] M = new byte[20];
+ for (int i = 0; i < 20; i++)
+ {
+ s = P[(s + P[i & 0xff]) & 0xff];
+ M[i] = P[(P[(P[s & 0xff]) & 0xff] + 1) & 0xff];
+
+ byte temp = P[i & 0xff];
+ P[i & 0xff] = P[s & 0xff];
+ P[s & 0xff] = temp;
+ }
+
+ Array.Copy(M, 0, output, outOff, M.Length);
+ Reset();
+
+ return M.Length;
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "VMPC-MAC"; }
+ }
+
+ public virtual int GetMacSize()
+ {
+ return 20;
+ }
+
+ public virtual void Init(ICipherParameters parameters)
+ {
+ if (!(parameters is ParametersWithIV))
+ throw new ArgumentException("VMPC-MAC Init parameters must include an IV", "parameters");
+
+ ParametersWithIV ivParams = (ParametersWithIV) parameters;
+ KeyParameter key = (KeyParameter) ivParams.Parameters;
+
+ if (!(ivParams.Parameters is KeyParameter))
+ throw new ArgumentException("VMPC-MAC Init parameters must include a key", "parameters");
+
+ this.workingIV = ivParams.GetIV();
+
+ if (workingIV == null || workingIV.Length < 1 || workingIV.Length > 768)
+ throw new ArgumentException("VMPC-MAC requires 1 to 768 bytes of IV", "parameters");
+
+ this.workingKey = key.GetKey();
+
+ Reset();
+
+ }
+
+ private void initKey(byte[] keyBytes, byte[] ivBytes)
+ {
+ s = 0;
+ P = new byte[256];
+ for (int i = 0; i < 256; i++)
+ {
+ P[i] = (byte) i;
+ }
+ for (int m = 0; m < 768; m++)
+ {
+ s = P[(s + P[m & 0xff] + keyBytes[m % keyBytes.Length]) & 0xff];
+ byte temp = P[m & 0xff];
+ P[m & 0xff] = P[s & 0xff];
+ P[s & 0xff] = temp;
+ }
+ for (int m = 0; m < 768; m++)
+ {
+ s = P[(s + P[m & 0xff] + ivBytes[m % ivBytes.Length]) & 0xff];
+ byte temp = P[m & 0xff];
+ P[m & 0xff] = P[s & 0xff];
+ P[s & 0xff] = temp;
+ }
+ n = 0;
+ }
+
+ public virtual void Reset()
+ {
+ initKey(this.workingKey, this.workingIV);
+ g = x1 = x2 = x3 = x4 = n = 0;
+ T = new byte[32];
+ for (int i = 0; i < 32; i++)
+ {
+ T[i] = 0;
+ }
+ }
+
+ public virtual void Update(byte input)
+ {
+ s = P[(s + P[n & 0xff]) & 0xff];
+ byte c = (byte) (input ^ P[(P[(P[s & 0xff]) & 0xff] + 1) & 0xff]);
+
+ x4 = P[(x4 + x3) & 0xff];
+ x3 = P[(x3 + x2) & 0xff];
+ x2 = P[(x2 + x1) & 0xff];
+ x1 = P[(x1 + s + c) & 0xff];
+ T[g & 0x1f] = (byte) (T[g & 0x1f] ^ x1);
+ T[(g + 1) & 0x1f] = (byte) (T[(g + 1) & 0x1f] ^ x2);
+ T[(g + 2) & 0x1f] = (byte) (T[(g + 2) & 0x1f] ^ x3);
+ T[(g + 3) & 0x1f] = (byte) (T[(g + 3) & 0x1f] ^ x4);
+ g = (byte) ((g + 4) & 0x1f);
+
+ byte temp = P[n & 0xff];
+ P[n & 0xff] = P[s & 0xff];
+ P[s & 0xff] = temp;
+ n = (byte) ((n + 1) & 0xff);
+ }
+
+ public virtual void BlockUpdate(byte[] input, int inOff, int len)
+ {
+ if ((inOff + len) > input.Length)
+ throw new DataLengthException("input buffer too short");
+
+ for (int i = 0; i < len; i++)
+ {
+ Update(input[inOff + i]);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/VMPCMac.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/VMPCMac.cs.meta
new file mode 100644
index 00000000..892d98a5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/macs/VMPCMac.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 4144352b9e83dda43b21e612553bf87c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes.meta
new file mode 100644
index 00000000..d65ffab2
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 7290ea1bd4b4b8044b8c839a0f6e38e6
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/CbcBlockCipher.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/CbcBlockCipher.cs
new file mode 100644
index 00000000..8c683f59
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/CbcBlockCipher.cs
@@ -0,0 +1,245 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes
+{
+ /**
+ * implements Cipher-Block-Chaining (CBC) mode on top of a simple cipher.
+ */
+ public sealed class CbcBlockCipher
+ : IBlockCipher
+ {
+ private byte[] IV, cbcV, cbcNextV;
+ private int blockSize;
+ private IBlockCipher cipher;
+ private bool encrypting;
+
+ /**
+ * Basic constructor.
+ *
+ * @param cipher the block cipher to be used as the basis of chaining.
+ */
+ public CbcBlockCipher(
+ IBlockCipher cipher)
+ {
+ this.cipher = cipher;
+ this.blockSize = cipher.GetBlockSize();
+
+ this.IV = new byte[blockSize];
+ this.cbcV = new byte[blockSize];
+ this.cbcNextV = new byte[blockSize];
+ }
+
+ /**
+ * return the underlying block cipher that we are wrapping.
+ *
+ * @return the underlying block cipher that we are wrapping.
+ */
+ public IBlockCipher GetUnderlyingCipher()
+ {
+ return cipher;
+ }
+
+ /**
+ * Initialise the cipher and, possibly, the initialisation vector (IV).
+ * If an IV isn't passed as part of the parameter, the IV will be all zeros.
+ *
+ * @param forEncryption if true the cipher is initialised for
+ * encryption, if false for decryption.
+ * @param param the key and other data required by the cipher.
+ * @exception ArgumentException if the parameters argument is
+ * inappropriate.
+ */
+ public void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ bool oldEncrypting = this.encrypting;
+
+ this.encrypting = forEncryption;
+
+ if (parameters is ParametersWithIV)
+ {
+ ParametersWithIV ivParam = (ParametersWithIV)parameters;
+ byte[] iv = ivParam.GetIV();
+
+ if (iv.Length != blockSize)
+ {
+ throw new ArgumentException("initialisation vector must be the same length as block size");
+ }
+
+ Array.Copy(iv, 0, IV, 0, iv.Length);
+
+ parameters = ivParam.Parameters;
+ }
+
+ Reset();
+
+ // if null it's an IV changed only.
+ if (parameters != null)
+ {
+ cipher.Init(encrypting, parameters);
+ }
+ else if (oldEncrypting != encrypting)
+ {
+ throw new ArgumentException("cannot change encrypting state without providing key.");
+ }
+ }
+
+ /**
+ * return the algorithm name and mode.
+ *
+ * @return the name of the underlying algorithm followed by "/CBC".
+ */
+ public string AlgorithmName
+ {
+ get { return cipher.AlgorithmName + "/CBC"; }
+ }
+
+ public bool IsPartialBlockOkay
+ {
+ get { return false; }
+ }
+
+ /**
+ * return the block size of the underlying cipher.
+ *
+ * @return the block size of the underlying cipher.
+ */
+ public int GetBlockSize()
+ {
+ return cipher.GetBlockSize();
+ }
+
+ /**
+ * Process one block of input from the array in and write it to
+ * the out array.
+ *
+ * @param in the array containing the input data.
+ * @param inOff offset into the in array the data starts at.
+ * @param out the array the output data will be copied into.
+ * @param outOff the offset into the out array the output will start at.
+ * @exception DataLengthException if there isn't enough data in in, or
+ * space in out.
+ * @exception InvalidOperationException if the cipher isn't initialised.
+ * @return the number of bytes processed and produced.
+ */
+ public int ProcessBlock(
+ byte[] input,
+ int inOff,
+ byte[] output,
+ int outOff)
+ {
+ return (encrypting)
+ ? EncryptBlock(input, inOff, output, outOff)
+ : DecryptBlock(input, inOff, output, outOff);
+ }
+
+ /**
+ * reset the chaining vector back to the IV and reset the underlying
+ * cipher.
+ */
+ public void Reset()
+ {
+ Array.Copy(IV, 0, cbcV, 0, IV.Length);
+ Array.Clear(cbcNextV, 0, cbcNextV.Length);
+
+ cipher.Reset();
+ }
+
+ /**
+ * Do the appropriate chaining step for CBC mode encryption.
+ *
+ * @param in the array containing the data to be encrypted.
+ * @param inOff offset into the in array the data starts at.
+ * @param out the array the encrypted data will be copied into.
+ * @param outOff the offset into the out array the output will start at.
+ * @exception DataLengthException if there isn't enough data in in, or
+ * space in out.
+ * @exception InvalidOperationException if the cipher isn't initialised.
+ * @return the number of bytes processed and produced.
+ */
+ private int EncryptBlock(
+ byte[] input,
+ int inOff,
+ byte[] outBytes,
+ int outOff)
+ {
+ if ((inOff + blockSize) > input.Length)
+ {
+ throw new DataLengthException("input buffer too short");
+ }
+
+ /*
+ * XOR the cbcV and the input,
+ * then encrypt the cbcV
+ */
+ for (int i = 0; i < blockSize; i++)
+ {
+ cbcV[i] ^= input[inOff + i];
+ }
+
+ int length = cipher.ProcessBlock(cbcV, 0, outBytes, outOff);
+
+ /*
+ * copy ciphertext to cbcV
+ */
+ Array.Copy(outBytes, outOff, cbcV, 0, cbcV.Length);
+
+ return length;
+ }
+
+ /**
+ * Do the appropriate chaining step for CBC mode decryption.
+ *
+ * @param in the array containing the data to be decrypted.
+ * @param inOff offset into the in array the data starts at.
+ * @param out the array the decrypted data will be copied into.
+ * @param outOff the offset into the out array the output will start at.
+ * @exception DataLengthException if there isn't enough data in in, or
+ * space in out.
+ * @exception InvalidOperationException if the cipher isn't initialised.
+ * @return the number of bytes processed and produced.
+ */
+ private int DecryptBlock(
+ byte[] input,
+ int inOff,
+ byte[] outBytes,
+ int outOff)
+ {
+ if ((inOff + blockSize) > input.Length)
+ {
+ throw new DataLengthException("input buffer too short");
+ }
+
+ Array.Copy(input, inOff, cbcNextV, 0, blockSize);
+
+ int length = cipher.ProcessBlock(input, inOff, outBytes, outOff);
+
+ /*
+ * XOR the cbcV and the output
+ */
+ for (int i = 0; i < blockSize; i++)
+ {
+ outBytes[outOff + i] ^= cbcV[i];
+ }
+
+ /*
+ * swap the back up buffer into next position
+ */
+ byte[] tmp;
+
+ tmp = cbcV;
+ cbcV = cbcNextV;
+ cbcNextV = tmp;
+
+ return length;
+ }
+ }
+
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/CbcBlockCipher.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/CbcBlockCipher.cs.meta
new file mode 100644
index 00000000..723b50a6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/CbcBlockCipher.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 3831153ecb36bcf4ba6723fbb3b02484
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/CcmBlockCipher.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/CcmBlockCipher.cs
new file mode 100644
index 00000000..c07163d3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/CcmBlockCipher.cs
@@ -0,0 +1,451 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes
+{
+ /**
+ * Implements the Counter with Cipher Block Chaining mode (CCM) detailed in
+ * NIST Special Publication 800-38C.
+ *
+ * Note: this mode is a packet mode - it needs all the data up front.
+ *
+ */
+ public class CcmBlockCipher
+ : IAeadBlockCipher
+ {
+ private static readonly int BlockSize = 16;
+
+ private readonly IBlockCipher cipher;
+ private readonly byte[] macBlock;
+ private bool forEncryption;
+ private byte[] nonce;
+ private byte[] initialAssociatedText;
+ private int macSize;
+ private ICipherParameters keyParam;
+ private readonly MemoryStream associatedText = new MemoryStream();
+ private readonly MemoryStream data = new MemoryStream();
+
+ /**
+ * Basic constructor.
+ *
+ * @param cipher the block cipher to be used.
+ */
+ public CcmBlockCipher(
+ IBlockCipher cipher)
+ {
+ this.cipher = cipher;
+ this.macBlock = new byte[BlockSize];
+
+ if (cipher.GetBlockSize() != BlockSize)
+ throw new ArgumentException("cipher required with a block size of " + BlockSize + ".");
+ }
+
+ /**
+ * return the underlying block cipher that we are wrapping.
+ *
+ * @return the underlying block cipher that we are wrapping.
+ */
+ public virtual IBlockCipher GetUnderlyingCipher()
+ {
+ return cipher;
+ }
+
+ public virtual void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ this.forEncryption = forEncryption;
+
+ ICipherParameters cipherParameters;
+ if (parameters is AeadParameters)
+ {
+ AeadParameters param = (AeadParameters) parameters;
+
+ nonce = param.GetNonce();
+ initialAssociatedText = param.GetAssociatedText();
+ macSize = param.MacSize / 8;
+ cipherParameters = param.Key;
+ }
+ else if (parameters is ParametersWithIV)
+ {
+ ParametersWithIV param = (ParametersWithIV) parameters;
+
+ nonce = param.GetIV();
+ initialAssociatedText = null;
+ macSize = macBlock.Length / 2;
+ cipherParameters = param.Parameters;
+ }
+ else
+ {
+ throw new ArgumentException("invalid parameters passed to CCM");
+ }
+
+ // NOTE: Very basic support for key re-use, but no performance gain from it
+ if (cipherParameters != null)
+ {
+ keyParam = cipherParameters;
+ }
+
+ if (nonce == null || nonce.Length < 7 || nonce.Length > 13)
+ throw new ArgumentException("nonce must have length from 7 to 13 octets");
+
+ Reset();
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return cipher.AlgorithmName + "/CCM"; }
+ }
+
+ public virtual int GetBlockSize()
+ {
+ return cipher.GetBlockSize();
+ }
+
+ public virtual void ProcessAadByte(byte input)
+ {
+ associatedText.WriteByte(input);
+ }
+
+ public virtual void ProcessAadBytes(byte[] inBytes, int inOff, int len)
+ {
+ // TODO: Process AAD online
+ associatedText.Write(inBytes, inOff, len);
+ }
+
+ public virtual int ProcessByte(
+ byte input,
+ byte[] outBytes,
+ int outOff)
+ {
+ data.WriteByte(input);
+
+ return 0;
+ }
+
+ public virtual int ProcessBytes(
+ byte[] inBytes,
+ int inOff,
+ int inLen,
+ byte[] outBytes,
+ int outOff)
+ {
+ Check.DataLength(inBytes, inOff, inLen, "Input buffer too short");
+
+ data.Write(inBytes, inOff, inLen);
+
+ return 0;
+ }
+
+ public virtual int DoFinal(
+ byte[] outBytes,
+ int outOff)
+ {
+#if PORTABLE || NETFX_CORE
+ byte[] input = data.ToArray();
+ int inLen = input.Length;
+#else
+ byte[] input = data.GetBuffer();
+ int inLen = (int)data.Position;
+#endif
+
+ int len = ProcessPacket(input, 0, inLen, outBytes, outOff);
+
+ Reset();
+
+ return len;
+ }
+
+ public virtual void Reset()
+ {
+ cipher.Reset();
+ associatedText.SetLength(0);
+ data.SetLength(0);
+ }
+
+ /**
+ * Returns a byte array containing the mac calculated as part of the
+ * last encrypt or decrypt operation.
+ *
+ * @return the last mac calculated.
+ */
+ public virtual byte[] GetMac()
+ {
+ return Arrays.CopyOfRange(macBlock, 0, macSize);
+ }
+
+ public virtual int GetUpdateOutputSize(
+ int len)
+ {
+ return 0;
+ }
+
+ public virtual int GetOutputSize(
+ int len)
+ {
+ int totalData = (int)data.Length + len;
+
+ if (forEncryption)
+ {
+ return totalData + macSize;
+ }
+
+ return totalData < macSize ? 0 : totalData - macSize;
+ }
+
+ /**
+ * Process a packet of data for either CCM decryption or encryption.
+ *
+ * @param in data for processing.
+ * @param inOff offset at which data starts in the input array.
+ * @param inLen length of the data in the input array.
+ * @return a byte array containing the processed input..
+ * @throws IllegalStateException if the cipher is not appropriately set up.
+ * @throws InvalidCipherTextException if the input data is truncated or the mac check fails.
+ */
+ public virtual byte[] ProcessPacket(byte[] input, int inOff, int inLen)
+ {
+ byte[] output;
+
+ if (forEncryption)
+ {
+ output = new byte[inLen + macSize];
+ }
+ else
+ {
+ if (inLen < macSize)
+ throw new InvalidCipherTextException("data too short");
+
+ output = new byte[inLen - macSize];
+ }
+
+ ProcessPacket(input, inOff, inLen, output, 0);
+
+ return output;
+ }
+
+ /**
+ * Process a packet of data for either CCM decryption or encryption.
+ *
+ * @param in data for processing.
+ * @param inOff offset at which data starts in the input array.
+ * @param inLen length of the data in the input array.
+ * @param output output array.
+ * @param outOff offset into output array to start putting processed bytes.
+ * @return the number of bytes added to output.
+ * @throws IllegalStateException if the cipher is not appropriately set up.
+ * @throws InvalidCipherTextException if the input data is truncated or the mac check fails.
+ * @throws DataLengthException if output buffer too short.
+ */
+ public virtual int ProcessPacket(byte[] input, int inOff, int inLen, byte[] output, int outOff)
+ {
+ // TODO: handle null keyParam (e.g. via RepeatedKeySpec)
+ // Need to keep the CTR and CBC Mac parts around and reset
+ if (keyParam == null)
+ throw new InvalidOperationException("CCM cipher unitialized.");
+
+ int n = nonce.Length;
+ int q = 15 - n;
+ if (q < 4)
+ {
+ int limitLen = 1 << (8 * q);
+ if (inLen >= limitLen)
+ throw new InvalidOperationException("CCM packet too large for choice of q.");
+ }
+
+ byte[] iv = new byte[BlockSize];
+ iv[0] = (byte)((q - 1) & 0x7);
+ nonce.CopyTo(iv, 1);
+
+ IBlockCipher ctrCipher = new SicBlockCipher(cipher);
+ ctrCipher.Init(forEncryption, new ParametersWithIV(keyParam, iv));
+
+ int outputLen;
+ int inIndex = inOff;
+ int outIndex = outOff;
+
+ if (forEncryption)
+ {
+ outputLen = inLen + macSize;
+ Check.OutputLength(output, outOff, outputLen, "Output buffer too short.");
+
+ CalculateMac(input, inOff, inLen, macBlock);
+
+ byte[] encMac = new byte[BlockSize];
+ ctrCipher.ProcessBlock(macBlock, 0, encMac, 0); // S0
+
+ while (inIndex < (inOff + inLen - BlockSize)) // S1...
+ {
+ ctrCipher.ProcessBlock(input, inIndex, output, outIndex);
+ outIndex += BlockSize;
+ inIndex += BlockSize;
+ }
+
+ byte[] block = new byte[BlockSize];
+
+ Array.Copy(input, inIndex, block, 0, inLen + inOff - inIndex);
+
+ ctrCipher.ProcessBlock(block, 0, block, 0);
+
+ Array.Copy(block, 0, output, outIndex, inLen + inOff - inIndex);
+
+ Array.Copy(encMac, 0, output, outOff + inLen, macSize);
+ }
+ else
+ {
+ if (inLen < macSize)
+ throw new InvalidCipherTextException("data too short");
+
+ outputLen = inLen - macSize;
+ Check.OutputLength(output, outOff, outputLen, "Output buffer too short.");
+
+ Array.Copy(input, inOff + outputLen, macBlock, 0, macSize);
+
+ ctrCipher.ProcessBlock(macBlock, 0, macBlock, 0);
+
+ for (int i = macSize; i != macBlock.Length; i++)
+ {
+ macBlock[i] = 0;
+ }
+
+ while (inIndex < (inOff + outputLen - BlockSize))
+ {
+ ctrCipher.ProcessBlock(input, inIndex, output, outIndex);
+ outIndex += BlockSize;
+ inIndex += BlockSize;
+ }
+
+ byte[] block = new byte[BlockSize];
+
+ Array.Copy(input, inIndex, block, 0, outputLen - (inIndex - inOff));
+
+ ctrCipher.ProcessBlock(block, 0, block, 0);
+
+ Array.Copy(block, 0, output, outIndex, outputLen - (inIndex - inOff));
+
+ byte[] calculatedMacBlock = new byte[BlockSize];
+
+ CalculateMac(output, outOff, outputLen, calculatedMacBlock);
+
+ if (!Arrays.ConstantTimeAreEqual(macBlock, calculatedMacBlock))
+ throw new InvalidCipherTextException("mac check in CCM failed");
+ }
+
+ return outputLen;
+ }
+
+ private int CalculateMac(byte[] data, int dataOff, int dataLen, byte[] macBlock)
+ {
+ IMac cMac = new CbcBlockCipherMac(cipher, macSize * 8);
+
+ cMac.Init(keyParam);
+
+ //
+ // build b0
+ //
+ byte[] b0 = new byte[16];
+
+ if (HasAssociatedText())
+ {
+ b0[0] |= 0x40;
+ }
+
+ b0[0] |= (byte)((((cMac.GetMacSize() - 2) / 2) & 0x7) << 3);
+
+ b0[0] |= (byte)(((15 - nonce.Length) - 1) & 0x7);
+
+ Array.Copy(nonce, 0, b0, 1, nonce.Length);
+
+ int q = dataLen;
+ int count = 1;
+ while (q > 0)
+ {
+ b0[b0.Length - count] = (byte)(q & 0xff);
+ q >>= 8;
+ count++;
+ }
+
+ cMac.BlockUpdate(b0, 0, b0.Length);
+
+ //
+ // process associated text
+ //
+ if (HasAssociatedText())
+ {
+ int extra;
+
+ int textLength = GetAssociatedTextLength();
+ if (textLength < ((1 << 16) - (1 << 8)))
+ {
+ cMac.Update((byte)(textLength >> 8));
+ cMac.Update((byte)textLength);
+
+ extra = 2;
+ }
+ else // can't go any higher than 2^32
+ {
+ cMac.Update((byte)0xff);
+ cMac.Update((byte)0xfe);
+ cMac.Update((byte)(textLength >> 24));
+ cMac.Update((byte)(textLength >> 16));
+ cMac.Update((byte)(textLength >> 8));
+ cMac.Update((byte)textLength);
+
+ extra = 6;
+ }
+
+ if (initialAssociatedText != null)
+ {
+ cMac.BlockUpdate(initialAssociatedText, 0, initialAssociatedText.Length);
+ }
+ if (associatedText.Position > 0)
+ {
+#if PORTABLE || NETFX_CORE
+ byte[] input = associatedText.ToArray();
+ int len = input.Length;
+#else
+ byte[] input = associatedText.GetBuffer();
+ int len = (int)associatedText.Position;
+#endif
+
+ cMac.BlockUpdate(input, 0, len);
+ }
+
+ extra = (extra + textLength) % 16;
+ if (extra != 0)
+ {
+ for (int i = extra; i < 16; ++i)
+ {
+ cMac.Update((byte)0x00);
+ }
+ }
+ }
+
+ //
+ // add the text
+ //
+ cMac.BlockUpdate(data, dataOff, dataLen);
+
+ return cMac.DoFinal(macBlock, 0);
+ }
+
+ private int GetAssociatedTextLength()
+ {
+ return (int)associatedText.Length + ((initialAssociatedText == null) ? 0 : initialAssociatedText.Length);
+ }
+
+ private bool HasAssociatedText()
+ {
+ return GetAssociatedTextLength() > 0;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/CcmBlockCipher.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/CcmBlockCipher.cs.meta
new file mode 100644
index 00000000..4f10a308
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/CcmBlockCipher.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: e209f184af83f8f4494a19e8b869a055
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/CfbBlockCipher.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/CfbBlockCipher.cs
new file mode 100644
index 00000000..87249413
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/CfbBlockCipher.cs
@@ -0,0 +1,228 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes
+{
+ /**
+ * implements a Cipher-FeedBack (CFB) mode on top of a simple cipher.
+ */
+ public class CfbBlockCipher
+ : IBlockCipher
+ {
+ private byte[] IV;
+ private byte[] cfbV;
+ private byte[] cfbOutV;
+ private bool encrypting;
+
+ private readonly int blockSize;
+ private readonly IBlockCipher cipher;
+
+ /**
+ * Basic constructor.
+ *
+ * @param cipher the block cipher to be used as the basis of the
+ * feedback mode.
+ * @param blockSize the block size in bits (note: a multiple of 8)
+ */
+ public CfbBlockCipher(
+ IBlockCipher cipher,
+ int bitBlockSize)
+ {
+ this.cipher = cipher;
+ this.blockSize = bitBlockSize / 8;
+ this.IV = new byte[cipher.GetBlockSize()];
+ this.cfbV = new byte[cipher.GetBlockSize()];
+ this.cfbOutV = new byte[cipher.GetBlockSize()];
+ }
+ /**
+ * return the underlying block cipher that we are wrapping.
+ *
+ * @return the underlying block cipher that we are wrapping.
+ */
+ public IBlockCipher GetUnderlyingCipher()
+ {
+ return cipher;
+ }
+ /**
+ * Initialise the cipher and, possibly, the initialisation vector (IV).
+ * If an IV isn't passed as part of the parameter, the IV will be all zeros.
+ * An IV which is too short is handled in FIPS compliant fashion.
+ *
+ * @param forEncryption if true the cipher is initialised for
+ * encryption, if false for decryption.
+ * @param param the key and other data required by the cipher.
+ * @exception ArgumentException if the parameters argument is
+ * inappropriate.
+ */
+ public void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ this.encrypting = forEncryption;
+ if (parameters is ParametersWithIV)
+ {
+ ParametersWithIV ivParam = (ParametersWithIV) parameters;
+ byte[] iv = ivParam.GetIV();
+ int diff = IV.Length - iv.Length;
+ Array.Copy(iv, 0, IV, diff, iv.Length);
+ Array.Clear(IV, 0, diff);
+
+ parameters = ivParam.Parameters;
+ }
+ Reset();
+
+ // if it's null, key is to be reused.
+ if (parameters != null)
+ {
+ cipher.Init(true, parameters);
+ }
+ }
+
+ /**
+ * return the algorithm name and mode.
+ *
+ * @return the name of the underlying algorithm followed by "/CFB"
+ * and the block size in bits.
+ */
+ public string AlgorithmName
+ {
+ get { return cipher.AlgorithmName + "/CFB" + (blockSize * 8); }
+ }
+
+ public bool IsPartialBlockOkay
+ {
+ get { return true; }
+ }
+
+ /**
+ * return the block size we are operating at.
+ *
+ * @return the block size we are operating at (in bytes).
+ */
+ public int GetBlockSize()
+ {
+ return blockSize;
+ }
+
+ /**
+ * Process one block of input from the array in and write it to
+ * the out array.
+ *
+ * @param in the array containing the input data.
+ * @param inOff offset into the in array the data starts at.
+ * @param out the array the output data will be copied into.
+ * @param outOff the offset into the out array the output will start at.
+ * @exception DataLengthException if there isn't enough data in in, or
+ * space in out.
+ * @exception InvalidOperationException if the cipher isn't initialised.
+ * @return the number of bytes processed and produced.
+ */
+ public int ProcessBlock(
+ byte[] input,
+ int inOff,
+ byte[] output,
+ int outOff)
+ {
+ return (encrypting)
+ ? EncryptBlock(input, inOff, output, outOff)
+ : DecryptBlock(input, inOff, output, outOff);
+ }
+
+ /**
+ * Do the appropriate processing for CFB mode encryption.
+ *
+ * @param in the array containing the data to be encrypted.
+ * @param inOff offset into the in array the data starts at.
+ * @param out the array the encrypted data will be copied into.
+ * @param outOff the offset into the out array the output will start at.
+ * @exception DataLengthException if there isn't enough data in in, or
+ * space in out.
+ * @exception InvalidOperationException if the cipher isn't initialised.
+ * @return the number of bytes processed and produced.
+ */
+ public int EncryptBlock(
+ byte[] input,
+ int inOff,
+ byte[] outBytes,
+ int outOff)
+ {
+ if ((inOff + blockSize) > input.Length)
+ {
+ throw new DataLengthException("input buffer too short");
+ }
+ if ((outOff + blockSize) > outBytes.Length)
+ {
+ throw new DataLengthException("output buffer too short");
+ }
+ cipher.ProcessBlock(cfbV, 0, cfbOutV, 0);
+ //
+ // XOR the cfbV with the plaintext producing the ciphertext
+ //
+ for (int i = 0; i < blockSize; i++)
+ {
+ outBytes[outOff + i] = (byte)(cfbOutV[i] ^ input[inOff + i]);
+ }
+ //
+ // change over the input block.
+ //
+ Array.Copy(cfbV, blockSize, cfbV, 0, cfbV.Length - blockSize);
+ Array.Copy(outBytes, outOff, cfbV, cfbV.Length - blockSize, blockSize);
+ return blockSize;
+ }
+ /**
+ * Do the appropriate processing for CFB mode decryption.
+ *
+ * @param in the array containing the data to be decrypted.
+ * @param inOff offset into the in array the data starts at.
+ * @param out the array the encrypted data will be copied into.
+ * @param outOff the offset into the out array the output will start at.
+ * @exception DataLengthException if there isn't enough data in in, or
+ * space in out.
+ * @exception InvalidOperationException if the cipher isn't initialised.
+ * @return the number of bytes processed and produced.
+ */
+ public int DecryptBlock(
+ byte[] input,
+ int inOff,
+ byte[] outBytes,
+ int outOff)
+ {
+ if ((inOff + blockSize) > input.Length)
+ {
+ throw new DataLengthException("input buffer too short");
+ }
+ if ((outOff + blockSize) > outBytes.Length)
+ {
+ throw new DataLengthException("output buffer too short");
+ }
+ cipher.ProcessBlock(cfbV, 0, cfbOutV, 0);
+ //
+ // change over the input block.
+ //
+ Array.Copy(cfbV, blockSize, cfbV, 0, cfbV.Length - blockSize);
+ Array.Copy(input, inOff, cfbV, cfbV.Length - blockSize, blockSize);
+ //
+ // XOR the cfbV with the ciphertext producing the plaintext
+ //
+ for (int i = 0; i < blockSize; i++)
+ {
+ outBytes[outOff + i] = (byte)(cfbOutV[i] ^ input[inOff + i]);
+ }
+ return blockSize;
+ }
+ /**
+ * reset the chaining vector back to the IV and reset the underlying
+ * cipher.
+ */
+ public void Reset()
+ {
+ Array.Copy(IV, 0, cfbV, 0, IV.Length);
+ cipher.Reset();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/CfbBlockCipher.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/CfbBlockCipher.cs.meta
new file mode 100644
index 00000000..6118b126
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/CfbBlockCipher.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c7ff0cbf4f101654b8f34a6112e42ae3
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/CtsBlockCipher.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/CtsBlockCipher.cs
new file mode 100644
index 00000000..5008ae4a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/CtsBlockCipher.cs
@@ -0,0 +1,257 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Diagnostics;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes
+{
+ /**
+ * A Cipher Text Stealing (CTS) mode cipher. CTS allows block ciphers to
+ * be used to produce cipher text which is the same outLength as the plain text.
+ */
+ public class CtsBlockCipher
+ : BufferedBlockCipher
+ {
+ private readonly int blockSize;
+
+ /**
+ * Create a buffered block cipher that uses Cipher Text Stealing
+ *
+ * @param cipher the underlying block cipher this buffering object wraps.
+ */
+ public CtsBlockCipher(
+ IBlockCipher cipher)
+ {
+ // TODO Should this test for acceptable ones instead?
+ if (cipher is OfbBlockCipher || cipher is CfbBlockCipher)
+ throw new ArgumentException("CtsBlockCipher can only accept ECB, or CBC ciphers");
+
+ this.cipher = cipher;
+
+ blockSize = cipher.GetBlockSize();
+
+ buf = new byte[blockSize * 2];
+ bufOff = 0;
+ }
+
+ /**
+ * return the size of the output buffer required for an update of 'length' bytes.
+ *
+ * @param length the outLength of the input.
+ * @return the space required to accommodate a call to update
+ * with length bytes of input.
+ */
+ public override int GetUpdateOutputSize(
+ int length)
+ {
+ int total = length + bufOff;
+ int leftOver = total % buf.Length;
+
+ if (leftOver == 0)
+ {
+ return total - buf.Length;
+ }
+
+ return total - leftOver;
+ }
+
+ /**
+ * return the size of the output buffer required for an update plus a
+ * doFinal with an input of length bytes.
+ *
+ * @param length the outLength of the input.
+ * @return the space required to accommodate a call to update and doFinal
+ * with length bytes of input.
+ */
+ public override int GetOutputSize(
+ int length)
+ {
+ return length + bufOff;
+ }
+
+ /**
+ * process a single byte, producing an output block if necessary.
+ *
+ * @param in the input byte.
+ * @param out the space for any output that might be produced.
+ * @param outOff the offset from which the output will be copied.
+ * @return the number of output bytes copied to out.
+ * @exception DataLengthException if there isn't enough space in out.
+ * @exception InvalidOperationException if the cipher isn't initialised.
+ */
+ public override int ProcessByte(
+ byte input,
+ byte[] output,
+ int outOff)
+ {
+ int resultLen = 0;
+
+ if (bufOff == buf.Length)
+ {
+ resultLen = cipher.ProcessBlock(buf, 0, output, outOff);
+ Debug.Assert(resultLen == blockSize);
+
+ Array.Copy(buf, blockSize, buf, 0, blockSize);
+ bufOff = blockSize;
+ }
+
+ buf[bufOff++] = input;
+
+ return resultLen;
+ }
+
+ /**
+ * process an array of bytes, producing output if necessary.
+ *
+ * @param in the input byte array.
+ * @param inOff the offset at which the input data starts.
+ * @param length the number of bytes to be copied out of the input array.
+ * @param out the space for any output that might be produced.
+ * @param outOff the offset from which the output will be copied.
+ * @return the number of output bytes copied to out.
+ * @exception DataLengthException if there isn't enough space in out.
+ * @exception InvalidOperationException if the cipher isn't initialised.
+ */
+ public override int ProcessBytes(
+ byte[] input,
+ int inOff,
+ int length,
+ byte[] output,
+ int outOff)
+ {
+ if (length < 0)
+ {
+ throw new ArgumentException("Can't have a negative input outLength!");
+ }
+
+ int blockSize = GetBlockSize();
+ int outLength = GetUpdateOutputSize(length);
+
+ if (outLength > 0)
+ {
+ if ((outOff + outLength) > output.Length)
+ {
+ throw new DataLengthException("output buffer too short");
+ }
+ }
+
+ int resultLen = 0;
+ int gapLen = buf.Length - bufOff;
+
+ if (length > gapLen)
+ {
+ Array.Copy(input, inOff, buf, bufOff, gapLen);
+
+ resultLen += cipher.ProcessBlock(buf, 0, output, outOff);
+ Array.Copy(buf, blockSize, buf, 0, blockSize);
+
+ bufOff = blockSize;
+
+ length -= gapLen;
+ inOff += gapLen;
+
+ while (length > blockSize)
+ {
+ Array.Copy(input, inOff, buf, bufOff, blockSize);
+ resultLen += cipher.ProcessBlock(buf, 0, output, outOff + resultLen);
+ Array.Copy(buf, blockSize, buf, 0, blockSize);
+
+ length -= blockSize;
+ inOff += blockSize;
+ }
+ }
+
+ Array.Copy(input, inOff, buf, bufOff, length);
+
+ bufOff += length;
+
+ return resultLen;
+ }
+
+ /**
+ * Process the last block in the buffer.
+ *
+ * @param out the array the block currently being held is copied into.
+ * @param outOff the offset at which the copying starts.
+ * @return the number of output bytes copied to out.
+ * @exception DataLengthException if there is insufficient space in out for
+ * the output.
+ * @exception InvalidOperationException if the underlying cipher is not
+ * initialised.
+ * @exception InvalidCipherTextException if cipher text decrypts wrongly (in
+ * case the exception will never Get thrown).
+ */
+ public override int DoFinal(
+ byte[] output,
+ int outOff)
+ {
+ if (bufOff + outOff > output.Length)
+ {
+ throw new DataLengthException("output buffer too small in doFinal");
+ }
+
+ int blockSize = cipher.GetBlockSize();
+ int length = bufOff - blockSize;
+ byte[] block = new byte[blockSize];
+
+ if (forEncryption)
+ {
+ cipher.ProcessBlock(buf, 0, block, 0);
+
+ if (bufOff < blockSize)
+ {
+ throw new DataLengthException("need at least one block of input for CTS");
+ }
+
+ for (int i = bufOff; i != buf.Length; i++)
+ {
+ buf[i] = block[i - blockSize];
+ }
+
+ for (int i = blockSize; i != bufOff; i++)
+ {
+ buf[i] ^= block[i - blockSize];
+ }
+
+ IBlockCipher c = (cipher is CbcBlockCipher)
+ ? ((CbcBlockCipher)cipher).GetUnderlyingCipher()
+ : cipher;
+
+ c.ProcessBlock(buf, blockSize, output, outOff);
+
+ Array.Copy(block, 0, output, outOff + blockSize, length);
+ }
+ else
+ {
+ byte[] lastBlock = new byte[blockSize];
+
+ IBlockCipher c = (cipher is CbcBlockCipher)
+ ? ((CbcBlockCipher)cipher).GetUnderlyingCipher()
+ : cipher;
+
+ c.ProcessBlock(buf, 0, block, 0);
+
+ for (int i = blockSize; i != bufOff; i++)
+ {
+ lastBlock[i - blockSize] = (byte)(block[i - blockSize] ^ buf[i]);
+ }
+
+ Array.Copy(buf, blockSize, block, 0, length);
+
+ cipher.ProcessBlock(block, 0, output, outOff);
+ Array.Copy(lastBlock, 0, output, outOff + blockSize, length);
+ }
+
+ int offset = bufOff;
+
+ Reset();
+
+ return offset;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/CtsBlockCipher.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/CtsBlockCipher.cs.meta
new file mode 100644
index 00000000..282052a2
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/CtsBlockCipher.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: d853fe439c7b3cd42be0ebc115faebc1
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/EAXBlockCipher.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/EAXBlockCipher.cs
new file mode 100644
index 00000000..966b4cb2
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/EAXBlockCipher.cs
@@ -0,0 +1,383 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes
+{
+ /**
+ * A Two-Pass Authenticated-Encryption Scheme Optimized for Simplicity and
+ * Efficiency - by M. Bellare, P. Rogaway, D. Wagner.
+ *
+ * http://www.cs.ucdavis.edu/~rogaway/papers/eax.pdf
+ *
+ * EAX is an AEAD scheme based on CTR and OMAC1/CMAC, that uses a single block
+ * cipher to encrypt and authenticate data. It's on-line (the length of a
+ * message isn't needed to begin processing it), has good performances, it's
+ * simple and provably secure (provided the underlying block cipher is secure).
+ *
+ * Of course, this implementations is NOT thread-safe.
+ */
+ public class EaxBlockCipher
+ : IAeadBlockCipher
+ {
+ private enum Tag : byte { N, H, C };
+
+ private SicBlockCipher cipher;
+
+ private bool forEncryption;
+
+ private int blockSize;
+
+ private IMac mac;
+
+ private byte[] nonceMac;
+ private byte[] associatedTextMac;
+ private byte[] macBlock;
+
+ private int macSize;
+ private byte[] bufBlock;
+ private int bufOff;
+
+ private bool cipherInitialized;
+ private byte[] initialAssociatedText;
+
+ /**
+ * Constructor that accepts an instance of a block cipher engine.
+ *
+ * @param cipher the engine to use
+ */
+ public EaxBlockCipher(
+ IBlockCipher cipher)
+ {
+ blockSize = cipher.GetBlockSize();
+ mac = new CMac(cipher);
+ macBlock = new byte[blockSize];
+ associatedTextMac = new byte[mac.GetMacSize()];
+ nonceMac = new byte[mac.GetMacSize()];
+ this.cipher = new SicBlockCipher(cipher);
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return cipher.GetUnderlyingCipher().AlgorithmName + "/EAX"; }
+ }
+
+ public virtual IBlockCipher GetUnderlyingCipher()
+ {
+ return cipher;
+ }
+
+ public virtual int GetBlockSize()
+ {
+ return cipher.GetBlockSize();
+ }
+
+ public virtual void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ this.forEncryption = forEncryption;
+
+ byte[] nonce;
+ ICipherParameters keyParam;
+
+ if (parameters is AeadParameters)
+ {
+ AeadParameters param = (AeadParameters) parameters;
+
+ nonce = param.GetNonce();
+ initialAssociatedText = param.GetAssociatedText();
+ macSize = param.MacSize / 8;
+ keyParam = param.Key;
+ }
+ else if (parameters is ParametersWithIV)
+ {
+ ParametersWithIV param = (ParametersWithIV) parameters;
+
+ nonce = param.GetIV();
+ initialAssociatedText = null;
+ macSize = mac.GetMacSize() / 2;
+ keyParam = param.Parameters;
+ }
+ else
+ {
+ throw new ArgumentException("invalid parameters passed to EAX");
+ }
+
+ bufBlock = new byte[forEncryption ? blockSize : (blockSize + macSize)];
+
+ byte[] tag = new byte[blockSize];
+
+ // Key reuse implemented in CBC mode of underlying CMac
+ mac.Init(keyParam);
+
+ tag[blockSize - 1] = (byte)Tag.N;
+ mac.BlockUpdate(tag, 0, blockSize);
+ mac.BlockUpdate(nonce, 0, nonce.Length);
+ mac.DoFinal(nonceMac, 0);
+
+ // Same BlockCipher underlies this and the mac, so reuse last key on cipher
+ cipher.Init(true, new ParametersWithIV(null, nonceMac));
+
+ Reset();
+ }
+
+ private void InitCipher()
+ {
+ if (cipherInitialized)
+ {
+ return;
+ }
+
+ cipherInitialized = true;
+
+ mac.DoFinal(associatedTextMac, 0);
+
+ byte[] tag = new byte[blockSize];
+ tag[blockSize - 1] = (byte)Tag.C;
+ mac.BlockUpdate(tag, 0, blockSize);
+ }
+
+ private void CalculateMac()
+ {
+ byte[] outC = new byte[blockSize];
+ mac.DoFinal(outC, 0);
+
+ for (int i = 0; i < macBlock.Length; i++)
+ {
+ macBlock[i] = (byte)(nonceMac[i] ^ associatedTextMac[i] ^ outC[i]);
+ }
+ }
+
+ public virtual void Reset()
+ {
+ Reset(true);
+ }
+
+ private void Reset(
+ bool clearMac)
+ {
+ cipher.Reset(); // TODO Redundant since the mac will reset it?
+ mac.Reset();
+
+ bufOff = 0;
+ Array.Clear(bufBlock, 0, bufBlock.Length);
+
+ if (clearMac)
+ {
+ Array.Clear(macBlock, 0, macBlock.Length);
+ }
+
+ byte[] tag = new byte[blockSize];
+ tag[blockSize - 1] = (byte)Tag.H;
+ mac.BlockUpdate(tag, 0, blockSize);
+
+ cipherInitialized = false;
+
+ if (initialAssociatedText != null)
+ {
+ ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length);
+ }
+ }
+
+ public virtual void ProcessAadByte(byte input)
+ {
+ if (cipherInitialized)
+ {
+ throw new InvalidOperationException("AAD data cannot be added after encryption/decryption processing has begun.");
+ }
+ mac.Update(input);
+ }
+
+ public virtual void ProcessAadBytes(byte[] inBytes, int inOff, int len)
+ {
+ if (cipherInitialized)
+ {
+ throw new InvalidOperationException("AAD data cannot be added after encryption/decryption processing has begun.");
+ }
+ mac.BlockUpdate(inBytes, inOff, len);
+ }
+
+ public virtual int ProcessByte(
+ byte input,
+ byte[] outBytes,
+ int outOff)
+ {
+ InitCipher();
+
+ return Process(input, outBytes, outOff);
+ }
+
+ public virtual int ProcessBytes(
+ byte[] inBytes,
+ int inOff,
+ int len,
+ byte[] outBytes,
+ int outOff)
+ {
+ InitCipher();
+
+ int resultLen = 0;
+
+ for (int i = 0; i != len; i++)
+ {
+ resultLen += Process(inBytes[inOff + i], outBytes, outOff + resultLen);
+ }
+
+ return resultLen;
+ }
+
+ public virtual int DoFinal(
+ byte[] outBytes,
+ int outOff)
+ {
+ InitCipher();
+
+ int extra = bufOff;
+ byte[] tmp = new byte[bufBlock.Length];
+
+ bufOff = 0;
+
+ if (forEncryption)
+ {
+ Check.OutputLength(outBytes, outOff, extra + macSize, "Output buffer too short");
+
+ cipher.ProcessBlock(bufBlock, 0, tmp, 0);
+
+ Array.Copy(tmp, 0, outBytes, outOff, extra);
+
+ mac.BlockUpdate(tmp, 0, extra);
+
+ CalculateMac();
+
+ Array.Copy(macBlock, 0, outBytes, outOff + extra, macSize);
+
+ Reset(false);
+
+ return extra + macSize;
+ }
+ else
+ {
+ if (extra < macSize)
+ throw new InvalidCipherTextException("data too short");
+
+ Check.OutputLength(outBytes, outOff, extra - macSize, "Output buffer too short");
+
+ if (extra > macSize)
+ {
+ mac.BlockUpdate(bufBlock, 0, extra - macSize);
+
+ cipher.ProcessBlock(bufBlock, 0, tmp, 0);
+
+ Array.Copy(tmp, 0, outBytes, outOff, extra - macSize);
+ }
+
+ CalculateMac();
+
+ if (!VerifyMac(bufBlock, extra - macSize))
+ throw new InvalidCipherTextException("mac check in EAX failed");
+
+ Reset(false);
+
+ return extra - macSize;
+ }
+ }
+
+ public virtual byte[] GetMac()
+ {
+ byte[] mac = new byte[macSize];
+
+ Array.Copy(macBlock, 0, mac, 0, macSize);
+
+ return mac;
+ }
+
+ public virtual int GetUpdateOutputSize(
+ int len)
+ {
+ int totalData = len + bufOff;
+ if (!forEncryption)
+ {
+ if (totalData < macSize)
+ {
+ return 0;
+ }
+ totalData -= macSize;
+ }
+ return totalData - totalData % blockSize;
+ }
+
+ public virtual int GetOutputSize(
+ int len)
+ {
+ int totalData = len + bufOff;
+
+ if (forEncryption)
+ {
+ return totalData + macSize;
+ }
+
+ return totalData < macSize ? 0 : totalData - macSize;
+ }
+
+ private int Process(
+ byte b,
+ byte[] outBytes,
+ int outOff)
+ {
+ bufBlock[bufOff++] = b;
+
+ if (bufOff == bufBlock.Length)
+ {
+ Check.OutputLength(outBytes, outOff, blockSize, "Output buffer is too short");
+
+ // TODO Could move the ProcessByte(s) calls to here
+// InitCipher();
+
+ int size;
+
+ if (forEncryption)
+ {
+ size = cipher.ProcessBlock(bufBlock, 0, outBytes, outOff);
+
+ mac.BlockUpdate(outBytes, outOff, blockSize);
+ }
+ else
+ {
+ mac.BlockUpdate(bufBlock, 0, blockSize);
+
+ size = cipher.ProcessBlock(bufBlock, 0, outBytes, outOff);
+ }
+
+ bufOff = 0;
+ if (!forEncryption)
+ {
+ Array.Copy(bufBlock, blockSize, bufBlock, 0, macSize);
+ bufOff = macSize;
+ }
+
+ return size;
+ }
+
+ return 0;
+ }
+
+ private bool VerifyMac(byte[] mac, int off)
+ {
+ int nonEqual = 0;
+
+ for (int i = 0; i < macSize; i++)
+ {
+ nonEqual |= (macBlock[i] ^ mac[off + i]);
+ }
+
+ return nonEqual == 0;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/EAXBlockCipher.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/EAXBlockCipher.cs.meta
new file mode 100644
index 00000000..bcc886ad
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/EAXBlockCipher.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 56a798d87f3f7d741b9de7bff3c6622e
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/GCMBlockCipher.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/GCMBlockCipher.cs
new file mode 100644
index 00000000..5df264dc
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/GCMBlockCipher.cs
@@ -0,0 +1,651 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes.Gcm;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes
+{
+ ///
+ /// Implements the Galois/Counter mode (GCM) detailed in
+ /// NIST Special Publication 800-38D.
+ ///
+ public sealed class GcmBlockCipher
+ : IAeadBlockCipher
+ {
+ private const int BlockSize = 16;
+ byte[] ctrBlock = new byte[BlockSize];
+
+ private readonly IBlockCipher cipher;
+ private readonly IGcmMultiplier multiplier;
+ private IGcmExponentiator exp;
+
+ // These fields are set by Init and not modified by processing
+ private bool forEncryption;
+ private bool initialised;
+ private int macSize;
+ private byte[] lastKey;
+ private byte[] nonce;
+ private byte[] initialAssociatedText;
+ private byte[] H;
+ private byte[] J0;
+
+ // These fields are modified during processing
+ private byte[] bufBlock;
+ private byte[] macBlock;
+ private byte[] S, S_at, S_atPre;
+ private byte[] counter;
+ private uint blocksRemaining;
+ private int bufOff;
+ private ulong totalLength;
+ private byte[] atBlock;
+ private int atBlockPos;
+ private ulong atLength;
+ private ulong atLengthPre;
+
+ public GcmBlockCipher(
+ IBlockCipher c)
+ : this(c, null)
+ {
+ }
+
+ public GcmBlockCipher(
+ IBlockCipher c,
+ IGcmMultiplier m)
+ {
+ if (c.GetBlockSize() != BlockSize)
+ throw new ArgumentException("cipher required with a block size of " + BlockSize + ".");
+
+ if (m == null)
+ {
+ // TODO Consider a static property specifying default multiplier
+ m = new Tables8kGcmMultiplier();
+ }
+
+ this.cipher = c;
+ this.multiplier = m;
+ }
+
+ public /*virtual*/ string AlgorithmName
+ {
+ get { return cipher.AlgorithmName + "/GCM"; }
+ }
+
+ public IBlockCipher GetUnderlyingCipher()
+ {
+ return cipher;
+ }
+
+ public /*virtual*/ int GetBlockSize()
+ {
+ return BlockSize;
+ }
+
+ ///
+ /// MAC sizes from 32 bits to 128 bits (must be a multiple of 8) are supported. The default is 128 bits.
+ /// Sizes less than 96 are not recommended, but are supported for specialized applications.
+ ///
+ public /*virtual*/ void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ this.forEncryption = forEncryption;
+ this.macBlock = null;
+ this.initialised = true;
+
+ KeyParameter keyParam;
+ byte[] newNonce = null;
+
+ if (parameters is AeadParameters)
+ {
+ AeadParameters param = (AeadParameters)parameters;
+
+ newNonce = param.GetNonce();
+ initialAssociatedText = param.GetAssociatedText();
+
+ int macSizeBits = param.MacSize;
+ if (macSizeBits < 32 || macSizeBits > 128 || macSizeBits % 8 != 0)
+ {
+ throw new ArgumentException("Invalid value for MAC size: " + macSizeBits);
+ }
+
+ macSize = macSizeBits / 8;
+ keyParam = param.Key;
+ }
+ else if (parameters is ParametersWithIV)
+ {
+ ParametersWithIV param = (ParametersWithIV)parameters;
+
+ newNonce = param.GetIV();
+ initialAssociatedText = null;
+ macSize = 16;
+ keyParam = (KeyParameter)param.Parameters;
+ }
+ else
+ {
+ throw new ArgumentException("invalid parameters passed to GCM");
+ }
+
+ int bufLength = forEncryption ? BlockSize : (BlockSize + macSize);
+ this.bufBlock = new byte[bufLength];
+
+ if (newNonce == null || newNonce.Length < 1)
+ {
+ throw new ArgumentException("IV must be at least 1 byte");
+ }
+
+ if (forEncryption)
+ {
+ if (nonce != null && Arrays.AreEqual(nonce, newNonce))
+ {
+ if (keyParam == null)
+ {
+ throw new ArgumentException("cannot reuse nonce for GCM encryption");
+ }
+ if (lastKey != null && Arrays.AreEqual(lastKey, keyParam.GetKey()))
+ {
+ throw new ArgumentException("cannot reuse nonce for GCM encryption");
+ }
+ }
+ }
+
+ nonce = newNonce;
+ if (keyParam != null)
+ {
+ lastKey = keyParam.GetKey();
+ }
+
+ // TODO Restrict macSize to 16 if nonce length not 12?
+
+ // Cipher always used in forward mode
+ // if keyParam is null we're reusing the last key.
+ if (keyParam != null)
+ {
+ cipher.Init(true, keyParam);
+
+ this.H = new byte[BlockSize];
+ cipher.ProcessBlock(H, 0, H, 0);
+
+ // if keyParam is null we're reusing the last key and the multiplier doesn't need re-init
+ multiplier.Init(H);
+ exp = null;
+ }
+ else if (this.H == null)
+ {
+ throw new ArgumentException("Key must be specified in initial init");
+ }
+
+ this.J0 = new byte[BlockSize];
+
+ if (nonce.Length == 12)
+ {
+ Array.Copy(nonce, 0, J0, 0, nonce.Length);
+ this.J0[BlockSize - 1] = 0x01;
+ }
+ else
+ {
+ gHASH(J0, nonce, nonce.Length);
+ byte[] X = new byte[BlockSize];
+ Pack.UInt64_To_BE((ulong)nonce.Length * 8UL, X, 8);
+ gHASHBlock(J0, X);
+ }
+
+ this.S = new byte[BlockSize];
+ this.S_at = new byte[BlockSize];
+ this.S_atPre = new byte[BlockSize];
+ this.atBlock = new byte[BlockSize];
+ this.atBlockPos = 0;
+ this.atLength = 0;
+ this.atLengthPre = 0;
+ this.counter = Arrays.Clone(J0);
+ this.blocksRemaining = uint.MaxValue - 1; // page 8, len(P) <= 2^39 - 256, 1 block used by tag
+ this.bufOff = 0;
+ this.totalLength = 0;
+
+ if (initialAssociatedText != null)
+ {
+ ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length);
+ }
+ }
+
+ public /*virtual*/ byte[] GetMac()
+ {
+ return macBlock == null
+ ? new byte[macSize]
+ : Arrays.Clone(macBlock);
+ }
+
+ public /*virtual*/ int GetOutputSize(
+ int len)
+ {
+ int totalData = len + bufOff;
+
+ if (forEncryption)
+ {
+ return totalData + macSize;
+ }
+
+ return totalData < macSize ? 0 : totalData - macSize;
+ }
+
+ public /*virtual*/ int GetUpdateOutputSize(
+ int len)
+ {
+ int totalData = len + bufOff;
+ if (!forEncryption)
+ {
+ if (totalData < macSize)
+ {
+ return 0;
+ }
+ totalData -= macSize;
+ }
+ return totalData - totalData % BlockSize;
+ }
+
+ public /*virtual*/ void ProcessAadByte(byte input)
+ {
+ CheckStatus();
+
+ atBlock[atBlockPos] = input;
+ if (++atBlockPos == BlockSize)
+ {
+ // Hash each block as it fills
+ gHASHBlock(S_at, atBlock);
+ atBlockPos = 0;
+ atLength += BlockSize;
+ }
+ }
+
+ public /*virtual*/ void ProcessAadBytes(byte[] inBytes, int inOff, int len)
+ {
+ CheckStatus();
+
+ for (int i = 0; i < len; ++i)
+ {
+ atBlock[atBlockPos] = inBytes[inOff + i];
+ if (++atBlockPos == BlockSize)
+ {
+ // Hash each block as it fills
+ gHASHBlock(S_at, atBlock);
+ atBlockPos = 0;
+ atLength += BlockSize;
+ }
+ }
+ }
+
+ private void InitCipher()
+ {
+ if (atLength > 0)
+ {
+ Array.Copy(S_at, 0, S_atPre, 0, BlockSize);
+ atLengthPre = atLength;
+ }
+
+ // Finish hash for partial AAD block
+ if (atBlockPos > 0)
+ {
+ gHASHPartial(S_atPre, atBlock, 0, atBlockPos);
+ atLengthPre += (uint)atBlockPos;
+ }
+
+ if (atLengthPre > 0)
+ {
+ Array.Copy(S_atPre, 0, S, 0, BlockSize);
+ }
+ }
+
+ public /*virtual*/ int ProcessByte(
+ byte input,
+ byte[] output,
+ int outOff)
+ {
+ CheckStatus();
+
+ bufBlock[bufOff] = input;
+ if (++bufOff == bufBlock.Length)
+ {
+ ProcessBlock(bufBlock, 0, output, outOff);
+ if (forEncryption)
+ {
+ bufOff = 0;
+ }
+ else
+ {
+ Array.Copy(bufBlock, BlockSize, bufBlock, 0, macSize);
+ bufOff = macSize;
+ }
+ return BlockSize;
+ }
+ return 0;
+ }
+
+ public /*virtual*/ int ProcessBytes(
+ byte[] input,
+ int inOff,
+ int len,
+ byte[] output,
+ int outOff)
+ {
+ CheckStatus();
+
+ Check.DataLength(input, inOff, len, "input buffer too short");
+
+ int resultLen = 0;
+
+ if (forEncryption)
+ {
+ if (bufOff != 0)
+ {
+ while (len > 0)
+ {
+ --len;
+ bufBlock[bufOff] = input[inOff++];
+ if (++bufOff == BlockSize)
+ {
+ ProcessBlock(bufBlock, 0, output, outOff);
+ bufOff = 0;
+ resultLen += BlockSize;
+ break;
+ }
+ }
+ }
+
+ while (len >= BlockSize)
+ {
+ ProcessBlock(input, inOff, output, outOff + resultLen);
+ inOff += BlockSize;
+ len -= BlockSize;
+ resultLen += BlockSize;
+ }
+
+ if (len > 0)
+ {
+ Array.Copy(input, inOff, bufBlock, 0, len);
+ bufOff = len;
+ }
+ }
+ else
+ {
+ for (int i = 0; i < len; ++i)
+ {
+ bufBlock[bufOff] = input[inOff + i];
+ if (++bufOff == bufBlock.Length)
+ {
+ ProcessBlock(bufBlock, 0, output, outOff + resultLen);
+ Array.Copy(bufBlock, BlockSize, bufBlock, 0, macSize);
+ bufOff = macSize;
+ resultLen += BlockSize;
+ }
+ }
+ }
+
+ return resultLen;
+ }
+
+ public int DoFinal(byte[] output, int outOff)
+ {
+ CheckStatus();
+
+ if (totalLength == 0)
+ {
+ InitCipher();
+ }
+
+ int extra = bufOff;
+
+ if (forEncryption)
+ {
+ Check.OutputLength(output, outOff, extra + macSize, "Output buffer too short");
+ }
+ else
+ {
+ if (extra < macSize)
+ throw new InvalidCipherTextException("data too short");
+
+ extra -= macSize;
+
+ Check.OutputLength(output, outOff, extra, "Output buffer too short");
+ }
+
+ if (extra > 0)
+ {
+ ProcessPartial(bufBlock, 0, extra, output, outOff);
+ }
+
+ atLength += (uint)atBlockPos;
+
+ if (atLength > atLengthPre)
+ {
+ /*
+ * Some AAD was sent after the cipher started. We determine the difference b/w the hash value
+ * we actually used when the cipher started (S_atPre) and the final hash value calculated (S_at).
+ * Then we carry this difference forward by multiplying by H^c, where c is the number of (full or
+ * partial) cipher-text blocks produced, and adjust the current hash.
+ */
+
+ // Finish hash for partial AAD block
+ if (atBlockPos > 0)
+ {
+ gHASHPartial(S_at, atBlock, 0, atBlockPos);
+ }
+
+ // Find the difference between the AAD hashes
+ if (atLengthPre > 0)
+ {
+ GcmUtilities.Xor(S_at, S_atPre);
+ }
+
+ // Number of cipher-text blocks produced
+ long c = (long)(((totalLength * 8) + 127) >> 7);
+
+ // Calculate the adjustment factor
+ byte[] H_c = new byte[16];
+ if (exp == null)
+ {
+ exp = new Tables1kGcmExponentiator();
+ exp.Init(H);
+ }
+ exp.ExponentiateX(c, H_c);
+
+ // Carry the difference forward
+ GcmUtilities.Multiply(S_at, H_c);
+
+ // Adjust the current hash
+ GcmUtilities.Xor(S, S_at);
+ }
+
+ // Final gHASH
+ byte[] X = new byte[BlockSize];
+ Pack.UInt64_To_BE(atLength * 8UL, X, 0);
+ Pack.UInt64_To_BE(totalLength * 8UL, X, 8);
+
+ gHASHBlock(S, X);
+
+ // T = MSBt(GCTRk(J0,S))
+ byte[] tag = new byte[BlockSize];
+ cipher.ProcessBlock(J0, 0, tag, 0);
+ GcmUtilities.Xor(tag, S);
+
+ int resultLen = extra;
+
+ // We place into macBlock our calculated value for T
+ this.macBlock = new byte[macSize];
+ Array.Copy(tag, 0, macBlock, 0, macSize);
+
+ if (forEncryption)
+ {
+ // Append T to the message
+ Array.Copy(macBlock, 0, output, outOff + bufOff, macSize);
+ resultLen += macSize;
+ }
+ else
+ {
+ // Retrieve the T value from the message and compare to calculated one
+ byte[] msgMac = new byte[macSize];
+ Array.Copy(bufBlock, extra, msgMac, 0, macSize);
+ if (!Arrays.ConstantTimeAreEqual(this.macBlock, msgMac))
+ throw new InvalidCipherTextException("mac check in GCM failed");
+ }
+
+ Reset(false);
+
+ return resultLen;
+ }
+
+ public /*virtual*/ void Reset()
+ {
+ Reset(true);
+ }
+
+ private void Reset(
+ bool clearMac)
+ {
+ cipher.Reset();
+
+ // note: we do not reset the nonce.
+
+ S = new byte[BlockSize];
+ S_at = new byte[BlockSize];
+ S_atPre = new byte[BlockSize];
+ atBlock = new byte[BlockSize];
+ atBlockPos = 0;
+ atLength = 0;
+ atLengthPre = 0;
+ counter = Arrays.Clone(J0);
+ blocksRemaining = uint.MaxValue - 1;
+ bufOff = 0;
+ totalLength = 0;
+
+ if (bufBlock != null)
+ {
+ Arrays.Fill(bufBlock, 0);
+ }
+
+ if (clearMac)
+ {
+ macBlock = null;
+ }
+
+ if (forEncryption)
+ {
+ initialised = false;
+ }
+ else
+ {
+ if (initialAssociatedText != null)
+ {
+ ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length);
+ }
+ }
+ }
+
+ private void ProcessBlock(byte[] buf, int bufOff, byte[] output, int outOff)
+ {
+ Check.OutputLength(output, outOff, BlockSize, "Output buffer too short");
+
+ if (totalLength == 0)
+ {
+ InitCipher();
+ }
+
+ //byte[] ctrBlock = new byte[BlockSize];
+ GetNextCtrBlock(ctrBlock);
+
+ if (forEncryption)
+ {
+ GcmUtilities.Xor(ctrBlock, buf, bufOff);
+ gHASHBlock(S, ctrBlock);
+ Array.Copy(ctrBlock, 0, output, outOff, BlockSize);
+ }
+ else
+ {
+ gHASHBlock(S, buf, bufOff);
+ GcmUtilities.Xor(ctrBlock, 0, buf, bufOff, output, outOff);
+ }
+
+ totalLength += BlockSize;
+ }
+
+ private void ProcessPartial(byte[] buf, int off, int len, byte[] output, int outOff)
+ {
+ //byte[] ctrBlock = new byte[BlockSize];
+ GetNextCtrBlock(ctrBlock);
+
+ if (forEncryption)
+ {
+ GcmUtilities.Xor(buf, off, ctrBlock, 0, len);
+ gHASHPartial(S, buf, off, len);
+ }
+ else
+ {
+ gHASHPartial(S, buf, off, len);
+ GcmUtilities.Xor(buf, off, ctrBlock, 0, len);
+ }
+
+ Array.Copy(buf, off, output, outOff, len);
+ totalLength += (uint)len;
+ }
+
+ private void gHASH(byte[] Y, byte[] b, int len)
+ {
+ for (int pos = 0; pos < len; pos += BlockSize)
+ {
+ int num = System.Math.Min(len - pos, BlockSize);
+ gHASHPartial(Y, b, pos, num);
+ }
+ }
+
+ private void gHASHBlock(byte[] Y, byte[] b)
+ {
+ GcmUtilities.Xor(Y, b);
+ multiplier.MultiplyH(Y);
+ }
+
+ private void gHASHBlock(byte[] Y, byte[] b, int off)
+ {
+ GcmUtilities.Xor(Y, b, off);
+ multiplier.MultiplyH(Y);
+ }
+
+ private void gHASHPartial(byte[] Y, byte[] b, int off, int len)
+ {
+ GcmUtilities.Xor(Y, b, off, len);
+ multiplier.MultiplyH(Y);
+ }
+
+ private void GetNextCtrBlock(byte[] block)
+ {
+ if (blocksRemaining == 0)
+ throw new InvalidOperationException("Attempt to process too many blocks");
+
+ blocksRemaining--;
+
+ uint c = 1;
+ c += counter[15]; counter[15] = (byte)c; c >>= 8;
+ c += counter[14]; counter[14] = (byte)c; c >>= 8;
+ c += counter[13]; counter[13] = (byte)c; c >>= 8;
+ c += counter[12]; counter[12] = (byte)c;
+
+ cipher.ProcessBlock(counter, 0, block, 0);
+ }
+
+ private void CheckStatus()
+ {
+ if (!initialised)
+ {
+ if (forEncryption)
+ {
+ throw new InvalidOperationException("GCM cipher cannot be reused for encryption");
+ }
+ throw new InvalidOperationException("GCM cipher needs to be initialised");
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/GCMBlockCipher.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/GCMBlockCipher.cs.meta
new file mode 100644
index 00000000..bad82543
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/GCMBlockCipher.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: f9e700bc931d48247b4b368d48e44803
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/GOFBBlockCipher.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/GOFBBlockCipher.cs
new file mode 100644
index 00000000..4ad7f355
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/GOFBBlockCipher.cs
@@ -0,0 +1,238 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes
+{
+ /**
+ * implements the GOST 28147 OFB counter mode (GCTR).
+ */
+ public class GOfbBlockCipher
+ : IBlockCipher
+ {
+ private byte[] IV;
+ private byte[] ofbV;
+ private byte[] ofbOutV;
+
+ private readonly int blockSize;
+ private readonly IBlockCipher cipher;
+
+ bool firstStep = true;
+ int N3;
+ int N4;
+ const int C1 = 16843012; //00000001000000010000000100000100
+ const int C2 = 16843009; //00000001000000010000000100000001
+
+ /**
+ * Basic constructor.
+ *
+ * @param cipher the block cipher to be used as the basis of the
+ * counter mode (must have a 64 bit block size).
+ */
+ public GOfbBlockCipher(
+ IBlockCipher cipher)
+ {
+ this.cipher = cipher;
+ this.blockSize = cipher.GetBlockSize();
+
+ if (blockSize != 8)
+ {
+ throw new ArgumentException("GCTR only for 64 bit block ciphers");
+ }
+
+ this.IV = new byte[cipher.GetBlockSize()];
+ this.ofbV = new byte[cipher.GetBlockSize()];
+ this.ofbOutV = new byte[cipher.GetBlockSize()];
+ }
+
+ /**
+ * return the underlying block cipher that we are wrapping.
+ *
+ * @return the underlying block cipher that we are wrapping.
+ */
+ public IBlockCipher GetUnderlyingCipher()
+ {
+ return cipher;
+ }
+
+ /**
+ * Initialise the cipher and, possibly, the initialisation vector (IV).
+ * If an IV isn't passed as part of the parameter, the IV will be all zeros.
+ * An IV which is too short is handled in FIPS compliant fashion.
+ *
+ * @param encrypting if true the cipher is initialised for
+ * encryption, if false for decryption.
+ * @param parameters the key and other data required by the cipher.
+ * @exception ArgumentException if the parameters argument is inappropriate.
+ */
+ public void Init(
+ bool forEncryption, //ignored by this CTR mode
+ ICipherParameters parameters)
+ {
+ firstStep = true;
+ N3 = 0;
+ N4 = 0;
+
+ if (parameters is ParametersWithIV)
+ {
+ ParametersWithIV ivParam = (ParametersWithIV)parameters;
+ byte[] iv = ivParam.GetIV();
+
+ if (iv.Length < IV.Length)
+ {
+ // prepend the supplied IV with zeros (per FIPS PUB 81)
+ Array.Copy(iv, 0, IV, IV.Length - iv.Length, iv.Length);
+ for (int i = 0; i < IV.Length - iv.Length; i++)
+ {
+ IV[i] = 0;
+ }
+ }
+ else
+ {
+ Array.Copy(iv, 0, IV, 0, IV.Length);
+ }
+
+ parameters = ivParam.Parameters;
+ }
+
+ Reset();
+
+ // if it's null, key is to be reused.
+ if (parameters != null)
+ {
+ cipher.Init(true, parameters);
+ }
+ }
+
+ /**
+ * return the algorithm name and mode.
+ *
+ * @return the name of the underlying algorithm followed by "/GCTR"
+ * and the block size in bits
+ */
+ public string AlgorithmName
+ {
+ get { return cipher.AlgorithmName + "/GCTR"; }
+ }
+
+ public bool IsPartialBlockOkay
+ {
+ get { return true; }
+ }
+
+ /**
+ * return the block size we are operating at (in bytes).
+ *
+ * @return the block size we are operating at (in bytes).
+ */
+ public int GetBlockSize()
+ {
+ return blockSize;
+ }
+
+ /**
+ * Process one block of input from the array in and write it to
+ * the out array.
+ *
+ * @param in the array containing the input data.
+ * @param inOff offset into the in array the data starts at.
+ * @param out the array the output data will be copied into.
+ * @param outOff the offset into the out array the output will start at.
+ * @exception DataLengthException if there isn't enough data in in, or
+ * space in out.
+ * @exception InvalidOperationException if the cipher isn't initialised.
+ * @return the number of bytes processed and produced.
+ */
+ public int ProcessBlock(
+ byte[] input,
+ int inOff,
+ byte[] output,
+ int outOff)
+ {
+ if ((inOff + blockSize) > input.Length)
+ {
+ throw new DataLengthException("input buffer too short");
+ }
+
+ if ((outOff + blockSize) > output.Length)
+ {
+ throw new DataLengthException("output buffer too short");
+ }
+
+ if (firstStep)
+ {
+ firstStep = false;
+ cipher.ProcessBlock(ofbV, 0, ofbOutV, 0);
+ N3 = bytesToint(ofbOutV, 0);
+ N4 = bytesToint(ofbOutV, 4);
+ }
+ N3 += C2;
+ N4 += C1;
+ if (N4 < C1) // addition is mod (2**32 - 1)
+ {
+ if (N4 > 0)
+ {
+ N4++;
+ }
+ }
+ intTobytes(N3, ofbV, 0);
+ intTobytes(N4, ofbV, 4);
+
+ cipher.ProcessBlock(ofbV, 0, ofbOutV, 0);
+
+ //
+ // XOR the ofbV with the plaintext producing the cipher text (and
+ // the next input block).
+ //
+ for (int i = 0; i < blockSize; i++)
+ {
+ output[outOff + i] = (byte)(ofbOutV[i] ^ input[inOff + i]);
+ }
+
+ //
+ // change over the input block.
+ //
+ Array.Copy(ofbV, blockSize, ofbV, 0, ofbV.Length - blockSize);
+ Array.Copy(ofbOutV, 0, ofbV, ofbV.Length - blockSize, blockSize);
+
+ return blockSize;
+ }
+
+ /**
+ * reset the feedback vector back to the IV and reset the underlying
+ * cipher.
+ */
+ public void Reset()
+ {
+ Array.Copy(IV, 0, ofbV, 0, IV.Length);
+
+ cipher.Reset();
+ }
+
+ //array of bytes to type int
+ private int bytesToint(
+ byte[] inBytes,
+ int inOff)
+ {
+ return (int)((inBytes[inOff + 3] << 24) & 0xff000000) + ((inBytes[inOff + 2] << 16) & 0xff0000) +
+ ((inBytes[inOff + 1] << 8) & 0xff00) + (inBytes[inOff] & 0xff);
+ }
+
+ //int to array of bytes
+ private void intTobytes(
+ int num,
+ byte[] outBytes,
+ int outOff)
+ {
+ outBytes[outOff + 3] = (byte)(num >> 24);
+ outBytes[outOff + 2] = (byte)(num >> 16);
+ outBytes[outOff + 1] = (byte)(num >> 8);
+ outBytes[outOff] = (byte)num;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/GOFBBlockCipher.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/GOFBBlockCipher.cs.meta
new file mode 100644
index 00000000..f11a4065
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/GOFBBlockCipher.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: e3a091d7cad075041a691018998b39de
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/IAeadBlockCipher.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/IAeadBlockCipher.cs
new file mode 100644
index 00000000..25e34c21
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/IAeadBlockCipher.cs
@@ -0,0 +1,109 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes
+{
+ ///
+ /// A block cipher mode that includes authenticated encryption with a streaming mode
+ /// and optional associated data.
+ ///
+ public interface IAeadBlockCipher
+ {
+ /// The name of the algorithm this cipher implements.
+ string AlgorithmName { get; }
+
+ /// The block cipher underlying this algorithm.
+ IBlockCipher GetUnderlyingCipher();
+
+ /// Initialise the cipher.
+ /// Parameter can either be an AeadParameters or a ParametersWithIV object.
+ /// Initialise for encryption if true, for decryption if false.
+ /// The key or other data required by the cipher.
+ void Init(bool forEncryption, ICipherParameters parameters);
+
+ /// The block size for this cipher, in bytes.
+ int GetBlockSize();
+
+ /// Add a single byte to the associated data check.
+ /// If the implementation supports it, this will be an online operation and will not retain the associated data.
+ /// The byte to be processed.
+ void ProcessAadByte(byte input);
+
+ /// Add a sequence of bytes to the associated data check.
+ /// If the implementation supports it, this will be an online operation and will not retain the associated data.
+ /// The input byte array.
+ /// The offset into the input array where the data to be processed starts.
+ /// The number of bytes to be processed.
+ void ProcessAadBytes(byte[] inBytes, int inOff, int len);
+
+ /**
+ * Encrypt/decrypt a single byte.
+ *
+ * @param input the byte to be processed.
+ * @param outBytes the output buffer the processed byte goes into.
+ * @param outOff the offset into the output byte array the processed data starts at.
+ * @return the number of bytes written to out.
+ * @exception DataLengthException if the output buffer is too small.
+ */
+ int ProcessByte(byte input, byte[] outBytes, int outOff);
+
+ /**
+ * Process a block of bytes from in putting the result into out.
+ *
+ * @param inBytes the input byte array.
+ * @param inOff the offset into the in array where the data to be processed starts.
+ * @param len the number of bytes to be processed.
+ * @param outBytes the output buffer the processed bytes go into.
+ * @param outOff the offset into the output byte array the processed data starts at.
+ * @return the number of bytes written to out.
+ * @exception DataLengthException if the output buffer is too small.
+ */
+ int ProcessBytes(byte[] inBytes, int inOff, int len, byte[] outBytes, int outOff);
+
+ /**
+ * Finish the operation either appending or verifying the MAC at the end of the data.
+ *
+ * @param outBytes space for any resulting output data.
+ * @param outOff offset into out to start copying the data at.
+ * @return number of bytes written into out.
+ * @throws InvalidOperationException if the cipher is in an inappropriate state.
+ * @throws InvalidCipherTextException if the MAC fails to match.
+ */
+ int DoFinal(byte[] outBytes, int outOff);
+
+ /**
+ * Return the value of the MAC associated with the last stream processed.
+ *
+ * @return MAC for plaintext data.
+ */
+ byte[] GetMac();
+
+ /**
+ * Return the size of the output buffer required for a ProcessBytes
+ * an input of len bytes.
+ *
+ * @param len the length of the input.
+ * @return the space required to accommodate a call to ProcessBytes
+ * with len bytes of input.
+ */
+ int GetUpdateOutputSize(int len);
+
+ /**
+ * Return the size of the output buffer required for a ProcessBytes plus a
+ * DoFinal with an input of len bytes.
+ *
+ * @param len the length of the input.
+ * @return the space required to accommodate a call to ProcessBytes and DoFinal
+ * with len bytes of input.
+ */
+ int GetOutputSize(int len);
+
+ ///
+ /// Reset the cipher to the same state as it was after the last init (if there was one).
+ ///
+ void Reset();
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/IAeadBlockCipher.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/IAeadBlockCipher.cs.meta
new file mode 100644
index 00000000..b33e62d7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/IAeadBlockCipher.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 18514e25fcebaa840909a75294f2f1e8
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/KCcmBlockCipher.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/KCcmBlockCipher.cs
new file mode 100644
index 00000000..ea5e5792
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/KCcmBlockCipher.cs
@@ -0,0 +1,494 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes
+{
+ public class KCcmBlockCipher: IAeadBlockCipher
+ {
+ private static readonly int BYTES_IN_INT = 4;
+ private static readonly int BITS_IN_BYTE = 8;
+
+ private static readonly int MAX_MAC_BIT_LENGTH = 512;
+ private static readonly int MIN_MAC_BIT_LENGTH = 64;
+
+ private IBlockCipher engine;
+
+ private int macSize;
+ private bool forEncryption;
+
+ private byte[] initialAssociatedText;
+ private byte[] mac;
+ private byte[] macBlock;
+
+ private byte[] nonce;
+
+ private byte[] G1;
+ private byte[] buffer;
+
+ private byte[] s;
+ private byte[] counter;
+
+ private readonly MemoryStream associatedText = new MemoryStream();
+ private readonly MemoryStream data = new MemoryStream();
+
+ /*
+ *
+ *
+ */
+ private int Nb_ = 4;
+
+ private void setNb(int Nb)
+ {
+ if (Nb == 4 || Nb == 6 || Nb == 8)
+ {
+ Nb_ = Nb;
+ }
+ else
+ {
+ throw new ArgumentException("Nb = 4 is recommended by DSTU7624 but can be changed to only 6 or 8 in this implementation");
+ }
+ }
+
+ ///
+ /// Base constructor. Nb value is set to 4.
+ ///
+ /// base cipher to use under CCM.
+ public KCcmBlockCipher(IBlockCipher engine): this(engine, 4)
+ {
+ }
+
+ ///
+ /// Constructor allowing Nb configuration.
+ ///
+ /// Nb is a parameter specified in CCM mode of DSTU7624 standard.
+ /// This parameter specifies maximum possible length of input.It should
+ /// be calculated as follows: Nb = 1 / 8 * (-3 + log[2]Nmax) + 1,
+ /// where Nmax - length of input message in bits.For practical reasons
+ /// Nmax usually less than 4Gb, e.g. for Nmax = 2^32 - 1, Nb = 4.
+ ///
+ /// base cipher to use under CCM.
+ /// Nb value to use.
+ public KCcmBlockCipher(IBlockCipher engine, int Nb)
+ {
+ this.engine = engine;
+ this.macSize = engine.GetBlockSize();
+ this.nonce = new byte[engine.GetBlockSize()];
+ this.initialAssociatedText = new byte[engine.GetBlockSize()];
+ this.mac = new byte[engine.GetBlockSize()];
+ this.macBlock = new byte[engine.GetBlockSize()];
+ this.G1 = new byte[engine.GetBlockSize()];
+ this.buffer = new byte[engine.GetBlockSize()];
+ this.s = new byte[engine.GetBlockSize()];
+ this.counter = new byte[engine.GetBlockSize()];
+ setNb(Nb);
+ }
+
+ public virtual void Init(bool forEncryption, ICipherParameters parameters)
+ {
+
+ ICipherParameters cipherParameters;
+ if (parameters is AeadParameters)
+ {
+
+ AeadParameters param = (AeadParameters)parameters;
+
+ if (param.MacSize > MAX_MAC_BIT_LENGTH || param.MacSize < MIN_MAC_BIT_LENGTH || param.MacSize % 8 != 0)
+ {
+ throw new ArgumentException("Invalid mac size specified");
+ }
+
+ nonce = param.GetNonce();
+ macSize = param.MacSize / BITS_IN_BYTE;
+ initialAssociatedText = param.GetAssociatedText();
+ cipherParameters = param.Key;
+ }
+ else if (parameters is ParametersWithIV)
+ {
+ nonce = ((ParametersWithIV)parameters).GetIV();
+ macSize = engine.GetBlockSize(); // use default blockSize for MAC if it is not specified
+ initialAssociatedText = null;
+ cipherParameters = ((ParametersWithIV)parameters).Parameters;
+ }
+ else
+ {
+ throw new ArgumentException("Invalid parameters specified");
+ }
+
+ this.mac = new byte[macSize];
+ this.forEncryption = forEncryption;
+ engine.Init(true, cipherParameters);
+
+ counter[0] = 0x01; // defined in standard
+
+ if (initialAssociatedText != null)
+ {
+ ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length);
+ }
+ }
+
+ public virtual String AlgorithmName
+ {
+ get
+ {
+ return engine.AlgorithmName + "/KCCM";
+ }
+ }
+
+ public virtual int GetBlockSize()
+ {
+ return engine.GetBlockSize();
+ }
+
+ public virtual IBlockCipher GetUnderlyingCipher()
+ {
+ return engine;
+ }
+
+ public virtual void ProcessAadByte(byte input)
+ {
+ associatedText.WriteByte(input);
+ }
+
+ public virtual void ProcessAadBytes(byte[] input, int inOff, int len)
+ {
+ associatedText.Write(input, inOff, len);
+ }
+
+ private void ProcessAAD(byte[] assocText, int assocOff, int assocLen, int dataLen)
+ {
+ if (assocLen - assocOff < engine.GetBlockSize())
+ {
+ throw new ArgumentException("authText buffer too short");
+ }
+ if (assocLen % engine.GetBlockSize() != 0)
+ {
+ throw new ArgumentException("padding not supported");
+ }
+
+ Array.Copy(nonce, 0, G1, 0, nonce.Length - Nb_ - 1);
+
+ intToBytes(dataLen, buffer, 0); // for G1
+
+ Array.Copy(buffer, 0, G1, nonce.Length - Nb_ - 1, BYTES_IN_INT);
+
+ G1[G1.Length - 1] = getFlag(true, macSize);
+
+ engine.ProcessBlock(G1, 0, macBlock, 0);
+
+ intToBytes(assocLen, buffer, 0); // for G2
+
+ if (assocLen <= engine.GetBlockSize() - Nb_)
+ {
+ for (int byteIndex = 0; byteIndex < assocLen; byteIndex++)
+ {
+ buffer[byteIndex + Nb_] ^= assocText[assocOff + byteIndex];
+ }
+
+ for (int byteIndex = 0; byteIndex < engine.GetBlockSize(); byteIndex++)
+ {
+ macBlock[byteIndex] ^= buffer[byteIndex];
+ }
+
+ engine.ProcessBlock(macBlock, 0, macBlock, 0);
+
+ return;
+ }
+
+ for (int byteIndex = 0; byteIndex < engine.GetBlockSize(); byteIndex++)
+ {
+ macBlock[byteIndex] ^= buffer[byteIndex];
+ }
+
+ engine.ProcessBlock(macBlock, 0, macBlock, 0);
+
+ int authLen = assocLen;
+ while (authLen != 0)
+ {
+ for (int byteIndex = 0; byteIndex < engine.GetBlockSize(); byteIndex++)
+ {
+ macBlock[byteIndex] ^= assocText[byteIndex + assocOff];
+ }
+
+ engine.ProcessBlock(macBlock, 0, macBlock, 0);
+
+ assocOff += engine.GetBlockSize();
+ authLen -= engine.GetBlockSize();
+ }
+ }
+
+ public virtual int ProcessByte(byte input, byte[] output, int outOff)
+ {
+ data.WriteByte(input);
+
+ return 0;
+ }
+
+ public virtual int ProcessBytes(byte[] input, int inOff, int inLen, byte[] output, int outOff)
+ {
+ Check.DataLength(input, inOff, inLen, "input buffer too short");
+
+ data.Write(input, inOff, inLen);
+
+ return 0;
+ }
+
+ public int ProcessPacket(byte[] input, int inOff, int len, byte[] output, int outOff)
+ {
+ Check.DataLength(input, inOff, len, "input buffer too short");
+ Check.OutputLength(output, outOff, len, "output buffer too short");
+
+ if (associatedText.Length > 0)
+ {
+#if PORTABLE || NETFX_CORE
+ byte[] aad = associatedText.ToArray();
+ int aadLen = aad.Length;
+#else
+ byte[] aad = associatedText.GetBuffer();
+ int aadLen = (int)associatedText.Length;
+#endif
+
+ int dataLen = forEncryption ? (int)data.Length : ((int)data.Length - macSize);
+
+ ProcessAAD(aad, 0, aadLen, dataLen);
+ }
+
+ if (forEncryption)
+ {
+ Check.DataLength(len % engine.GetBlockSize() != 0, "partial blocks not supported");
+
+ CalculateMac(input, inOff, len);
+ engine.ProcessBlock(nonce, 0, s, 0);
+
+ int totalLength = len;
+ while (totalLength > 0)
+ {
+ ProcessBlock(input, inOff, len, output, outOff);
+ totalLength -= engine.GetBlockSize();
+ inOff += engine.GetBlockSize();
+ outOff += engine.GetBlockSize();
+ }
+
+ for (int byteIndex = 0; byteIndex inOff)
+ {
+ for (int byteIndex = 0; byteIndex 0)
+ {
+ for (int byteIndex = 0; byteIndex < engine.GetBlockSize(); byteIndex++)
+ {
+ macBlock[byteIndex] ^= authText[authOff + byteIndex];
+ }
+
+ engine.ProcessBlock(macBlock, 0, macBlock, 0);
+
+ totalLen -= engine.GetBlockSize();
+ authOff += engine.GetBlockSize();
+ }
+ }
+
+ public virtual int DoFinal(byte[] output, int outOff)
+ {
+#if PORTABLE || NETFX_CORE
+ byte[] buf = data.ToArray();
+ int bufLen = buf.Length;
+#else
+ byte[] buf = data.GetBuffer();
+ int bufLen = (int)data.Length;
+#endif
+
+ int len = ProcessPacket(buf, 0, bufLen, output, outOff);
+
+ Reset();
+
+ return len;
+ }
+
+ public virtual byte[] GetMac()
+ {
+ return Arrays.Clone(mac);
+ }
+
+ public virtual int GetUpdateOutputSize(int len)
+ {
+ return len;
+ }
+
+ public virtual int GetOutputSize(int len)
+ {
+ return len + macSize;
+ }
+
+ public virtual void Reset()
+ {
+ Arrays.Fill(G1, (byte)0);
+ Arrays.Fill(buffer, (byte)0);
+ Arrays.Fill(counter, (byte)0);
+ Arrays.Fill(macBlock, (byte)0);
+
+ counter[0] = 0x01;
+ data.SetLength(0);
+ associatedText.SetLength(0);
+
+ if (initialAssociatedText != null)
+ {
+ ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length);
+ }
+ }
+
+ private void intToBytes(
+ int num,
+ byte[] outBytes,
+ int outOff)
+ {
+ outBytes[outOff + 3] = (byte)(num >> 24);
+ outBytes[outOff + 2] = (byte)(num >> 16);
+ outBytes[outOff + 1] = (byte)(num >> 8);
+ outBytes[outOff] = (byte)num;
+ }
+
+ private byte getFlag(bool authTextPresents, int macSize)
+ {
+ StringBuilder flagByte = new StringBuilder();
+
+ if (authTextPresents)
+ {
+ flagByte.Append("1");
+ }
+ else
+ {
+ flagByte.Append("0");
+ }
+
+
+ switch (macSize)
+ {
+ case 8:
+ flagByte.Append("010"); // binary 2
+ break;
+ case 16:
+ flagByte.Append("011"); // binary 3
+ break;
+ case 32:
+ flagByte.Append("100"); // binary 4
+ break;
+ case 48:
+ flagByte.Append("101"); // binary 5
+ break;
+ case 64:
+ flagByte.Append("110"); // binary 6
+ break;
+ }
+
+ String binaryNb = Convert.ToString(Nb_ - 1, 2);
+ while (binaryNb.Length < 4)
+ {
+ binaryNb = new StringBuilder(binaryNb).Insert(0, "0").ToString();
+ }
+
+ flagByte.Append(binaryNb);
+
+ return (byte)Convert.ToInt32(flagByte.ToString(), 2);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/KCcmBlockCipher.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/KCcmBlockCipher.cs.meta
new file mode 100644
index 00000000..1d59104f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/KCcmBlockCipher.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: afe761e6598d68e4397a8694051cd2f9
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/KCtrBlockCipher.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/KCtrBlockCipher.cs
new file mode 100644
index 00000000..e5935086
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/KCtrBlockCipher.cs
@@ -0,0 +1,239 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes
+{
+ /**
+ * Implements a Gamming or Counter (CTR) mode on top of a DSTU 7624 block cipher.
+ */
+ public class KCtrBlockCipher : IStreamCipher, IBlockCipher
+ {
+ private byte[] IV;
+ private byte[] ofbV;
+ private byte[] ofbOutV;
+ private bool initialised;
+
+ private int byteCount;
+
+ private readonly int blockSize;
+ private readonly IBlockCipher cipher;
+
+ /**
+ * Basic constructor.
+ *
+ * @param cipher the block cipher to be used as the basis of the
+ * feedback mode.
+ */
+ public KCtrBlockCipher(IBlockCipher cipher)
+ {
+ this.cipher = cipher;
+ this.IV = new byte[cipher.GetBlockSize()];
+ this.blockSize = cipher.GetBlockSize();
+
+ this.ofbV = new byte[cipher.GetBlockSize()];
+ this.ofbOutV = new byte[cipher.GetBlockSize()];
+ }
+
+ /**
+ * return the underlying block cipher that we are wrapping.
+ *
+ * @return the underlying block cipher that we are wrapping.
+ */
+ public IBlockCipher GetUnderlyingCipher()
+ {
+ return cipher;
+ }
+ /**
+ * Initialise the cipher and, possibly, the initialisation vector (IV).
+ * If an IV isn't passed as part of the parameter, the IV will be all zeros.
+ * An IV which is too short is handled in FIPS compliant fashion.
+ *
+ * @param forEncryption if true the cipher is initialised for
+ * encryption, if false for decryption.
+ * @param param the key and other data required by the cipher.
+ * @exception ArgumentException if the parameters argument is
+ * inappropriate.
+ */
+ public void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ this.initialised = true;
+ if (parameters is ParametersWithIV)
+ {
+ ParametersWithIV ivParam = (ParametersWithIV)parameters;
+ byte[] iv = ivParam.GetIV();
+ int diff = IV.Length - iv.Length;
+
+ Array.Clear(IV, 0, IV.Length);
+ Array.Copy(iv, 0, IV, diff, iv.Length);
+
+ parameters = ivParam.Parameters;
+ }
+ else
+ {
+ throw new ArgumentException("Invalid parameter passed");
+ }
+
+ // if it's null, key is to be reused.
+ if (parameters != null)
+ {
+ cipher.Init(true, parameters);
+ }
+
+ Reset();
+ }
+
+ /**
+ * return the algorithm name and mode.
+ *
+ * @return the name of the underlying algorithm followed by "/KCTR"
+ * and the block size in bits.
+ */
+ public string AlgorithmName
+ {
+ get { return cipher.AlgorithmName + "/KCTR"; }
+ }
+
+ public bool IsPartialBlockOkay
+ {
+ get { return true; }
+ }
+
+ /**
+ * return the block size we are operating at.
+ *
+ * @return the block size we are operating at (in bytes).
+ */
+ public int GetBlockSize()
+ {
+ return cipher.GetBlockSize();
+ }
+
+ public byte ReturnByte(byte input)
+ {
+ return CalculateByte(input);
+ }
+
+ public void ProcessBytes(byte[] input, int inOff, int len, byte[] output, int outOff)
+ {
+ if (outOff + len > output.Length)
+ {
+ throw new DataLengthException("Output buffer too short");
+ }
+
+ if (inOff + len > input.Length)
+ {
+ throw new DataLengthException("Input buffer too small");
+ }
+
+ int inStart = inOff;
+ int inEnd = inOff + len;
+ int outStart = outOff;
+
+ while (inStartRFC 7253 on The OCB
+ * Authenticated-Encryption Algorithm, licensed per:
+ *
+ *
License for
+ * Open-Source Software Implementations of OCB (Jan 9, 2013) - 'License 1'
+ * Under this license, you are authorized to make, use, and distribute open-source software
+ * implementations of OCB. This license terminates for you if you sue someone over their open-source
+ * software implementation of OCB claiming that you have a patent covering their implementation.
+ *
+ * This is a non-binding summary of a legal document (the link above). The parameters of the license
+ * are specified in the license document and that document is controlling.
+ */
+ public class OcbBlockCipher
+ : IAeadBlockCipher
+ {
+ private const int BLOCK_SIZE = 16;
+
+ private readonly IBlockCipher hashCipher;
+ private readonly IBlockCipher mainCipher;
+
+ /*
+ * CONFIGURATION
+ */
+ private bool forEncryption;
+ private int macSize;
+ private byte[] initialAssociatedText;
+
+ /*
+ * KEY-DEPENDENT
+ */
+ // NOTE: elements are lazily calculated
+ private IList L;
+ private byte[] L_Asterisk, L_Dollar;
+
+ /*
+ * NONCE-DEPENDENT
+ */
+ private byte[] KtopInput = null;
+ private byte[] Stretch = new byte[24];
+ private byte[] OffsetMAIN_0 = new byte[16];
+
+ /*
+ * PER-ENCRYPTION/DECRYPTION
+ */
+ private byte[] hashBlock, mainBlock;
+ private int hashBlockPos, mainBlockPos;
+ private long hashBlockCount, mainBlockCount;
+ private byte[] OffsetHASH;
+ private byte[] Sum;
+ private byte[] OffsetMAIN = new byte[16];
+ private byte[] Checksum;
+
+ // NOTE: The MAC value is preserved after doFinal
+ private byte[] macBlock;
+
+ public OcbBlockCipher(IBlockCipher hashCipher, IBlockCipher mainCipher)
+ {
+ if (hashCipher == null)
+ throw new ArgumentNullException("hashCipher");
+ if (hashCipher.GetBlockSize() != BLOCK_SIZE)
+ throw new ArgumentException("must have a block size of " + BLOCK_SIZE, "hashCipher");
+ if (mainCipher == null)
+ throw new ArgumentNullException("mainCipher");
+ if (mainCipher.GetBlockSize() != BLOCK_SIZE)
+ throw new ArgumentException("must have a block size of " + BLOCK_SIZE, "mainCipher");
+
+ if (!hashCipher.AlgorithmName.Equals(mainCipher.AlgorithmName))
+ throw new ArgumentException("'hashCipher' and 'mainCipher' must be the same algorithm");
+
+ this.hashCipher = hashCipher;
+ this.mainCipher = mainCipher;
+ }
+
+ public virtual IBlockCipher GetUnderlyingCipher()
+ {
+ return mainCipher;
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return mainCipher.AlgorithmName + "/OCB"; }
+ }
+
+ public virtual void Init(bool forEncryption, ICipherParameters parameters)
+ {
+ bool oldForEncryption = this.forEncryption;
+ this.forEncryption = forEncryption;
+ this.macBlock = null;
+
+ KeyParameter keyParameter;
+
+ byte[] N;
+ if (parameters is AeadParameters)
+ {
+ AeadParameters aeadParameters = (AeadParameters) parameters;
+
+ N = aeadParameters.GetNonce();
+ initialAssociatedText = aeadParameters.GetAssociatedText();
+
+ int macSizeBits = aeadParameters.MacSize;
+ if (macSizeBits < 64 || macSizeBits > 128 || macSizeBits % 8 != 0)
+ throw new ArgumentException("Invalid value for MAC size: " + macSizeBits);
+
+ macSize = macSizeBits / 8;
+ keyParameter = aeadParameters.Key;
+ }
+ else if (parameters is ParametersWithIV)
+ {
+ ParametersWithIV parametersWithIV = (ParametersWithIV) parameters;
+
+ N = parametersWithIV.GetIV();
+ initialAssociatedText = null;
+ macSize = 16;
+ keyParameter = (KeyParameter) parametersWithIV.Parameters;
+ }
+ else
+ {
+ throw new ArgumentException("invalid parameters passed to OCB");
+ }
+
+ this.hashBlock = new byte[16];
+ this.mainBlock = new byte[forEncryption ? BLOCK_SIZE : (BLOCK_SIZE + macSize)];
+
+ if (N == null)
+ {
+ N = new byte[0];
+ }
+
+ if (N.Length > 15)
+ {
+ throw new ArgumentException("IV must be no more than 15 bytes");
+ }
+
+ /*
+ * KEY-DEPENDENT INITIALISATION
+ */
+
+ if (keyParameter != null)
+ {
+ // hashCipher always used in forward mode
+ hashCipher.Init(true, keyParameter);
+ mainCipher.Init(forEncryption, keyParameter);
+ KtopInput = null;
+ }
+ else if (oldForEncryption != forEncryption)
+ {
+ throw new ArgumentException("cannot change encrypting state without providing key.");
+ }
+
+ this.L_Asterisk = new byte[16];
+ hashCipher.ProcessBlock(L_Asterisk, 0, L_Asterisk, 0);
+
+ this.L_Dollar = OCB_double(L_Asterisk);
+
+ this.L = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ this.L.Add(OCB_double(L_Dollar));
+
+ /*
+ * NONCE-DEPENDENT AND PER-ENCRYPTION/DECRYPTION INITIALISATION
+ */
+
+ int bottom = ProcessNonce(N);
+
+ int bits = bottom % 8, bytes = bottom / 8;
+ if (bits == 0)
+ {
+ Array.Copy(Stretch, bytes, OffsetMAIN_0, 0, 16);
+ }
+ else
+ {
+ for (int i = 0; i < 16; ++i)
+ {
+ uint b1 = Stretch[bytes];
+ uint b2 = Stretch[++bytes];
+ this.OffsetMAIN_0[i] = (byte) ((b1 << bits) | (b2 >> (8 - bits)));
+ }
+ }
+
+ this.hashBlockPos = 0;
+ this.mainBlockPos = 0;
+
+ this.hashBlockCount = 0;
+ this.mainBlockCount = 0;
+
+ this.OffsetHASH = new byte[16];
+ this.Sum = new byte[16];
+ Array.Copy(OffsetMAIN_0, 0, OffsetMAIN, 0, 16);
+ this.Checksum = new byte[16];
+
+ if (initialAssociatedText != null)
+ {
+ ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length);
+ }
+ }
+
+ protected virtual int ProcessNonce(byte[] N)
+ {
+ byte[] nonce = new byte[16];
+ Array.Copy(N, 0, nonce, nonce.Length - N.Length, N.Length);
+ nonce[0] = (byte)(macSize << 4);
+ nonce[15 - N.Length] |= 1;
+
+ int bottom = nonce[15] & 0x3F;
+ nonce[15] &= 0xC0;
+
+ /*
+ * When used with incrementing nonces, the cipher is only applied once every 64 inits.
+ */
+ if (KtopInput == null || !Arrays.AreEqual(nonce, KtopInput))
+ {
+ byte[] Ktop = new byte[16];
+ KtopInput = nonce;
+ hashCipher.ProcessBlock(KtopInput, 0, Ktop, 0);
+ Array.Copy(Ktop, 0, Stretch, 0, 16);
+ for (int i = 0; i < 8; ++i)
+ {
+ Stretch[16 + i] = (byte)(Ktop[i] ^ Ktop[i + 1]);
+ }
+ }
+
+ return bottom;
+ }
+
+ public virtual int GetBlockSize()
+ {
+ return BLOCK_SIZE;
+ }
+
+ public virtual byte[] GetMac()
+ {
+ return macBlock == null
+ ? new byte[macSize]
+ : Arrays.Clone(macBlock);
+ }
+
+ public virtual int GetOutputSize(int len)
+ {
+ int totalData = len + mainBlockPos;
+ if (forEncryption)
+ {
+ return totalData + macSize;
+ }
+ return totalData < macSize ? 0 : totalData - macSize;
+ }
+
+ public virtual int GetUpdateOutputSize(int len)
+ {
+ int totalData = len + mainBlockPos;
+ if (!forEncryption)
+ {
+ if (totalData < macSize)
+ {
+ return 0;
+ }
+ totalData -= macSize;
+ }
+ return totalData - totalData % BLOCK_SIZE;
+ }
+
+ public virtual void ProcessAadByte(byte input)
+ {
+ hashBlock[hashBlockPos] = input;
+ if (++hashBlockPos == hashBlock.Length)
+ {
+ ProcessHashBlock();
+ }
+ }
+
+ public virtual void ProcessAadBytes(byte[] input, int off, int len)
+ {
+ for (int i = 0; i < len; ++i)
+ {
+ hashBlock[hashBlockPos] = input[off + i];
+ if (++hashBlockPos == hashBlock.Length)
+ {
+ ProcessHashBlock();
+ }
+ }
+ }
+
+ public virtual int ProcessByte(byte input, byte[] output, int outOff)
+ {
+ mainBlock[mainBlockPos] = input;
+ if (++mainBlockPos == mainBlock.Length)
+ {
+ ProcessMainBlock(output, outOff);
+ return BLOCK_SIZE;
+ }
+ return 0;
+ }
+
+ public virtual int ProcessBytes(byte[] input, int inOff, int len, byte[] output, int outOff)
+ {
+ int resultLen = 0;
+
+ for (int i = 0; i < len; ++i)
+ {
+ mainBlock[mainBlockPos] = input[inOff + i];
+ if (++mainBlockPos == mainBlock.Length)
+ {
+ ProcessMainBlock(output, outOff + resultLen);
+ resultLen += BLOCK_SIZE;
+ }
+ }
+
+ return resultLen;
+ }
+
+ public virtual int DoFinal(byte[] output, int outOff)
+ {
+ /*
+ * For decryption, get the tag from the end of the message
+ */
+ byte[] tag = null;
+ if (!forEncryption) {
+ if (mainBlockPos < macSize)
+ throw new InvalidCipherTextException("data too short");
+
+ mainBlockPos -= macSize;
+ tag = new byte[macSize];
+ Array.Copy(mainBlock, mainBlockPos, tag, 0, macSize);
+ }
+
+ /*
+ * HASH: Process any final partial block; compute final hash value
+ */
+ if (hashBlockPos > 0)
+ {
+ OCB_extend(hashBlock, hashBlockPos);
+ UpdateHASH(L_Asterisk);
+ }
+
+ /*
+ * OCB-ENCRYPT/OCB-DECRYPT: Process any final partial block
+ */
+ if (mainBlockPos > 0)
+ {
+ if (forEncryption)
+ {
+ OCB_extend(mainBlock, mainBlockPos);
+ Xor(Checksum, mainBlock);
+ }
+
+ Xor(OffsetMAIN, L_Asterisk);
+
+ byte[] Pad = new byte[16];
+ hashCipher.ProcessBlock(OffsetMAIN, 0, Pad, 0);
+
+ Xor(mainBlock, Pad);
+
+ Check.OutputLength(output, outOff, mainBlockPos, "Output buffer too short");
+ Array.Copy(mainBlock, 0, output, outOff, mainBlockPos);
+
+ if (!forEncryption)
+ {
+ OCB_extend(mainBlock, mainBlockPos);
+ Xor(Checksum, mainBlock);
+ }
+ }
+
+ /*
+ * OCB-ENCRYPT/OCB-DECRYPT: Compute raw tag
+ */
+ Xor(Checksum, OffsetMAIN);
+ Xor(Checksum, L_Dollar);
+ hashCipher.ProcessBlock(Checksum, 0, Checksum, 0);
+ Xor(Checksum, Sum);
+
+ this.macBlock = new byte[macSize];
+ Array.Copy(Checksum, 0, macBlock, 0, macSize);
+
+ /*
+ * Validate or append tag and reset this cipher for the next run
+ */
+ int resultLen = mainBlockPos;
+
+ if (forEncryption)
+ {
+ Check.OutputLength(output, outOff, resultLen + macSize, "Output buffer too short");
+
+ // Append tag to the message
+ Array.Copy(macBlock, 0, output, outOff + resultLen, macSize);
+ resultLen += macSize;
+ }
+ else
+ {
+ // Compare the tag from the message with the calculated one
+ if (!Arrays.ConstantTimeAreEqual(macBlock, tag))
+ throw new InvalidCipherTextException("mac check in OCB failed");
+ }
+
+ Reset(false);
+
+ return resultLen;
+ }
+
+ public virtual void Reset()
+ {
+ Reset(true);
+ }
+
+ protected virtual void Clear(byte[] bs)
+ {
+ if (bs != null)
+ {
+ Array.Clear(bs, 0, bs.Length);
+ }
+ }
+
+ protected virtual byte[] GetLSub(int n)
+ {
+ while (n >= L.Count)
+ {
+ L.Add(OCB_double((byte[]) L[L.Count - 1]));
+ }
+ return (byte[])L[n];
+ }
+
+ protected virtual void ProcessHashBlock()
+ {
+ /*
+ * HASH: Process any whole blocks
+ */
+ UpdateHASH(GetLSub(OCB_ntz(++hashBlockCount)));
+ hashBlockPos = 0;
+ }
+
+ protected virtual void ProcessMainBlock(byte[] output, int outOff)
+ {
+ Check.DataLength(output, outOff, BLOCK_SIZE, "Output buffer too short");
+
+ /*
+ * OCB-ENCRYPT/OCB-DECRYPT: Process any whole blocks
+ */
+
+ if (forEncryption)
+ {
+ Xor(Checksum, mainBlock);
+ mainBlockPos = 0;
+ }
+
+ Xor(OffsetMAIN, GetLSub(OCB_ntz(++mainBlockCount)));
+
+ Xor(mainBlock, OffsetMAIN);
+ mainCipher.ProcessBlock(mainBlock, 0, mainBlock, 0);
+ Xor(mainBlock, OffsetMAIN);
+
+ Array.Copy(mainBlock, 0, output, outOff, 16);
+
+ if (!forEncryption)
+ {
+ Xor(Checksum, mainBlock);
+ Array.Copy(mainBlock, BLOCK_SIZE, mainBlock, 0, macSize);
+ mainBlockPos = macSize;
+ }
+ }
+
+ protected virtual void Reset(bool clearMac)
+ {
+ hashCipher.Reset();
+ mainCipher.Reset();
+
+ Clear(hashBlock);
+ Clear(mainBlock);
+
+ hashBlockPos = 0;
+ mainBlockPos = 0;
+
+ hashBlockCount = 0;
+ mainBlockCount = 0;
+
+ Clear(OffsetHASH);
+ Clear(Sum);
+ Array.Copy(OffsetMAIN_0, 0, OffsetMAIN, 0, 16);
+ Clear(Checksum);
+
+ if (clearMac)
+ {
+ macBlock = null;
+ }
+
+ if (initialAssociatedText != null)
+ {
+ ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length);
+ }
+ }
+
+ protected virtual void UpdateHASH(byte[] LSub)
+ {
+ Xor(OffsetHASH, LSub);
+ Xor(hashBlock, OffsetHASH);
+ hashCipher.ProcessBlock(hashBlock, 0, hashBlock, 0);
+ Xor(Sum, hashBlock);
+ }
+
+ protected static byte[] OCB_double(byte[] block)
+ {
+ byte[] result = new byte[16];
+ int carry = ShiftLeft(block, result);
+
+ /*
+ * NOTE: This construction is an attempt at a constant-time implementation.
+ */
+ result[15] ^= (byte)(0x87 >> ((1 - carry) << 3));
+
+ return result;
+ }
+
+ protected static void OCB_extend(byte[] block, int pos)
+ {
+ block[pos] = (byte) 0x80;
+ while (++pos < 16)
+ {
+ block[pos] = 0;
+ }
+ }
+
+ protected static int OCB_ntz(long x)
+ {
+ if (x == 0)
+ {
+ return 64;
+ }
+
+ int n = 0;
+ ulong ux = (ulong)x;
+ while ((ux & 1UL) == 0UL)
+ {
+ ++n;
+ ux >>= 1;
+ }
+ return n;
+ }
+
+ protected static int ShiftLeft(byte[] block, byte[] output)
+ {
+ int i = 16;
+ uint bit = 0;
+ while (--i >= 0)
+ {
+ uint b = block[i];
+ output[i] = (byte) ((b << 1) | bit);
+ bit = (b >> 7) & 1;
+ }
+ return (int)bit;
+ }
+
+ protected static void Xor(byte[] block, byte[] val)
+ {
+ for (int i = 15; i >= 0; --i)
+ {
+ block[i] ^= val[i];
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/OCBBlockCipher.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/OCBBlockCipher.cs.meta
new file mode 100644
index 00000000..a6a9e514
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/OCBBlockCipher.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 89052943097a6b3488c0e056459769e9
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/OfbBlockCipher.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/OfbBlockCipher.cs
new file mode 100644
index 00000000..5b31da6f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/OfbBlockCipher.cs
@@ -0,0 +1,186 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes
+{
+ /**
+ * implements a Output-FeedBack (OFB) mode on top of a simple cipher.
+ */
+ public class OfbBlockCipher
+ : IBlockCipher
+ {
+ private byte[] IV;
+ private byte[] ofbV;
+ private byte[] ofbOutV;
+
+ private readonly int blockSize;
+ private readonly IBlockCipher cipher;
+
+ /**
+ * Basic constructor.
+ *
+ * @param cipher the block cipher to be used as the basis of the
+ * feedback mode.
+ * @param blockSize the block size in bits (note: a multiple of 8)
+ */
+ public OfbBlockCipher(
+ IBlockCipher cipher,
+ int blockSize)
+ {
+ this.cipher = cipher;
+ this.blockSize = blockSize / 8;
+
+ this.IV = new byte[cipher.GetBlockSize()];
+ this.ofbV = new byte[cipher.GetBlockSize()];
+ this.ofbOutV = new byte[cipher.GetBlockSize()];
+ }
+
+ /**
+ * return the underlying block cipher that we are wrapping.
+ *
+ * @return the underlying block cipher that we are wrapping.
+ */
+ public IBlockCipher GetUnderlyingCipher()
+ {
+ return cipher;
+ }
+
+ /**
+ * Initialise the cipher and, possibly, the initialisation vector (IV).
+ * If an IV isn't passed as part of the parameter, the IV will be all zeros.
+ * An IV which is too short is handled in FIPS compliant fashion.
+ *
+ * @param forEncryption if true the cipher is initialised for
+ * encryption, if false for decryption.
+ * @param param the key and other data required by the cipher.
+ * @exception ArgumentException if the parameters argument is
+ * inappropriate.
+ */
+ public void Init(
+ bool forEncryption, //ignored by this OFB mode
+ ICipherParameters parameters)
+ {
+ if (parameters is ParametersWithIV)
+ {
+ ParametersWithIV ivParam = (ParametersWithIV)parameters;
+ byte[] iv = ivParam.GetIV();
+
+ if (iv.Length < IV.Length)
+ {
+ // prepend the supplied IV with zeros (per FIPS PUB 81)
+ Array.Copy(iv, 0, IV, IV.Length - iv.Length, iv.Length);
+ for (int i = 0; i < IV.Length - iv.Length; i++)
+ {
+ IV[i] = 0;
+ }
+ }
+ else
+ {
+ Array.Copy(iv, 0, IV, 0, IV.Length);
+ }
+
+ parameters = ivParam.Parameters;
+ }
+
+ Reset();
+
+ // if it's null, key is to be reused.
+ if (parameters != null)
+ {
+ cipher.Init(true, parameters);
+ }
+ }
+
+ /**
+ * return the algorithm name and mode.
+ *
+ * @return the name of the underlying algorithm followed by "/OFB"
+ * and the block size in bits
+ */
+ public string AlgorithmName
+ {
+ get { return cipher.AlgorithmName + "/OFB" + (blockSize * 8); }
+ }
+
+ public bool IsPartialBlockOkay
+ {
+ get { return true; }
+ }
+
+ /**
+ * return the block size we are operating at (in bytes).
+ *
+ * @return the block size we are operating at (in bytes).
+ */
+ public int GetBlockSize()
+ {
+ return blockSize;
+ }
+
+ /**
+ * Process one block of input from the array in and write it to
+ * the out array.
+ *
+ * @param in the array containing the input data.
+ * @param inOff offset into the in array the data starts at.
+ * @param out the array the output data will be copied into.
+ * @param outOff the offset into the out array the output will start at.
+ * @exception DataLengthException if there isn't enough data in in, or
+ * space in out.
+ * @exception InvalidOperationException if the cipher isn't initialised.
+ * @return the number of bytes processed and produced.
+ */
+ public int ProcessBlock(
+ byte[] input,
+ int inOff,
+ byte[] output,
+ int outOff)
+ {
+ if ((inOff + blockSize) > input.Length)
+ {
+ throw new DataLengthException("input buffer too short");
+ }
+
+ if ((outOff + blockSize) > output.Length)
+ {
+ throw new DataLengthException("output buffer too short");
+ }
+
+ cipher.ProcessBlock(ofbV, 0, ofbOutV, 0);
+
+ //
+ // XOR the ofbV with the plaintext producing the cipher text (and
+ // the next input block).
+ //
+ for (int i = 0; i < blockSize; i++)
+ {
+ output[outOff + i] = (byte)(ofbOutV[i] ^ input[inOff + i]);
+ }
+
+ //
+ // change over the input block.
+ //
+ Array.Copy(ofbV, blockSize, ofbV, 0, ofbV.Length - blockSize);
+ Array.Copy(ofbOutV, 0, ofbV, ofbV.Length - blockSize, blockSize);
+
+ return blockSize;
+ }
+
+ /**
+ * reset the feedback vector back to the IV and reset the underlying
+ * cipher.
+ */
+ public void Reset()
+ {
+ Array.Copy(IV, 0, ofbV, 0, IV.Length);
+
+ cipher.Reset();
+ }
+ }
+
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/OfbBlockCipher.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/OfbBlockCipher.cs.meta
new file mode 100644
index 00000000..06ef7cb8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/OfbBlockCipher.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 71bc36ce7925c074aa3654b21bda3a7f
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/OpenPgpCfbBlockCipher.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/OpenPgpCfbBlockCipher.cs
new file mode 100644
index 00000000..93213723
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/OpenPgpCfbBlockCipher.cs
@@ -0,0 +1,341 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes
+{
+ /**
+ * Implements OpenPGP's rather strange version of Cipher-FeedBack (CFB) mode
+ * on top of a simple cipher. This class assumes the IV has been prepended
+ * to the data stream already, and just accomodates the reset after
+ * (blockSize + 2) bytes have been read.
+ *
+ */
+ public class OpenPgpCfbBlockCipher
+ : IBlockCipher
+ {
+ private byte[] IV;
+ private byte[] FR;
+ private byte[] FRE;
+
+ private readonly IBlockCipher cipher;
+ private readonly int blockSize;
+
+ private int count;
+ private bool forEncryption;
+
+ /**
+ * Basic constructor.
+ *
+ * @param cipher the block cipher to be used as the basis of the
+ * feedback mode.
+ */
+ public OpenPgpCfbBlockCipher(
+ IBlockCipher cipher)
+ {
+ this.cipher = cipher;
+
+ this.blockSize = cipher.GetBlockSize();
+ this.IV = new byte[blockSize];
+ this.FR = new byte[blockSize];
+ this.FRE = new byte[blockSize];
+ }
+
+ /**
+ * return the underlying block cipher that we are wrapping.
+ *
+ * @return the underlying block cipher that we are wrapping.
+ */
+ public IBlockCipher GetUnderlyingCipher()
+ {
+ return cipher;
+ }
+
+ /**
+ * return the algorithm name and mode.
+ *
+ * @return the name of the underlying algorithm followed by "/PGPCFB"
+ * and the block size in bits.
+ */
+ public string AlgorithmName
+ {
+ get { return cipher.AlgorithmName + "/OpenPGPCFB"; }
+ }
+
+ public bool IsPartialBlockOkay
+ {
+ get { return true; }
+ }
+
+ /**
+ * return the block size we are operating at.
+ *
+ * @return the block size we are operating at (in bytes).
+ */
+ public int GetBlockSize()
+ {
+ return cipher.GetBlockSize();
+ }
+
+ /**
+ * Process one block of input from the array in and write it to
+ * the out array.
+ *
+ * @param in the array containing the input data.
+ * @param inOff offset into the in array the data starts at.
+ * @param out the array the output data will be copied into.
+ * @param outOff the offset into the out array the output will start at.
+ * @exception DataLengthException if there isn't enough data in in, or
+ * space in out.
+ * @exception InvalidOperationException if the cipher isn't initialised.
+ * @return the number of bytes processed and produced.
+ */
+ public int ProcessBlock(
+ byte[] input,
+ int inOff,
+ byte[] output,
+ int outOff)
+ {
+ return (forEncryption) ? EncryptBlock(input, inOff, output, outOff) : DecryptBlock(input, inOff, output, outOff);
+ }
+
+ /**
+ * reset the chaining vector back to the IV and reset the underlying
+ * cipher.
+ */
+ public void Reset()
+ {
+ count = 0;
+
+ Array.Copy(IV, 0, FR, 0, FR.Length);
+
+ cipher.Reset();
+ }
+
+ /**
+ * Initialise the cipher and, possibly, the initialisation vector (IV).
+ * If an IV isn't passed as part of the parameter, the IV will be all zeros.
+ * An IV which is too short is handled in FIPS compliant fashion.
+ *
+ * @param forEncryption if true the cipher is initialised for
+ * encryption, if false for decryption.
+ * @param parameters the key and other data required by the cipher.
+ * @exception ArgumentException if the parameters argument is
+ * inappropriate.
+ */
+ public void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ this.forEncryption = forEncryption;
+
+ if (parameters is ParametersWithIV)
+ {
+ ParametersWithIV ivParam = (ParametersWithIV)parameters;
+ byte[] iv = ivParam.GetIV();
+
+ if (iv.Length < IV.Length)
+ {
+ // prepend the supplied IV with zeros (per FIPS PUB 81)
+ Array.Copy(iv, 0, IV, IV.Length - iv.Length, iv.Length);
+ for (int i = 0; i < IV.Length - iv.Length; i++)
+ {
+ IV[i] = 0;
+ }
+ }
+ else
+ {
+ Array.Copy(iv, 0, IV, 0, IV.Length);
+ }
+
+ parameters = ivParam.Parameters;
+ }
+
+ Reset();
+
+ cipher.Init(true, parameters);
+ }
+
+ /**
+ * Encrypt one byte of data according to CFB mode.
+ * @param data the byte to encrypt
+ * @param blockOff offset in the current block
+ * @returns the encrypted byte
+ */
+ private byte EncryptByte(byte data, int blockOff)
+ {
+ return (byte)(FRE[blockOff] ^ data);
+ }
+
+ /**
+ * Do the appropriate processing for CFB IV mode encryption.
+ *
+ * @param in the array containing the data to be encrypted.
+ * @param inOff offset into the in array the data starts at.
+ * @param out the array the encrypted data will be copied into.
+ * @param outOff the offset into the out array the output will start at.
+ * @exception DataLengthException if there isn't enough data in in, or
+ * space in out.
+ * @exception InvalidOperationException if the cipher isn't initialised.
+ * @return the number of bytes processed and produced.
+ */
+ private int EncryptBlock(
+ byte[] input,
+ int inOff,
+ byte[] outBytes,
+ int outOff)
+ {
+ if ((inOff + blockSize) > input.Length)
+ {
+ throw new DataLengthException("input buffer too short");
+ }
+
+ if ((outOff + blockSize) > outBytes.Length)
+ {
+ throw new DataLengthException("output buffer too short");
+ }
+
+ if (count > blockSize)
+ {
+ FR[blockSize - 2] = outBytes[outOff] = EncryptByte(input[inOff], blockSize - 2);
+ FR[blockSize - 1] = outBytes[outOff + 1] = EncryptByte(input[inOff + 1], blockSize - 1);
+
+ cipher.ProcessBlock(FR, 0, FRE, 0);
+
+ for (int n = 2; n < blockSize; n++)
+ {
+ FR[n - 2] = outBytes[outOff + n] = EncryptByte(input[inOff + n], n - 2);
+ }
+ }
+ else if (count == 0)
+ {
+ cipher.ProcessBlock(FR, 0, FRE, 0);
+
+ for (int n = 0; n < blockSize; n++)
+ {
+ FR[n] = outBytes[outOff + n] = EncryptByte(input[inOff + n], n);
+ }
+
+ count += blockSize;
+ }
+ else if (count == blockSize)
+ {
+ cipher.ProcessBlock(FR, 0, FRE, 0);
+
+ outBytes[outOff] = EncryptByte(input[inOff], 0);
+ outBytes[outOff + 1] = EncryptByte(input[inOff + 1], 1);
+
+ //
+ // do reset
+ //
+ Array.Copy(FR, 2, FR, 0, blockSize - 2);
+ Array.Copy(outBytes, outOff, FR, blockSize - 2, 2);
+
+ cipher.ProcessBlock(FR, 0, FRE, 0);
+
+ for (int n = 2; n < blockSize; n++)
+ {
+ FR[n - 2] = outBytes[outOff + n] = EncryptByte(input[inOff + n], n - 2);
+ }
+
+ count += blockSize;
+ }
+
+ return blockSize;
+ }
+
+ /**
+ * Do the appropriate processing for CFB IV mode decryption.
+ *
+ * @param in the array containing the data to be decrypted.
+ * @param inOff offset into the in array the data starts at.
+ * @param out the array the encrypted data will be copied into.
+ * @param outOff the offset into the out array the output will start at.
+ * @exception DataLengthException if there isn't enough data in in, or
+ * space in out.
+ * @exception InvalidOperationException if the cipher isn't initialised.
+ * @return the number of bytes processed and produced.
+ */
+ private int DecryptBlock(
+ byte[] input,
+ int inOff,
+ byte[] outBytes,
+ int outOff)
+ {
+ if ((inOff + blockSize) > input.Length)
+ {
+ throw new DataLengthException("input buffer too short");
+ }
+
+ if ((outOff + blockSize) > outBytes.Length)
+ {
+ throw new DataLengthException("output buffer too short");
+ }
+
+ if (count > blockSize)
+ {
+ byte inVal = input[inOff];
+ FR[blockSize - 2] = inVal;
+ outBytes[outOff] = EncryptByte(inVal, blockSize - 2);
+
+ inVal = input[inOff + 1];
+ FR[blockSize - 1] = inVal;
+ outBytes[outOff + 1] = EncryptByte(inVal, blockSize - 1);
+
+ cipher.ProcessBlock(FR, 0, FRE, 0);
+
+ for (int n = 2; n < blockSize; n++)
+ {
+ inVal = input[inOff + n];
+ FR[n - 2] = inVal;
+ outBytes[outOff + n] = EncryptByte(inVal, n - 2);
+ }
+ }
+ else if (count == 0)
+ {
+ cipher.ProcessBlock(FR, 0, FRE, 0);
+
+ for (int n = 0; n < blockSize; n++)
+ {
+ FR[n] = input[inOff + n];
+ outBytes[n] = EncryptByte(input[inOff + n], n);
+ }
+
+ count += blockSize;
+ }
+ else if (count == blockSize)
+ {
+ cipher.ProcessBlock(FR, 0, FRE, 0);
+
+ byte inVal1 = input[inOff];
+ byte inVal2 = input[inOff + 1];
+ outBytes[outOff ] = EncryptByte(inVal1, 0);
+ outBytes[outOff + 1] = EncryptByte(inVal2, 1);
+
+ Array.Copy(FR, 2, FR, 0, blockSize - 2);
+
+ FR[blockSize - 2] = inVal1;
+ FR[blockSize - 1] = inVal2;
+
+ cipher.ProcessBlock(FR, 0, FRE, 0);
+
+ for (int n = 2; n < blockSize; n++)
+ {
+ byte inVal = input[inOff + n];
+ FR[n - 2] = inVal;
+ outBytes[outOff + n] = EncryptByte(inVal, n - 2);
+ }
+
+ count += blockSize;
+ }
+
+ return blockSize;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/OpenPgpCfbBlockCipher.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/OpenPgpCfbBlockCipher.cs.meta
new file mode 100644
index 00000000..10974c92
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/OpenPgpCfbBlockCipher.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: b1ada4d10e1ce0546a797441077dd7a4
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/SicBlockCipher.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/SicBlockCipher.cs
new file mode 100644
index 00000000..014d29c9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/SicBlockCipher.cs
@@ -0,0 +1,124 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes
+{
+ /**
+ * Implements the Segmented Integer Counter (SIC) mode on top of a simple
+ * block cipher.
+ */
+ public class SicBlockCipher
+ : IBlockCipher
+ {
+ private readonly IBlockCipher cipher;
+ private readonly int blockSize;
+ private readonly byte[] counter;
+ private readonly byte[] counterOut;
+ private byte[] IV;
+
+ /**
+ * Basic constructor.
+ *
+ * @param c the block cipher to be used.
+ */
+ public SicBlockCipher(IBlockCipher cipher)
+ {
+ this.cipher = cipher;
+ this.blockSize = cipher.GetBlockSize();
+ this.counter = new byte[blockSize];
+ this.counterOut = new byte[blockSize];
+ this.IV = new byte[blockSize];
+ }
+
+ /**
+ * return the underlying block cipher that we are wrapping.
+ *
+ * @return the underlying block cipher that we are wrapping.
+ */
+ public virtual IBlockCipher GetUnderlyingCipher()
+ {
+ return cipher;
+ }
+
+ public virtual void Init(
+ bool forEncryption, //ignored by this CTR mode
+ ICipherParameters parameters)
+ {
+ ParametersWithIV ivParam = parameters as ParametersWithIV;
+ if (ivParam == null)
+ throw new ArgumentException("CTR/SIC mode requires ParametersWithIV", "parameters");
+
+ this.IV = Arrays.Clone(ivParam.GetIV());
+
+ if (blockSize < IV.Length)
+ throw new ArgumentException("CTR/SIC mode requires IV no greater than: " + blockSize + " bytes.");
+
+ int maxCounterSize = System.Math.Min(8, blockSize / 2);
+ if (blockSize - IV.Length > maxCounterSize)
+ throw new ArgumentException("CTR/SIC mode requires IV of at least: " + (blockSize - maxCounterSize) + " bytes.");
+
+ // if null it's an IV changed only.
+ if (ivParam.Parameters != null)
+ {
+ cipher.Init(true, ivParam.Parameters);
+ }
+
+ Reset();
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return cipher.AlgorithmName + "/SIC"; }
+ }
+
+ public virtual bool IsPartialBlockOkay
+ {
+ get { return true; }
+ }
+
+ public virtual int GetBlockSize()
+ {
+ return cipher.GetBlockSize();
+ }
+
+ public virtual int ProcessBlock(
+ byte[] input,
+ int inOff,
+ byte[] output,
+ int outOff)
+ {
+ cipher.ProcessBlock(counter, 0, counterOut, 0);
+
+ //
+ // XOR the counterOut with the plaintext producing the cipher text
+ //
+ for (int i = 0; i < counterOut.Length; i++)
+ {
+ output[outOff + i] = (byte)(counterOut[i] ^ input[inOff + i]);
+ }
+
+ // Increment the counter
+ int j = counter.Length;
+ while (--j >= 0 && ++counter[j] == 0)
+ {
+ }
+
+ return counter.Length;
+ }
+
+ public virtual void Reset()
+ {
+ Arrays.Fill(counter, (byte)0);
+ Array.Copy(IV, 0, counter, 0, IV.Length);
+ cipher.Reset();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/SicBlockCipher.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/SicBlockCipher.cs.meta
new file mode 100644
index 00000000..26d92958
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/SicBlockCipher.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 2296184ee476c384393555a8260b697e
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm.meta
new file mode 100644
index 00000000..789a2606
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 25332b96083d377489f73df4e40c17c8
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/BasicGcmExponentiator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/BasicGcmExponentiator.cs
new file mode 100644
index 00000000..cabf8207
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/BasicGcmExponentiator.cs
@@ -0,0 +1,44 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes.Gcm
+{
+ public class BasicGcmExponentiator
+ : IGcmExponentiator
+ {
+ private uint[] x;
+
+ public void Init(byte[] x)
+ {
+ this.x = GcmUtilities.AsUints(x);
+ }
+
+ public void ExponentiateX(long pow, byte[] output)
+ {
+ // Initial value is little-endian 1
+ uint[] y = GcmUtilities.OneAsUints();
+
+ if (pow > 0)
+ {
+ uint[] powX = Arrays.Clone(x);
+ do
+ {
+ if ((pow & 1L) != 0)
+ {
+ GcmUtilities.Multiply(y, powX);
+ }
+ GcmUtilities.Multiply(powX, powX);
+ pow >>= 1;
+ }
+ while (pow > 0);
+ }
+
+ GcmUtilities.AsBytes(y, output);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/BasicGcmExponentiator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/BasicGcmExponentiator.cs.meta
new file mode 100644
index 00000000..f0ad3d54
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/BasicGcmExponentiator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a079161b52b48be48a3b061183d2342a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/BasicGcmMultiplier.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/BasicGcmMultiplier.cs
new file mode 100644
index 00000000..c87a7e0c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/BasicGcmMultiplier.cs
@@ -0,0 +1,26 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes.Gcm
+{
+ public class BasicGcmMultiplier
+ : IGcmMultiplier
+ {
+ private uint[] H;
+
+ public void Init(byte[] H)
+ {
+ this.H = GcmUtilities.AsUints(H);
+ }
+
+ public void MultiplyH(byte[] x)
+ {
+ uint[] t = GcmUtilities.AsUints(x);
+ GcmUtilities.Multiply(t, H);
+ GcmUtilities.AsBytes(t, x);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/BasicGcmMultiplier.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/BasicGcmMultiplier.cs.meta
new file mode 100644
index 00000000..ae9b801e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/BasicGcmMultiplier.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 21667055c0a779443a148941e7c64ee1
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/GcmUtilities.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/GcmUtilities.cs
new file mode 100644
index 00000000..1ab51637
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/GcmUtilities.cs
@@ -0,0 +1,357 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes.Gcm
+{
+ internal abstract class GcmUtilities
+ {
+ private const uint E1 = 0xe1000000;
+ private const ulong E1L = (ulong)E1 << 32;
+
+ private static uint[] GenerateLookup()
+ {
+ uint[] lookup = new uint[256];
+
+ for (int c = 0; c < 256; ++c)
+ {
+ uint v = 0;
+ for (int i = 7; i >= 0; --i)
+ {
+ if ((c & (1 << i)) != 0)
+ {
+ v ^= (E1 >> (7 - i));
+ }
+ }
+ lookup[c] = v;
+ }
+
+ return lookup;
+ }
+
+ private static readonly uint[] LOOKUP = GenerateLookup();
+
+ internal static byte[] OneAsBytes()
+ {
+ byte[] tmp = new byte[16];
+ tmp[0] = 0x80;
+ return tmp;
+ }
+
+ internal static uint[] OneAsUints()
+ {
+ uint[] tmp = new uint[4];
+ tmp[0] = 0x80000000;
+ return tmp;
+ }
+
+ internal static ulong[] OneAsUlongs()
+ {
+ ulong[] tmp = new ulong[2];
+ tmp[0] = 1UL << 63;
+ return tmp;
+ }
+
+ internal static byte[] AsBytes(uint[] x)
+ {
+ return Pack.UInt32_To_BE(x);
+ }
+
+ internal static void AsBytes(uint[] x, byte[] z)
+ {
+ Pack.UInt32_To_BE(x, z, 0);
+ }
+
+ internal static byte[] AsBytes(ulong[] x)
+ {
+ byte[] z = new byte[16];
+ Pack.UInt64_To_BE(x, z, 0);
+ return z;
+ }
+
+ internal static void AsBytes(ulong[] x, byte[] z)
+ {
+ Pack.UInt64_To_BE(x, z, 0);
+ }
+
+ internal static uint[] AsUints(byte[] bs)
+ {
+ uint[] output = new uint[4];
+ Pack.BE_To_UInt32(bs, 0, output);
+ return output;
+ }
+
+ internal static void AsUints(byte[] bs, uint[] output)
+ {
+ Pack.BE_To_UInt32(bs, 0, output);
+ }
+
+ internal static ulong[] AsUlongs(byte[] x)
+ {
+ ulong[] z = new ulong[2];
+ Pack.BE_To_UInt64(x, 0, z);
+ return z;
+ }
+
+ public static void AsUlongs(byte[] x, ulong[] z)
+ {
+ Pack.BE_To_UInt64(x, 0, z);
+ }
+
+ internal static void Multiply(byte[] x, byte[] y)
+ {
+ uint[] t1 = GcmUtilities.AsUints(x);
+ uint[] t2 = GcmUtilities.AsUints(y);
+ GcmUtilities.Multiply(t1, t2);
+ GcmUtilities.AsBytes(t1, x);
+ }
+
+ internal static void Multiply(uint[] x, uint[] y)
+ {
+ uint r00 = x[0], r01 = x[1], r02 = x[2], r03 = x[3];
+ uint r10 = 0, r11 = 0, r12 = 0, r13 = 0;
+
+ for (int i = 0; i < 4; ++i)
+ {
+ int bits = (int)y[i];
+ for (int j = 0; j < 32; ++j)
+ {
+ uint m1 = (uint)(bits >> 31); bits <<= 1;
+ r10 ^= (r00 & m1);
+ r11 ^= (r01 & m1);
+ r12 ^= (r02 & m1);
+ r13 ^= (r03 & m1);
+
+ uint m2 = (uint)((int)(r03 << 31) >> 8);
+ r03 = (r03 >> 1) | (r02 << 31);
+ r02 = (r02 >> 1) | (r01 << 31);
+ r01 = (r01 >> 1) | (r00 << 31);
+ r00 = (r00 >> 1) ^ (m2 & E1);
+ }
+ }
+
+ x[0] = r10;
+ x[1] = r11;
+ x[2] = r12;
+ x[3] = r13;
+ }
+
+ internal static void Multiply(ulong[] x, ulong[] y)
+ {
+ ulong r00 = x[0], r01 = x[1], r10 = 0, r11 = 0;
+
+ for (int i = 0; i < 2; ++i)
+ {
+ long bits = (long)y[i];
+ for (int j = 0; j < 64; ++j)
+ {
+ ulong m1 = (ulong)(bits >> 63); bits <<= 1;
+ r10 ^= (r00 & m1);
+ r11 ^= (r01 & m1);
+
+ ulong m2 = (ulong)((long)(r01 << 63) >> 8);
+ r01 = (r01 >> 1) | (r00 << 63);
+ r00 = (r00 >> 1) ^ (m2 & E1L);
+ }
+ }
+
+ x[0] = r10;
+ x[1] = r11;
+ }
+
+ // P is the value with only bit i=1 set
+ internal static void MultiplyP(uint[] x)
+ {
+ uint m = (uint)((int)ShiftRight(x) >> 8);
+ x[0] ^= (m & E1);
+ }
+
+ internal static void MultiplyP(uint[] x, uint[] z)
+ {
+ uint m = (uint)((int)ShiftRight(x, z) >> 8);
+ z[0] ^= (m & E1);
+ }
+
+ internal static void MultiplyP8(uint[] x)
+ {
+// for (int i = 8; i != 0; --i)
+// {
+// MultiplyP(x);
+// }
+
+ uint c = ShiftRightN(x, 8);
+ x[0] ^= LOOKUP[c >> 24];
+ }
+
+ internal static void MultiplyP8(uint[] x, uint[] y)
+ {
+ uint c = ShiftRightN(x, 8, y);
+ y[0] ^= LOOKUP[c >> 24];
+ }
+
+ internal static uint ShiftRight(uint[] x)
+ {
+ uint b = x[0];
+ x[0] = b >> 1;
+ uint c = b << 31;
+ b = x[1];
+ x[1] = (b >> 1) | c;
+ c = b << 31;
+ b = x[2];
+ x[2] = (b >> 1) | c;
+ c = b << 31;
+ b = x[3];
+ x[3] = (b >> 1) | c;
+ return b << 31;
+ }
+
+ internal static uint ShiftRight(uint[] x, uint[] z)
+ {
+ uint b = x[0];
+ z[0] = b >> 1;
+ uint c = b << 31;
+ b = x[1];
+ z[1] = (b >> 1) | c;
+ c = b << 31;
+ b = x[2];
+ z[2] = (b >> 1) | c;
+ c = b << 31;
+ b = x[3];
+ z[3] = (b >> 1) | c;
+ return b << 31;
+ }
+
+ internal static uint ShiftRightN(uint[] x, int n)
+ {
+ uint b = x[0]; int nInv = 32 - n;
+ x[0] = b >> n;
+ uint c = b << nInv;
+ b = x[1];
+ x[1] = (b >> n) | c;
+ c = b << nInv;
+ b = x[2];
+ x[2] = (b >> n) | c;
+ c = b << nInv;
+ b = x[3];
+ x[3] = (b >> n) | c;
+ return b << nInv;
+ }
+
+ internal static uint ShiftRightN(uint[] x, int n, uint[] z)
+ {
+ uint b = x[0]; int nInv = 32 - n;
+ z[0] = b >> n;
+ uint c = b << nInv;
+ b = x[1];
+ z[1] = (b >> n) | c;
+ c = b << nInv;
+ b = x[2];
+ z[2] = (b >> n) | c;
+ c = b << nInv;
+ b = x[3];
+ z[3] = (b >> n) | c;
+ return b << nInv;
+ }
+
+ internal static void Xor(byte[] x, byte[] y)
+ {
+ int i = 0;
+ do
+ {
+ x[i] ^= y[i]; ++i;
+ x[i] ^= y[i]; ++i;
+ x[i] ^= y[i]; ++i;
+ x[i] ^= y[i]; ++i;
+ }
+ while (i < 16);
+ }
+
+ internal static void Xor(byte[] x, byte[] y, int yOff)
+ {
+ int i = 0;
+ do
+ {
+ x[i] ^= y[yOff + i]; ++i;
+ x[i] ^= y[yOff + i]; ++i;
+ x[i] ^= y[yOff + i]; ++i;
+ x[i] ^= y[yOff + i]; ++i;
+ }
+ while (i < 16);
+ }
+
+ internal static void Xor(byte[] x, int xOff, byte[] y, int yOff, byte[] z, int zOff)
+ {
+ int i = 0;
+ do
+ {
+ z[zOff + i] = (byte)(x[xOff + i] ^ y[yOff + i]); ++i;
+ z[zOff + i] = (byte)(x[xOff + i] ^ y[yOff + i]); ++i;
+ z[zOff + i] = (byte)(x[xOff + i] ^ y[yOff + i]); ++i;
+ z[zOff + i] = (byte)(x[xOff + i] ^ y[yOff + i]); ++i;
+ }
+ while (i < 16);
+ }
+
+ internal static void Xor(byte[] x, byte[] y, int yOff, int yLen)
+ {
+ while (--yLen >= 0)
+ {
+ x[yLen] ^= y[yOff + yLen];
+ }
+ }
+
+ internal static void Xor(byte[] x, int xOff, byte[] y, int yOff, int len)
+ {
+ while (--len >= 0)
+ {
+ x[xOff + len] ^= y[yOff + len];
+ }
+ }
+
+ internal static void Xor(byte[] x, byte[] y, byte[] z)
+ {
+ int i = 0;
+ do
+ {
+ z[i] = (byte)(x[i] ^ y[i]); ++i;
+ z[i] = (byte)(x[i] ^ y[i]); ++i;
+ z[i] = (byte)(x[i] ^ y[i]); ++i;
+ z[i] = (byte)(x[i] ^ y[i]); ++i;
+ }
+ while (i < 16);
+ }
+
+ internal static void Xor(uint[] x, uint[] y)
+ {
+ x[0] ^= y[0];
+ x[1] ^= y[1];
+ x[2] ^= y[2];
+ x[3] ^= y[3];
+ }
+
+ internal static void Xor(uint[] x, uint[] y, uint[] z)
+ {
+ z[0] = x[0] ^ y[0];
+ z[1] = x[1] ^ y[1];
+ z[2] = x[2] ^ y[2];
+ z[3] = x[3] ^ y[3];
+ }
+
+ internal static void Xor(ulong[] x, ulong[] y)
+ {
+ x[0] ^= y[0];
+ x[1] ^= y[1];
+ }
+
+ internal static void Xor(ulong[] x, ulong[] y, ulong[] z)
+ {
+ z[0] = x[0] ^ y[0];
+ z[1] = x[1] ^ y[1];
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/GcmUtilities.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/GcmUtilities.cs.meta
new file mode 100644
index 00000000..3cbe3561
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/GcmUtilities.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a537b491bcdd0934aac526f2ac481e5e
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/IGcmExponentiator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/IGcmExponentiator.cs
new file mode 100644
index 00000000..09bc1632
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/IGcmExponentiator.cs
@@ -0,0 +1,14 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes.Gcm
+{
+ public interface IGcmExponentiator
+ {
+ void Init(byte[] x);
+ void ExponentiateX(long pow, byte[] output);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/IGcmExponentiator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/IGcmExponentiator.cs.meta
new file mode 100644
index 00000000..9caa76f6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/IGcmExponentiator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 2b9360b15af87e1479595647271315ad
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/IGcmMultiplier.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/IGcmMultiplier.cs
new file mode 100644
index 00000000..966c02c6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/IGcmMultiplier.cs
@@ -0,0 +1,14 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes.Gcm
+{
+ public interface IGcmMultiplier
+ {
+ void Init(byte[] H);
+ void MultiplyH(byte[] x);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/IGcmMultiplier.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/IGcmMultiplier.cs.meta
new file mode 100644
index 00000000..da3d384c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/IGcmMultiplier.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c18943b1cef80dd40b832574fd4e810e
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/Tables1kGcmExponentiator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/Tables1kGcmExponentiator.cs
new file mode 100644
index 00000000..57104a36
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/Tables1kGcmExponentiator.cs
@@ -0,0 +1,63 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes.Gcm
+{
+ public class Tables1kGcmExponentiator
+ : IGcmExponentiator
+ {
+ // A lookup table of the power-of-two powers of 'x'
+ // - lookupPowX2[i] = x^(2^i)
+ private IList lookupPowX2;
+
+ public void Init(byte[] x)
+ {
+ uint[] y = GcmUtilities.AsUints(x);
+ if (lookupPowX2 != null && Arrays.AreEqual(y, (uint[])lookupPowX2[0]))
+ return;
+
+ lookupPowX2 = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(8);
+ lookupPowX2.Add(y);
+ }
+
+ public void ExponentiateX(long pow, byte[] output)
+ {
+ uint[] y = GcmUtilities.OneAsUints();
+ int bit = 0;
+ while (pow > 0)
+ {
+ if ((pow & 1L) != 0)
+ {
+ EnsureAvailable(bit);
+ GcmUtilities.Multiply(y, (uint[])lookupPowX2[bit]);
+ }
+ ++bit;
+ pow >>= 1;
+ }
+
+ GcmUtilities.AsBytes(y, output);
+ }
+
+ private void EnsureAvailable(int bit)
+ {
+ int count = lookupPowX2.Count;
+ if (count <= bit)
+ {
+ uint[] tmp = (uint[])lookupPowX2[count - 1];
+ do
+ {
+ tmp = Arrays.Clone(tmp);
+ GcmUtilities.Multiply(tmp, tmp);
+ lookupPowX2.Add(tmp);
+ }
+ while (++count <= bit);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/Tables1kGcmExponentiator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/Tables1kGcmExponentiator.cs.meta
new file mode 100644
index 00000000..87abe9a6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/Tables1kGcmExponentiator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: fb76a60bca7933e4fa45510eada87774
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/Tables64kGcmMultiplier.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/Tables64kGcmMultiplier.cs
new file mode 100644
index 00000000..a8c93fc3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/Tables64kGcmMultiplier.cs
@@ -0,0 +1,81 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes.Gcm
+{
+ public class Tables64kGcmMultiplier
+ : IGcmMultiplier
+ {
+ private byte[] H;
+ private uint[][][] M;
+
+ public void Init(byte[] H)
+ {
+ if (M == null)
+ {
+ M = new uint[16][][];
+ }
+ else if (Arrays.AreEqual(this.H, H))
+ {
+ return;
+ }
+
+ this.H = Arrays.Clone(H);
+
+ M[0] = new uint[256][];
+ M[0][0] = new uint[4];
+ M[0][128] = GcmUtilities.AsUints(H);
+ for (int j = 64; j >= 1; j >>= 1)
+ {
+ uint[] tmp = (uint[])M[0][j + j].Clone();
+ GcmUtilities.MultiplyP(tmp);
+ M[0][j] = tmp;
+ }
+ for (int i = 0; ; )
+ {
+ for (int j = 2; j < 256; j += j)
+ {
+ for (int k = 1; k < j; ++k)
+ {
+ uint[] tmp = (uint[])M[i][j].Clone();
+ GcmUtilities.Xor(tmp, M[i][k]);
+ M[i][j + k] = tmp;
+ }
+ }
+
+ if (++i == 16) return;
+
+ M[i] = new uint[256][];
+ M[i][0] = new uint[4];
+ for (int j = 128; j > 0; j >>= 1)
+ {
+ uint[] tmp = (uint[])M[i - 1][j].Clone();
+ GcmUtilities.MultiplyP8(tmp);
+ M[i][j] = tmp;
+ }
+ }
+ }
+
+ public void MultiplyH(byte[] x)
+ {
+ uint[] z = new uint[4];
+ for (int i = 0; i != 16; ++i)
+ {
+ //GcmUtilities.Xor(z, M[i][x[i]]);
+ uint[] m = M[i][x[i]];
+ z[0] ^= m[0];
+ z[1] ^= m[1];
+ z[2] ^= m[2];
+ z[3] ^= m[3];
+ }
+
+ Pack.UInt32_To_BE(z, x, 0);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/Tables64kGcmMultiplier.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/Tables64kGcmMultiplier.cs.meta
new file mode 100644
index 00000000..10e5681d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/Tables64kGcmMultiplier.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 11e15117f8c61854a8ed870e37ef1af8
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/Tables8kGcmMultiplier.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/Tables8kGcmMultiplier.cs
new file mode 100644
index 00000000..e92cb2e3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/Tables8kGcmMultiplier.cs
@@ -0,0 +1,108 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes.Gcm
+{
+ public sealed class Tables8kGcmMultiplier
+ : IGcmMultiplier
+ {
+ private byte[] H;
+ private uint[][][] M;
+
+ public void Init(byte[] H)
+ {
+ if (M == null)
+ {
+ M = new uint[32][][];
+ }
+ else if (Arrays.AreEqual(this.H, H))
+ {
+ return;
+ }
+
+ this.H = Arrays.Clone(H);
+
+ M[0] = new uint[16][];
+ M[1] = new uint[16][];
+ M[0][0] = new uint[4];
+ M[1][0] = new uint[4];
+ M[1][8] = GcmUtilities.AsUints(H);
+
+ for (int j = 4; j >= 1; j >>= 1)
+ {
+ uint[] tmp = (uint[])M[1][j + j].Clone();
+ GcmUtilities.MultiplyP(tmp);
+ M[1][j] = tmp;
+ }
+
+ {
+ uint[] tmp = (uint[])M[1][1].Clone();
+ GcmUtilities.MultiplyP(tmp);
+ M[0][8] = tmp;
+ }
+
+ for (int j = 4; j >= 1; j >>= 1)
+ {
+ uint[] tmp = (uint[])M[0][j + j].Clone();
+ GcmUtilities.MultiplyP(tmp);
+ M[0][j] = tmp;
+ }
+
+ for (int i = 0; ; )
+ {
+ for (int j = 2; j < 16; j += j)
+ {
+ for (int k = 1; k < j; ++k)
+ {
+ uint[] tmp = (uint[])M[i][j].Clone();
+ GcmUtilities.Xor(tmp, M[i][k]);
+ M[i][j + k] = tmp;
+ }
+ }
+
+ if (++i == 32) return;
+
+ if (i > 1)
+ {
+ M[i] = new uint[16][];
+ M[i][0] = new uint[4];
+ for (int j = 8; j > 0; j >>= 1)
+ {
+ uint[] tmp = (uint[])M[i - 2][j].Clone();
+ GcmUtilities.MultiplyP8(tmp);
+ M[i][j] = tmp;
+ }
+ }
+ }
+ }
+ uint[] z = new uint[4];
+
+ public void MultiplyH(byte[] x)
+ {
+ Array.Clear(z, 0, z.Length);
+ for (int i = 15; i >= 0; --i)
+ {
+ //GcmUtilities.Xor(z, M[i + i][x[i] & 0x0f]);
+ uint[] m = M[i + i][x[i] & 0x0f];
+ z[0] ^= m[0];
+ z[1] ^= m[1];
+ z[2] ^= m[2];
+ z[3] ^= m[3];
+ //GcmUtilities.Xor(z, M[i + i + 1][(x[i] & 0xf0) >> 4]);
+ m = M[i + i + 1][(x[i] & 0xf0) >> 4];
+ z[0] ^= m[0];
+ z[1] ^= m[1];
+ z[2] ^= m[2];
+ z[3] ^= m[3];
+ }
+
+ Pack.UInt32_To_BE(z, x, 0);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/Tables8kGcmMultiplier.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/Tables8kGcmMultiplier.cs.meta
new file mode 100644
index 00000000..117d3451
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/modes/gcm/Tables8kGcmMultiplier.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: d0ed8793a414fb442ad8987957e3d03f
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators.meta
new file mode 100644
index 00000000..4643ca42
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 68a42d586834bc5489474f303f2686c1
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/Asn1Signature.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/Asn1Signature.cs
new file mode 100644
index 00000000..c367bd1d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/Asn1Signature.cs
@@ -0,0 +1,388 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Oiw;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.TeleTrust;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.IO;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Operators
+{
+ internal class X509Utilities
+ {
+ private static readonly Asn1Null derNull = DerNull.Instance;
+
+ private static readonly IDictionary algorithms = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ private static readonly IDictionary exParams = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ private static readonly ISet noParams = new HashSet();
+
+ static X509Utilities()
+ {
+ algorithms.Add("MD2WITHRSAENCRYPTION", PkcsObjectIdentifiers.MD2WithRsaEncryption);
+ algorithms.Add("MD2WITHRSA", PkcsObjectIdentifiers.MD2WithRsaEncryption);
+ algorithms.Add("MD5WITHRSAENCRYPTION", PkcsObjectIdentifiers.MD5WithRsaEncryption);
+ algorithms.Add("MD5WITHRSA", PkcsObjectIdentifiers.MD5WithRsaEncryption);
+ algorithms.Add("SHA1WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha1WithRsaEncryption);
+ algorithms.Add("SHA1WITHRSA", PkcsObjectIdentifiers.Sha1WithRsaEncryption);
+ algorithms.Add("SHA224WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha224WithRsaEncryption);
+ algorithms.Add("SHA224WITHRSA", PkcsObjectIdentifiers.Sha224WithRsaEncryption);
+ algorithms.Add("SHA256WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha256WithRsaEncryption);
+ algorithms.Add("SHA256WITHRSA", PkcsObjectIdentifiers.Sha256WithRsaEncryption);
+ algorithms.Add("SHA384WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha384WithRsaEncryption);
+ algorithms.Add("SHA384WITHRSA", PkcsObjectIdentifiers.Sha384WithRsaEncryption);
+ algorithms.Add("SHA512WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512WithRsaEncryption);
+ algorithms.Add("SHA512WITHRSA", PkcsObjectIdentifiers.Sha512WithRsaEncryption);
+ algorithms.Add("SHA1WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss);
+ algorithms.Add("SHA224WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss);
+ algorithms.Add("SHA256WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss);
+ algorithms.Add("SHA384WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss);
+ algorithms.Add("SHA512WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss);
+ algorithms.Add("RIPEMD160WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160);
+ algorithms.Add("RIPEMD160WITHRSA", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160);
+ algorithms.Add("RIPEMD128WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128);
+ algorithms.Add("RIPEMD128WITHRSA", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128);
+ algorithms.Add("RIPEMD256WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256);
+ algorithms.Add("RIPEMD256WITHRSA", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256);
+ algorithms.Add("SHA1WITHDSA", X9ObjectIdentifiers.IdDsaWithSha1);
+ algorithms.Add("DSAWITHSHA1", X9ObjectIdentifiers.IdDsaWithSha1);
+ algorithms.Add("SHA224WITHDSA", NistObjectIdentifiers.DsaWithSha224);
+ algorithms.Add("SHA256WITHDSA", NistObjectIdentifiers.DsaWithSha256);
+ algorithms.Add("SHA384WITHDSA", NistObjectIdentifiers.DsaWithSha384);
+ algorithms.Add("SHA512WITHDSA", NistObjectIdentifiers.DsaWithSha512);
+ algorithms.Add("SHA1WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha1);
+ algorithms.Add("ECDSAWITHSHA1", X9ObjectIdentifiers.ECDsaWithSha1);
+ algorithms.Add("SHA224WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha224);
+ algorithms.Add("SHA256WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha256);
+ algorithms.Add("SHA384WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha384);
+ algorithms.Add("SHA512WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha512);
+ algorithms.Add("GOST3411WITHGOST3410", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94);
+ algorithms.Add("GOST3411WITHGOST3410-94", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94);
+ algorithms.Add("GOST3411WITHECGOST3410", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001);
+ algorithms.Add("GOST3411WITHECGOST3410-2001", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001);
+ algorithms.Add("GOST3411WITHGOST3410-2001", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001);
+
+ //
+ // According to RFC 3279, the ASN.1 encoding SHALL (id-dsa-with-sha1) or MUST (ecdsa-with-SHA*) omit the parameters field.
+ // The parameters field SHALL be NULL for RSA based signature algorithms.
+ //
+ noParams.Add(X9ObjectIdentifiers.ECDsaWithSha1);
+ noParams.Add(X9ObjectIdentifiers.ECDsaWithSha224);
+ noParams.Add(X9ObjectIdentifiers.ECDsaWithSha256);
+ noParams.Add(X9ObjectIdentifiers.ECDsaWithSha384);
+ noParams.Add(X9ObjectIdentifiers.ECDsaWithSha512);
+ noParams.Add(X9ObjectIdentifiers.IdDsaWithSha1);
+ noParams.Add(NistObjectIdentifiers.DsaWithSha224);
+ noParams.Add(NistObjectIdentifiers.DsaWithSha256);
+ noParams.Add(NistObjectIdentifiers.DsaWithSha384);
+ noParams.Add(NistObjectIdentifiers.DsaWithSha512);
+
+ //
+ // RFC 4491
+ //
+ noParams.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94);
+ noParams.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001);
+
+ //
+ // explicit params
+ //
+ AlgorithmIdentifier sha1AlgId = new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance);
+ exParams.Add("SHA1WITHRSAANDMGF1", CreatePssParams(sha1AlgId, 20));
+
+ AlgorithmIdentifier sha224AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha224, DerNull.Instance);
+ exParams.Add("SHA224WITHRSAANDMGF1", CreatePssParams(sha224AlgId, 28));
+
+ AlgorithmIdentifier sha256AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha256, DerNull.Instance);
+ exParams.Add("SHA256WITHRSAANDMGF1", CreatePssParams(sha256AlgId, 32));
+
+ AlgorithmIdentifier sha384AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha384, DerNull.Instance);
+ exParams.Add("SHA384WITHRSAANDMGF1", CreatePssParams(sha384AlgId, 48));
+
+ AlgorithmIdentifier sha512AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha512, DerNull.Instance);
+ exParams.Add("SHA512WITHRSAANDMGF1", CreatePssParams(sha512AlgId, 64));
+ }
+
+ /**
+ * Return the digest algorithm using one of the standard JCA string
+ * representations rather than the algorithm identifier (if possible).
+ */
+ private static string GetDigestAlgName(
+ DerObjectIdentifier digestAlgOID)
+ {
+ if (PkcsObjectIdentifiers.MD5.Equals(digestAlgOID))
+ {
+ return "MD5";
+ }
+ else if (OiwObjectIdentifiers.IdSha1.Equals(digestAlgOID))
+ {
+ return "SHA1";
+ }
+ else if (NistObjectIdentifiers.IdSha224.Equals(digestAlgOID))
+ {
+ return "SHA224";
+ }
+ else if (NistObjectIdentifiers.IdSha256.Equals(digestAlgOID))
+ {
+ return "SHA256";
+ }
+ else if (NistObjectIdentifiers.IdSha384.Equals(digestAlgOID))
+ {
+ return "SHA384";
+ }
+ else if (NistObjectIdentifiers.IdSha512.Equals(digestAlgOID))
+ {
+ return "SHA512";
+ }
+ else if (TeleTrusTObjectIdentifiers.RipeMD128.Equals(digestAlgOID))
+ {
+ return "RIPEMD128";
+ }
+ else if (TeleTrusTObjectIdentifiers.RipeMD160.Equals(digestAlgOID))
+ {
+ return "RIPEMD160";
+ }
+ else if (TeleTrusTObjectIdentifiers.RipeMD256.Equals(digestAlgOID))
+ {
+ return "RIPEMD256";
+ }
+ else if (CryptoProObjectIdentifiers.GostR3411.Equals(digestAlgOID))
+ {
+ return "GOST3411";
+ }
+ else
+ {
+ return digestAlgOID.Id;
+ }
+ }
+
+ internal static string GetSignatureName(AlgorithmIdentifier sigAlgId)
+ {
+ Asn1Encodable parameters = sigAlgId.Parameters;
+
+ if (parameters != null && !derNull.Equals(parameters))
+ {
+ if (sigAlgId.Algorithm.Equals(PkcsObjectIdentifiers.IdRsassaPss))
+ {
+ RsassaPssParameters rsaParams = RsassaPssParameters.GetInstance(parameters);
+
+ return GetDigestAlgName(rsaParams.HashAlgorithm.Algorithm) + "withRSAandMGF1";
+ }
+ if (sigAlgId.Algorithm.Equals(X9ObjectIdentifiers.ECDsaWithSha2))
+ {
+ Asn1Sequence ecDsaParams = Asn1Sequence.GetInstance(parameters);
+
+ return GetDigestAlgName((DerObjectIdentifier)ecDsaParams[0]) + "withECDSA";
+ }
+ }
+
+ return sigAlgId.Algorithm.Id;
+ }
+
+ private static RsassaPssParameters CreatePssParams(
+ AlgorithmIdentifier hashAlgId,
+ int saltSize)
+ {
+ return new RsassaPssParameters(
+ hashAlgId,
+ new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, hashAlgId),
+ new DerInteger(saltSize),
+ new DerInteger(1));
+ }
+
+ internal static DerObjectIdentifier GetAlgorithmOid(
+ string algorithmName)
+ {
+ algorithmName = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithmName);
+
+ if (algorithms.Contains(algorithmName))
+ {
+ return (DerObjectIdentifier) algorithms[algorithmName];
+ }
+
+ return new DerObjectIdentifier(algorithmName);
+ }
+
+ internal static AlgorithmIdentifier GetSigAlgID(
+ DerObjectIdentifier sigOid,
+ string algorithmName)
+ {
+ if (noParams.Contains(sigOid))
+ {
+ return new AlgorithmIdentifier(sigOid);
+ }
+
+ algorithmName = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithmName);
+
+ if (exParams.Contains(algorithmName))
+ {
+ return new AlgorithmIdentifier(sigOid, (Asn1Encodable) exParams[algorithmName]);
+ }
+
+ return new AlgorithmIdentifier(sigOid, DerNull.Instance);
+ }
+
+ internal static IEnumerable GetAlgNames()
+ {
+ return new EnumerableProxy(algorithms.Keys);
+ }
+ }
+
+ ///
+ /// Calculator factory class for signature generation in ASN.1 based profiles that use an AlgorithmIdentifier to preserve
+ /// signature algorithm details.
+ ///
+ public class Asn1SignatureFactory
+ : ISignatureFactory
+ {
+ private readonly AlgorithmIdentifier algID;
+ private readonly string algorithm;
+ private readonly AsymmetricKeyParameter privateKey;
+ private readonly SecureRandom random;
+
+ ///
+ /// Base constructor.
+ ///
+ /// The name of the signature algorithm to use.
+ /// The private key to be used in the signing operation.
+ public Asn1SignatureFactory (string algorithm, AsymmetricKeyParameter privateKey)
+ : this(algorithm, privateKey, null)
+ {
+ }
+
+ ///
+ /// Constructor which also specifies a source of randomness to be used if one is required.
+ ///
+ /// The name of the signature algorithm to use.
+ /// The private key to be used in the signing operation.
+ /// The source of randomness to be used in signature calculation.
+ public Asn1SignatureFactory(string algorithm, AsymmetricKeyParameter privateKey, SecureRandom random)
+ {
+ if (algorithm == null)
+ throw new ArgumentNullException("algorithm");
+ if (privateKey == null)
+ throw new ArgumentNullException("privateKey");
+ if (!privateKey.IsPrivate)
+ throw new ArgumentException("Key for signing must be private", "privateKey");
+
+ DerObjectIdentifier sigOid = X509Utilities.GetAlgorithmOid(algorithm);
+
+ this.algorithm = algorithm;
+ this.privateKey = privateKey;
+ this.random = random;
+ this.algID = X509Utilities.GetSigAlgID(sigOid, algorithm);
+ }
+
+ public Object AlgorithmDetails
+ {
+ get { return this.algID; }
+ }
+
+ public IStreamCalculator CreateCalculator()
+ {
+ ISigner signer = SignerUtilities.InitSigner(algorithm, true, privateKey, random);
+
+ return new DefaultSignatureCalculator(signer);
+ }
+
+ ///
+ /// Allows enumeration of the signature names supported by the verifier provider.
+ ///
+ public static IEnumerable SignatureAlgNames
+ {
+ get { return X509Utilities.GetAlgNames(); }
+ }
+ }
+
+ ///
+ /// Verifier class for signature verification in ASN.1 based profiles that use an AlgorithmIdentifier to preserve
+ /// signature algorithm details.
+ ///
+ public class Asn1VerifierFactory
+ : IVerifierFactory
+ {
+ private readonly AlgorithmIdentifier algID;
+ private readonly AsymmetricKeyParameter publicKey;
+
+ ///
+ /// Base constructor.
+ ///
+ /// The name of the signature algorithm to use.
+ /// The public key to be used in the verification operation.
+ public Asn1VerifierFactory(string algorithm, AsymmetricKeyParameter publicKey)
+ {
+ if (algorithm == null)
+ throw new ArgumentNullException("algorithm");
+ if (publicKey == null)
+ throw new ArgumentNullException("publicKey");
+ if (publicKey.IsPrivate)
+ throw new ArgumentException("Key for verifying must be public", "publicKey");
+
+ DerObjectIdentifier sigOid = X509Utilities.GetAlgorithmOid(algorithm);
+
+ this.publicKey = publicKey;
+ this.algID = X509Utilities.GetSigAlgID(sigOid, algorithm);
+ }
+
+ public Asn1VerifierFactory(AlgorithmIdentifier algorithm, AsymmetricKeyParameter publicKey)
+ {
+ this.publicKey = publicKey;
+ this.algID = algorithm;
+ }
+
+ public Object AlgorithmDetails
+ {
+ get { return this.algID; }
+ }
+
+ public IStreamCalculator CreateCalculator()
+ {
+ ISigner verifier = SignerUtilities.InitSigner(X509Utilities.GetSignatureName(algID), false, publicKey, null);
+
+ return new DefaultVerifierCalculator(verifier);
+ }
+ }
+
+ ///
+ /// Provider class which supports dynamic creation of signature verifiers.
+ ///
+ public class Asn1VerifierFactoryProvider: IVerifierFactoryProvider
+ {
+ private readonly AsymmetricKeyParameter publicKey;
+
+ ///
+ /// Base constructor - specify the public key to be used in verification.
+ ///
+ /// The public key to be used in creating verifiers provided by this object.
+ public Asn1VerifierFactoryProvider(AsymmetricKeyParameter publicKey)
+ {
+ this.publicKey = publicKey;
+ }
+
+ public IVerifierFactory CreateVerifierFactory(Object algorithmDetails)
+ {
+ return new Asn1VerifierFactory((AlgorithmIdentifier)algorithmDetails, publicKey);
+ }
+
+ ///
+ /// Allows enumeration of the signature names supported by the verifier provider.
+ ///
+ public IEnumerable SignatureAlgNames
+ {
+ get { return X509Utilities.GetAlgNames(); }
+ }
+ }
+}
+
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/Asn1Signature.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/Asn1Signature.cs.meta
new file mode 100644
index 00000000..8ab4abdd
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/Asn1Signature.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 3cfa37c567c69d64e94a320d53944aff
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/DefaultSignatureCalculator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/DefaultSignatureCalculator.cs
new file mode 100644
index 00000000..4ed3ece6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/DefaultSignatureCalculator.cs
@@ -0,0 +1,32 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Operators
+{
+ public class DefaultSignatureCalculator
+ : IStreamCalculator
+ {
+ private readonly SignerSink mSignerSink;
+
+ public DefaultSignatureCalculator(ISigner signer)
+ {
+ this.mSignerSink = new SignerSink(signer);
+ }
+
+ public Stream Stream
+ {
+ get { return mSignerSink; }
+ }
+
+ public object GetResult()
+ {
+ return new DefaultSignatureResult(mSignerSink.Signer);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/DefaultSignatureCalculator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/DefaultSignatureCalculator.cs.meta
new file mode 100644
index 00000000..891ce0e7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/DefaultSignatureCalculator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: cd95bd10d03dd5c43a84352032191028
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/DefaultSignatureResult.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/DefaultSignatureResult.cs
new file mode 100644
index 00000000..3d89f999
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/DefaultSignatureResult.cs
@@ -0,0 +1,31 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Operators
+{
+ public class DefaultSignatureResult
+ : IBlockResult
+ {
+ private readonly ISigner mSigner;
+
+ public DefaultSignatureResult(ISigner signer)
+ {
+ this.mSigner = signer;
+ }
+
+ public byte[] Collect()
+ {
+ return mSigner.GenerateSignature();
+ }
+
+ public int Collect(byte[] sig, int sigOff)
+ {
+ byte[] signature = Collect();
+ signature.CopyTo(sig, sigOff);
+ return signature.Length;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/DefaultSignatureResult.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/DefaultSignatureResult.cs.meta
new file mode 100644
index 00000000..60485fe5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/DefaultSignatureResult.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 8713fbe707f798c41802405bcdf53ae3
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/DefaultVerifierCalculator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/DefaultVerifierCalculator.cs
new file mode 100644
index 00000000..aa0a3195
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/DefaultVerifierCalculator.cs
@@ -0,0 +1,32 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Operators
+{
+ public class DefaultVerifierCalculator
+ : IStreamCalculator
+ {
+ private readonly SignerSink mSignerSink;
+
+ public DefaultVerifierCalculator(ISigner signer)
+ {
+ this.mSignerSink = new SignerSink(signer);
+ }
+
+ public Stream Stream
+ {
+ get { return mSignerSink; }
+ }
+
+ public object GetResult()
+ {
+ return new DefaultVerifierResult(mSignerSink.Signer);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/DefaultVerifierCalculator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/DefaultVerifierCalculator.cs.meta
new file mode 100644
index 00000000..a1ba2219
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/DefaultVerifierCalculator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 17f76450775ae0d458726adec8a5ad4c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/DefaultVerifierResult.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/DefaultVerifierResult.cs
new file mode 100644
index 00000000..1f25d4b4
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/DefaultVerifierResult.cs
@@ -0,0 +1,33 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Operators
+{
+ public class DefaultVerifierResult
+ : IVerifier
+ {
+ private readonly ISigner mSigner;
+
+ public DefaultVerifierResult(ISigner signer)
+ {
+ this.mSigner = signer;
+ }
+
+ public bool IsVerified(byte[] signature)
+ {
+ return mSigner.VerifySignature(signature);
+ }
+
+ public bool IsVerified(byte[] sig, int sigOff, int sigLen)
+ {
+ byte[] signature = Arrays.CopyOfRange(sig, sigOff, sigOff + sigLen);
+
+ return IsVerified(signature);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/DefaultVerifierResult.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/DefaultVerifierResult.cs.meta
new file mode 100644
index 00000000..87f2fe8b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/operators/DefaultVerifierResult.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 6c49a906488d90c4dbe543d0d477d26d
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings.meta
new file mode 100644
index 00000000..d6c9e47d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: c60458b835ab8c54ba3ae600588beeeb
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/BlockCipherPadding.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/BlockCipherPadding.cs
new file mode 100644
index 00000000..33d32ecf
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/BlockCipherPadding.cs
@@ -0,0 +1,47 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Paddings
+{
+ /**
+ * Block cipher padders are expected to conform to this interface
+ */
+ public interface IBlockCipherPadding
+ {
+ /**
+ * Initialise the padder.
+ *
+ * @param param parameters, if any required.
+ */
+ void Init(SecureRandom random);
+ //throws ArgumentException;
+
+ /**
+ * Return the name of the algorithm the cipher implements.
+ *
+ * @return the name of the algorithm the cipher implements.
+ */
+ string PaddingName { get; }
+
+ /**
+ * add the pad bytes to the passed in block, returning the
+ * number of bytes added.
+ */
+ int AddPadding(byte[] input, int inOff);
+
+ /**
+ * return the number of pad bytes present in the block.
+ * @exception InvalidCipherTextException if the padding is badly formed
+ * or invalid.
+ */
+ int PadCount(byte[] input);
+ //throws InvalidCipherTextException;
+ }
+
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/BlockCipherPadding.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/BlockCipherPadding.cs.meta
new file mode 100644
index 00000000..8e84b310
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/BlockCipherPadding.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 4f24f6689dd124343ab88b53bbef3e26
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/ISO10126d2Padding.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/ISO10126d2Padding.cs
new file mode 100644
index 00000000..313b3224
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/ISO10126d2Padding.cs
@@ -0,0 +1,80 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Paddings
+{
+
+ /**
+ * A padder that adds ISO10126-2 padding to a block.
+ */
+ public class ISO10126d2Padding: IBlockCipherPadding
+ {
+ private SecureRandom random;
+
+ /**
+ * Initialise the padder.
+ *
+ * @param random a SecureRandom if available.
+ */
+ public void Init(
+ SecureRandom random)
+ //throws ArgumentException
+ {
+ this.random = (random != null) ? random : new SecureRandom();
+ }
+
+ /**
+ * Return the name of the algorithm the cipher implements.
+ *
+ * @return the name of the algorithm the cipher implements.
+ */
+ public string PaddingName
+ {
+ get { return "ISO10126-2"; }
+ }
+
+ /**
+ * add the pad bytes to the passed in block, returning the
+ * number of bytes added.
+ */
+ public int AddPadding(
+ byte[] input,
+ int inOff)
+ {
+ byte code = (byte)(input.Length - inOff);
+
+ while (inOff < (input.Length - 1))
+ {
+ input[inOff] = (byte)random.NextInt();
+ inOff++;
+ }
+
+ input[inOff] = code;
+
+ return code;
+ }
+
+ /**
+ * return the number of pad bytes present in the block.
+ */
+ public int PadCount(byte[] input)
+ //throws InvalidCipherTextException
+ {
+ int count = input[input.Length - 1] & 0xff;
+
+ if (count > input.Length)
+ {
+ throw new InvalidCipherTextException("pad block corrupted");
+ }
+
+ return count;
+ }
+ }
+
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/ISO10126d2Padding.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/ISO10126d2Padding.cs.meta
new file mode 100644
index 00000000..44806757
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/ISO10126d2Padding.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 81e4c7d79b217c44da9b2dc55d48fb3d
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/ISO7816d4Padding.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/ISO7816d4Padding.cs
new file mode 100644
index 00000000..18206dc8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/ISO7816d4Padding.cs
@@ -0,0 +1,83 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Paddings
+{
+ /**
+ * A padder that adds the padding according to the scheme referenced in
+ * ISO 7814-4 - scheme 2 from ISO 9797-1. The first byte is 0x80, rest is 0x00
+ */
+ public class ISO7816d4Padding
+ : IBlockCipherPadding
+ {
+ /**
+ * Initialise the padder.
+ *
+ * @param random - a SecureRandom if available.
+ */
+ public void Init(
+ SecureRandom random)
+ {
+ // nothing to do.
+ }
+
+ /**
+ * Return the name of the algorithm the padder implements.
+ *
+ * @return the name of the algorithm the padder implements.
+ */
+ public string PaddingName
+ {
+ get { return "ISO7816-4"; }
+ }
+
+ /**
+ * add the pad bytes to the passed in block, returning the
+ * number of bytes added.
+ */
+ public int AddPadding(
+ byte[] input,
+ int inOff)
+ {
+ int added = (input.Length - inOff);
+
+ input[inOff]= (byte) 0x80;
+ inOff ++;
+
+ while (inOff < input.Length)
+ {
+ input[inOff] = (byte) 0;
+ inOff++;
+ }
+
+ return added;
+ }
+
+ /**
+ * return the number of pad bytes present in the block.
+ */
+ public int PadCount(
+ byte[] input)
+ {
+ int count = input.Length - 1;
+
+ while (count > 0 && input[count] == 0)
+ {
+ count--;
+ }
+
+ if (input[count] != (byte)0x80)
+ {
+ throw new InvalidCipherTextException("pad block corrupted");
+ }
+
+ return input.Length - count;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/ISO7816d4Padding.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/ISO7816d4Padding.cs.meta
new file mode 100644
index 00000000..6ee22178
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/ISO7816d4Padding.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 26e9e3006aa8e5b49939429f343fbea4
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/PaddedBufferedBlockCipher.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/PaddedBufferedBlockCipher.cs
new file mode 100644
index 00000000..c68a5a76
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/PaddedBufferedBlockCipher.cs
@@ -0,0 +1,289 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Paddings
+{
+ /**
+ * A wrapper class that allows block ciphers to be used to process data in
+ * a piecemeal fashion with padding. The PaddedBufferedBlockCipher
+ * outputs a block only when the buffer is full and more data is being added,
+ * or on a doFinal (unless the current block in the buffer is a pad block).
+ * The default padding mechanism used is the one outlined in Pkcs5/Pkcs7.
+ */
+ public class PaddedBufferedBlockCipher
+ : BufferedBlockCipher
+ {
+ private readonly IBlockCipherPadding padding;
+
+ /**
+ * Create a buffered block cipher with the desired padding.
+ *
+ * @param cipher the underlying block cipher this buffering object wraps.
+ * @param padding the padding type.
+ */
+ public PaddedBufferedBlockCipher(
+ IBlockCipher cipher,
+ IBlockCipherPadding padding)
+ {
+ this.cipher = cipher;
+ this.padding = padding;
+
+ buf = new byte[cipher.GetBlockSize()];
+ bufOff = 0;
+ }
+
+ /**
+ * Create a buffered block cipher Pkcs7 padding
+ *
+ * @param cipher the underlying block cipher this buffering object wraps.
+ */
+ public PaddedBufferedBlockCipher(
+ IBlockCipher cipher)
+ : this(cipher, new Pkcs7Padding()) { }
+
+ /**
+ * initialise the cipher.
+ *
+ * @param forEncryption if true the cipher is initialised for
+ * encryption, if false for decryption.
+ * @param param the key and other data required by the cipher.
+ * @exception ArgumentException if the parameters argument is
+ * inappropriate.
+ */
+ public override void Init(
+ bool forEncryption,
+ ICipherParameters parameters)
+ {
+ this.forEncryption = forEncryption;
+
+ SecureRandom initRandom = null;
+ if (parameters is ParametersWithRandom)
+ {
+ ParametersWithRandom p = (ParametersWithRandom)parameters;
+ initRandom = p.Random;
+ parameters = p.Parameters;
+ }
+
+ Reset();
+ padding.Init(initRandom);
+ cipher.Init(forEncryption, parameters);
+ }
+
+ /**
+ * return the minimum size of the output buffer required for an update
+ * plus a doFinal with an input of len bytes.
+ *
+ * @param len the length of the input.
+ * @return the space required to accommodate a call to update and doFinal
+ * with len bytes of input.
+ */
+ public override int GetOutputSize(
+ int length)
+ {
+ int total = length + bufOff;
+ int leftOver = total % buf.Length;
+
+ if (leftOver == 0)
+ {
+ if (forEncryption)
+ {
+ return total + buf.Length;
+ }
+
+ return total;
+ }
+
+ return total - leftOver + buf.Length;
+ }
+
+ /**
+ * return the size of the output buffer required for an update
+ * an input of len bytes.
+ *
+ * @param len the length of the input.
+ * @return the space required to accommodate a call to update
+ * with len bytes of input.
+ */
+ public override int GetUpdateOutputSize(
+ int length)
+ {
+ int total = length + bufOff;
+ int leftOver = total % buf.Length;
+
+ if (leftOver == 0)
+ {
+ return total - buf.Length;
+ }
+
+ return total - leftOver;
+ }
+
+ /**
+ * process a single byte, producing an output block if necessary.
+ *
+ * @param in the input byte.
+ * @param out the space for any output that might be produced.
+ * @param outOff the offset from which the output will be copied.
+ * @return the number of output bytes copied to out.
+ * @exception DataLengthException if there isn't enough space in out.
+ * @exception InvalidOperationException if the cipher isn't initialised.
+ */
+ public override int ProcessByte(
+ byte input,
+ byte[] output,
+ int outOff)
+ {
+ int resultLen = 0;
+
+ if (bufOff == buf.Length)
+ {
+ resultLen = cipher.ProcessBlock(buf, 0, output, outOff);
+ bufOff = 0;
+ }
+
+ buf[bufOff++] = input;
+
+ return resultLen;
+ }
+
+ /**
+ * process an array of bytes, producing output if necessary.
+ *
+ * @param in the input byte array.
+ * @param inOff the offset at which the input data starts.
+ * @param len the number of bytes to be copied out of the input array.
+ * @param out the space for any output that might be produced.
+ * @param outOff the offset from which the output will be copied.
+ * @return the number of output bytes copied to out.
+ * @exception DataLengthException if there isn't enough space in out.
+ * @exception InvalidOperationException if the cipher isn't initialised.
+ */
+ public override int ProcessBytes(
+ byte[] input,
+ int inOff,
+ int length,
+ byte[] output,
+ int outOff)
+ {
+ if (length < 0)
+ {
+ throw new ArgumentException("Can't have a negative input length!");
+ }
+
+ int blockSize = GetBlockSize();
+ int outLength = GetUpdateOutputSize(length);
+
+ if (outLength > 0)
+ {
+ Check.OutputLength(output, outOff, outLength, "output buffer too short");
+ }
+
+ int resultLen = 0;
+ int gapLen = buf.Length - bufOff;
+
+ if (length > gapLen)
+ {
+ Array.Copy(input, inOff, buf, bufOff, gapLen);
+
+ resultLen += cipher.ProcessBlock(buf, 0, output, outOff);
+
+ bufOff = 0;
+ length -= gapLen;
+ inOff += gapLen;
+
+ while (length > buf.Length)
+ {
+ resultLen += cipher.ProcessBlock(input, inOff, output, outOff + resultLen);
+
+ length -= blockSize;
+ inOff += blockSize;
+ }
+ }
+
+ Array.Copy(input, inOff, buf, bufOff, length);
+
+ bufOff += length;
+
+ return resultLen;
+ }
+
+ /**
+ * Process the last block in the buffer. If the buffer is currently
+ * full and padding needs to be added a call to doFinal will produce
+ * 2 * GetBlockSize() bytes.
+ *
+ * @param out the array the block currently being held is copied into.
+ * @param outOff the offset at which the copying starts.
+ * @return the number of output bytes copied to out.
+ * @exception DataLengthException if there is insufficient space in out for
+ * the output or we are decrypting and the input is not block size aligned.
+ * @exception InvalidOperationException if the underlying cipher is not
+ * initialised.
+ * @exception InvalidCipherTextException if padding is expected and not found.
+ */
+ public override int DoFinal(
+ byte[] output,
+ int outOff)
+ {
+ int blockSize = cipher.GetBlockSize();
+ int resultLen = 0;
+
+ if (forEncryption)
+ {
+ if (bufOff == blockSize)
+ {
+ if ((outOff + 2 * blockSize) > output.Length)
+ {
+ Reset();
+
+ throw new OutputLengthException("output buffer too short");
+ }
+
+ resultLen = cipher.ProcessBlock(buf, 0, output, outOff);
+ bufOff = 0;
+ }
+
+ padding.AddPadding(buf, bufOff);
+
+ resultLen += cipher.ProcessBlock(buf, 0, output, outOff + resultLen);
+
+ Reset();
+ }
+ else
+ {
+ if (bufOff == blockSize)
+ {
+ resultLen = cipher.ProcessBlock(buf, 0, buf, 0);
+ bufOff = 0;
+ }
+ else
+ {
+ Reset();
+
+ throw new DataLengthException("last block incomplete in decryption");
+ }
+
+ try
+ {
+ resultLen -= padding.PadCount(buf);
+
+ Array.Copy(buf, 0, output, outOff, resultLen);
+ }
+ finally
+ {
+ Reset();
+ }
+ }
+
+ return resultLen;
+ }
+ }
+
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/PaddedBufferedBlockCipher.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/PaddedBufferedBlockCipher.cs.meta
new file mode 100644
index 00000000..5f7930aa
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/PaddedBufferedBlockCipher.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 65e1994a7e4976f4aa5b7844d08da1d2
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/Pkcs7Padding.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/Pkcs7Padding.cs
new file mode 100644
index 00000000..2e1d4b6c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/Pkcs7Padding.cs
@@ -0,0 +1,80 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Paddings
+{
+ /**
+ * A padder that adds Pkcs7/Pkcs5 padding to a block.
+ */
+ public class Pkcs7Padding
+ : IBlockCipherPadding
+ {
+ /**
+ * Initialise the padder.
+ *
+ * @param random - a SecureRandom if available.
+ */
+ public void Init(
+ SecureRandom random)
+ {
+ // nothing to do.
+ }
+
+ /**
+ * Return the name of the algorithm the cipher implements.
+ *
+ * @return the name of the algorithm the cipher implements.
+ */
+ public string PaddingName
+ {
+ get { return "PKCS7"; }
+ }
+
+ /**
+ * add the pad bytes to the passed in block, returning the
+ * number of bytes added.
+ */
+ public int AddPadding(
+ byte[] input,
+ int inOff)
+ {
+ byte code = (byte)(input.Length - inOff);
+
+ while (inOff < input.Length)
+ {
+ input[inOff] = code;
+ inOff++;
+ }
+
+ return code;
+ }
+
+ /**
+ * return the number of pad bytes present in the block.
+ */
+ public int PadCount(
+ byte[] input)
+ {
+ byte countAsByte = input[input.Length - 1];
+ int count = countAsByte;
+
+ if (count < 1 || count > input.Length)
+ throw new InvalidCipherTextException("pad block corrupted");
+
+ for (int i = 2; i <= count; i++)
+ {
+ if (input[input.Length - i] != countAsByte)
+ throw new InvalidCipherTextException("pad block corrupted");
+ }
+
+ return count;
+ }
+ }
+
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/Pkcs7Padding.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/Pkcs7Padding.cs.meta
new file mode 100644
index 00000000..5334f056
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/Pkcs7Padding.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a987dc3355949814fa1b788c5ba932d6
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/TbcPadding.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/TbcPadding.cs
new file mode 100644
index 00000000..0ed6edcd
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/TbcPadding.cs
@@ -0,0 +1,83 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Paddings
+{
+
+ /// A padder that adds Trailing-Bit-Compliment padding to a block.
+ ///
+ /// This padding pads the block out compliment of the last bit
+ /// of the plain text.
+ ///
+ ///
+ public class TbcPadding
+ : IBlockCipherPadding
+ {
+ /// Return the name of the algorithm the cipher implements.
+ /// the name of the algorithm the cipher implements.
+ ///
+ public string PaddingName
+ {
+ get { return "TBC"; }
+ }
+
+ /// Initialise the padder.
+ /// - a SecureRandom if available.
+ ///
+ public virtual void Init(SecureRandom random)
+ {
+ // nothing to do.
+ }
+
+ /// add the pad bytes to the passed in block, returning the
+ /// number of bytes added.
+ ///
+ /// Note: this assumes that the last block of plain text is always
+ /// passed to it inside in. i.e. if inOff is zero, indicating the
+ /// entire block is to be overwritten with padding the value of in
+ /// should be the same as the last block of plain text.
+ ///
+ ///
+ public virtual int AddPadding(byte[] input, int inOff)
+ {
+ int count = input.Length - inOff;
+ byte code;
+
+ if (inOff > 0)
+ {
+ code = (byte)((input[inOff - 1] & 0x01) == 0?0xff:0x00);
+ }
+ else
+ {
+ code = (byte)((input[input.Length - 1] & 0x01) == 0?0xff:0x00);
+ }
+
+ while (inOff < input.Length)
+ {
+ input[inOff] = code;
+ inOff++;
+ }
+
+ return count;
+ }
+
+ /// return the number of pad bytes present in the block.
+ public virtual int PadCount(byte[] input)
+ {
+ byte code = input[input.Length - 1];
+
+ int index = input.Length - 1;
+ while (index > 0 && input[index - 1] == code)
+ {
+ index--;
+ }
+
+ return input.Length - index;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/TbcPadding.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/TbcPadding.cs.meta
new file mode 100644
index 00000000..53ee546b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/TbcPadding.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ee3e7e57e20d50c41b6f9cc4f31b6b69
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/X923Padding.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/X923Padding.cs
new file mode 100644
index 00000000..00296b16
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/X923Padding.cs
@@ -0,0 +1,86 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Paddings
+{
+ /**
+ * A padder that adds X9.23 padding to a block - if a SecureRandom is
+ * passed in random padding is assumed, otherwise padding with zeros is used.
+ */
+ public class X923Padding
+ : IBlockCipherPadding
+ {
+ private SecureRandom random;
+
+ /**
+ * Initialise the padder.
+ *
+ * @param random a SecureRandom if one is available.
+ */
+ public void Init(
+ SecureRandom random)
+ {
+ this.random = random;
+ }
+
+ /**
+ * Return the name of the algorithm the cipher implements.
+ *
+ * @return the name of the algorithm the cipher implements.
+ */
+ public string PaddingName
+ {
+ get { return "X9.23"; }
+ }
+
+ /**
+ * add the pad bytes to the passed in block, returning the
+ * number of bytes added.
+ */
+ public int AddPadding(
+ byte[] input,
+ int inOff)
+ {
+ byte code = (byte)(input.Length - inOff);
+
+ while (inOff < input.Length - 1)
+ {
+ if (random == null)
+ {
+ input[inOff] = 0;
+ }
+ else
+ {
+ input[inOff] = (byte)random.NextInt();
+ }
+ inOff++;
+ }
+
+ input[inOff] = code;
+
+ return code;
+ }
+
+ /**
+ * return the number of pad bytes present in the block.
+ */
+ public int PadCount(
+ byte[] input)
+ {
+ int count = input[input.Length - 1] & 0xff;
+
+ if (count > input.Length)
+ {
+ throw new InvalidCipherTextException("pad block corrupted");
+ }
+
+ return count;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/X923Padding.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/X923Padding.cs.meta
new file mode 100644
index 00000000..7b01661a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/X923Padding.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 7c0da47832981c243887ec0245c7c943
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/ZeroBytePadding.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/ZeroBytePadding.cs
new file mode 100644
index 00000000..3033aef6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/ZeroBytePadding.cs
@@ -0,0 +1,72 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Paddings
+{
+
+ /// A padder that adds Null byte padding to a block.
+ public class ZeroBytePadding : IBlockCipherPadding
+ {
+ /// Return the name of the algorithm the cipher implements.
+ ///
+ ///
+ /// the name of the algorithm the cipher implements.
+ ///
+ public string PaddingName
+ {
+ get { return "ZeroBytePadding"; }
+ }
+
+ /// Initialise the padder.
+ ///
+ ///
+ /// - a SecureRandom if available.
+ ///
+ public void Init(SecureRandom random)
+ {
+ // nothing to do.
+ }
+
+ /// add the pad bytes to the passed in block, returning the
+ /// number of bytes added.
+ ///
+ public int AddPadding(
+ byte[] input,
+ int inOff)
+ {
+ int added = (input.Length - inOff);
+
+ while (inOff < input.Length)
+ {
+ input[inOff] = (byte) 0;
+ inOff++;
+ }
+
+ return added;
+ }
+
+ /// return the number of pad bytes present in the block.
+ public int PadCount(
+ byte[] input)
+ {
+ int count = input.Length;
+
+ while (count > 0)
+ {
+ if (input[count - 1] != 0)
+ {
+ break;
+ }
+
+ count--;
+ }
+
+ return input.Length - count;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/ZeroBytePadding.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/ZeroBytePadding.cs.meta
new file mode 100644
index 00000000..5962f1e8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/paddings/ZeroBytePadding.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: efef1293185559b4e9313cbecabb9d7c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters.meta
new file mode 100644
index 00000000..882a1c86
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: e16c007b18245954f945dea9b529da6f
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/AEADParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/AEADParameters.cs
new file mode 100644
index 00000000..f401add3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/AEADParameters.cs
@@ -0,0 +1,69 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class AeadParameters
+ : ICipherParameters
+ {
+ private readonly byte[] associatedText;
+ private readonly byte[] nonce;
+ private readonly KeyParameter key;
+ private readonly int macSize;
+
+ /**
+ * Base constructor.
+ *
+ * @param key key to be used by underlying cipher
+ * @param macSize macSize in bits
+ * @param nonce nonce to be used
+ */
+ public AeadParameters(KeyParameter key, int macSize, byte[] nonce)
+ : this(key, macSize, nonce, null)
+ {
+ }
+
+ /**
+ * Base constructor.
+ *
+ * @param key key to be used by underlying cipher
+ * @param macSize macSize in bits
+ * @param nonce nonce to be used
+ * @param associatedText associated text, if any
+ */
+ public AeadParameters(
+ KeyParameter key,
+ int macSize,
+ byte[] nonce,
+ byte[] associatedText)
+ {
+ this.key = key;
+ this.nonce = nonce;
+ this.macSize = macSize;
+ this.associatedText = associatedText;
+ }
+
+ public virtual KeyParameter Key
+ {
+ get { return key; }
+ }
+
+ public virtual int MacSize
+ {
+ get { return macSize; }
+ }
+
+ public virtual byte[] GetAssociatedText()
+ {
+ return associatedText;
+ }
+
+ public virtual byte[] GetNonce()
+ {
+ return nonce;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/AEADParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/AEADParameters.cs.meta
new file mode 100644
index 00000000..1587c907
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/AEADParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 2ab1e4d400f1fe643a1fc969f83989a6
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/CcmParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/CcmParameters.cs
new file mode 100644
index 00000000..9d3588d9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/CcmParameters.cs
@@ -0,0 +1,30 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ [Obsolete("Use AeadParameters")]
+ public class CcmParameters
+ : AeadParameters
+ {
+ /**
+ * Base constructor.
+ *
+ * @param key key to be used by underlying cipher
+ * @param macSize macSize in bits
+ * @param nonce nonce to be used
+ * @param associatedText associated text, if any
+ */
+ public CcmParameters(
+ KeyParameter key,
+ int macSize,
+ byte[] nonce,
+ byte[] associatedText)
+ : base(key, macSize, nonce, associatedText)
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/CcmParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/CcmParameters.cs.meta
new file mode 100644
index 00000000..d564d769
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/CcmParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 467dc2af6a94561478578aa36156b2d1
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHKeyGenerationParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHKeyGenerationParameters.cs
new file mode 100644
index 00000000..8076b692
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHKeyGenerationParameters.cs
@@ -0,0 +1,35 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class DHKeyGenerationParameters
+ : KeyGenerationParameters
+ {
+ private readonly DHParameters parameters;
+
+ public DHKeyGenerationParameters(
+ SecureRandom random,
+ DHParameters parameters)
+ : base(random, GetStrength(parameters))
+ {
+ this.parameters = parameters;
+ }
+
+ public DHParameters Parameters
+ {
+ get { return parameters; }
+ }
+
+ internal static int GetStrength(
+ DHParameters parameters)
+ {
+ return parameters.L != 0 ? parameters.L : parameters.P.BitLength;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHKeyGenerationParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHKeyGenerationParameters.cs.meta
new file mode 100644
index 00000000..c4d214ea
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHKeyGenerationParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: e3543cbf42d2468469b628ec9921121f
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHKeyParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHKeyParameters.cs
new file mode 100644
index 00000000..afeef1d0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHKeyParameters.cs
@@ -0,0 +1,80 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class DHKeyParameters
+ : AsymmetricKeyParameter
+ {
+ private readonly DHParameters parameters;
+ private readonly DerObjectIdentifier algorithmOid;
+
+ protected DHKeyParameters(
+ bool isPrivate,
+ DHParameters parameters)
+ : this(isPrivate, parameters, PkcsObjectIdentifiers.DhKeyAgreement)
+ {
+ }
+
+ protected DHKeyParameters(
+ bool isPrivate,
+ DHParameters parameters,
+ DerObjectIdentifier algorithmOid)
+ : base(isPrivate)
+ {
+ // TODO Should we allow parameters to be null?
+ this.parameters = parameters;
+ this.algorithmOid = algorithmOid;
+ }
+
+ public DHParameters Parameters
+ {
+ get { return parameters; }
+ }
+
+ public DerObjectIdentifier AlgorithmOid
+ {
+ get { return algorithmOid; }
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return true;
+
+ DHKeyParameters other = obj as DHKeyParameters;
+
+ if (other == null)
+ return false;
+
+ return Equals(other);
+ }
+
+ protected bool Equals(
+ DHKeyParameters other)
+ {
+ return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(parameters, other.parameters)
+ && base.Equals(other);
+ }
+
+ public override int GetHashCode()
+ {
+ int hc = base.GetHashCode();
+
+ if (parameters != null)
+ {
+ hc ^= parameters.GetHashCode();
+ }
+
+ return hc;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHKeyParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHKeyParameters.cs.meta
new file mode 100644
index 00000000..33d58615
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHKeyParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: b184706d42c626541b7a830e2f1eb396
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHParameters.cs
new file mode 100644
index 00000000..4f8d592c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHParameters.cs
@@ -0,0 +1,189 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class DHParameters
+ : ICipherParameters
+ {
+ private const int DefaultMinimumLength = 160;
+
+ private readonly BigInteger p, g, q, j;
+ private readonly int m, l;
+ private readonly DHValidationParameters validation;
+
+ private static int GetDefaultMParam(
+ int lParam)
+ {
+ if (lParam == 0)
+ return DefaultMinimumLength;
+
+ return System.Math.Min(lParam, DefaultMinimumLength);
+ }
+
+ public DHParameters(
+ BigInteger p,
+ BigInteger g)
+ : this(p, g, null, 0)
+ {
+ }
+
+ public DHParameters(
+ BigInteger p,
+ BigInteger g,
+ BigInteger q)
+ : this(p, g, q, 0)
+ {
+ }
+
+ public DHParameters(
+ BigInteger p,
+ BigInteger g,
+ BigInteger q,
+ int l)
+ : this(p, g, q, GetDefaultMParam(l), l, null, null)
+ {
+ }
+
+ public DHParameters(
+ BigInteger p,
+ BigInteger g,
+ BigInteger q,
+ int m,
+ int l)
+ : this(p, g, q, m, l, null, null)
+ {
+ }
+
+ public DHParameters(
+ BigInteger p,
+ BigInteger g,
+ BigInteger q,
+ BigInteger j,
+ DHValidationParameters validation)
+ : this(p, g, q, DefaultMinimumLength, 0, j, validation)
+ {
+ }
+
+ public DHParameters(
+ BigInteger p,
+ BigInteger g,
+ BigInteger q,
+ int m,
+ int l,
+ BigInteger j,
+ DHValidationParameters validation)
+ {
+ if (p == null)
+ throw new ArgumentNullException("p");
+ if (g == null)
+ throw new ArgumentNullException("g");
+ if (!p.TestBit(0))
+ throw new ArgumentException("field must be an odd prime", "p");
+ if (g.CompareTo(BigInteger.Two) < 0
+ || g.CompareTo(p.Subtract(BigInteger.Two)) > 0)
+ throw new ArgumentException("generator must in the range [2, p - 2]", "g");
+ if (q != null && q.BitLength >= p.BitLength)
+ throw new ArgumentException("q too big to be a factor of (p-1)", "q");
+ if (m >= p.BitLength)
+ throw new ArgumentException("m value must be < bitlength of p", "m");
+ if (l != 0)
+ {
+ // TODO Check this against the Java version, which has 'l > p.BitLength' here
+ if (l >= p.BitLength)
+ throw new ArgumentException("when l value specified, it must be less than bitlength(p)", "l");
+ if (l < m)
+ throw new ArgumentException("when l value specified, it may not be less than m value", "l");
+ }
+ if (j != null && j.CompareTo(BigInteger.Two) < 0)
+ throw new ArgumentException("subgroup factor must be >= 2", "j");
+
+ // TODO If q, j both provided, validate p = jq + 1 ?
+
+ this.p = p;
+ this.g = g;
+ this.q = q;
+ this.m = m;
+ this.l = l;
+ this.j = j;
+ this.validation = validation;
+ }
+
+ public BigInteger P
+ {
+ get { return p; }
+ }
+
+ public BigInteger G
+ {
+ get { return g; }
+ }
+
+ public BigInteger Q
+ {
+ get { return q; }
+ }
+
+ public BigInteger J
+ {
+ get { return j; }
+ }
+
+ /// The minimum bitlength of the private value.
+ public int M
+ {
+ get { return m; }
+ }
+
+ /// The bitlength of the private value.
+ public int L
+ {
+ get { return l; }
+ }
+
+ public DHValidationParameters ValidationParameters
+ {
+ get { return validation; }
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return true;
+
+ DHParameters other = obj as DHParameters;
+
+ if (other == null)
+ return false;
+
+ return Equals(other);
+ }
+
+ protected virtual bool Equals(
+ DHParameters other)
+ {
+ return p.Equals(other.p)
+ && g.Equals(other.g)
+ && BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(q, other.q);
+ }
+
+ public override int GetHashCode()
+ {
+ int hc = p.GetHashCode() ^ g.GetHashCode();
+
+ if (q != null)
+ {
+ hc ^= q.GetHashCode();
+ }
+
+ return hc;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHParameters.cs.meta
new file mode 100644
index 00000000..d4d69746
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: bf264f19a21f3204cb815a491eaf7891
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHPrivateKeyParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHPrivateKeyParameters.cs
new file mode 100644
index 00000000..6aeaaf22
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHPrivateKeyParameters.cs
@@ -0,0 +1,64 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class DHPrivateKeyParameters
+ : DHKeyParameters
+ {
+ private readonly BigInteger x;
+
+ public DHPrivateKeyParameters(
+ BigInteger x,
+ DHParameters parameters)
+ : base(true, parameters)
+ {
+ this.x = x;
+ }
+
+ public DHPrivateKeyParameters(
+ BigInteger x,
+ DHParameters parameters,
+ DerObjectIdentifier algorithmOid)
+ : base(true, parameters, algorithmOid)
+ {
+ this.x = x;
+ }
+
+ public BigInteger X
+ {
+ get { return x; }
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return true;
+
+ DHPrivateKeyParameters other = obj as DHPrivateKeyParameters;
+
+ if (other == null)
+ return false;
+
+ return Equals(other);
+ }
+
+ protected bool Equals(
+ DHPrivateKeyParameters other)
+ {
+ return x.Equals(other.x) && base.Equals(other);
+ }
+
+ public override int GetHashCode()
+ {
+ return x.GetHashCode() ^ base.GetHashCode();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHPrivateKeyParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHPrivateKeyParameters.cs.meta
new file mode 100644
index 00000000..ae6b4338
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHPrivateKeyParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0fdd4d67cf6500a4bb5dfe324c483f9e
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHPublicKeyParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHPublicKeyParameters.cs
new file mode 100644
index 00000000..d14c856b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHPublicKeyParameters.cs
@@ -0,0 +1,83 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class DHPublicKeyParameters
+ : DHKeyParameters
+ {
+ private static BigInteger Validate(BigInteger y, DHParameters dhParams)
+ {
+ if (y == null)
+ throw new ArgumentNullException("y");
+
+ // TLS check
+ if (y.CompareTo(BigInteger.Two) < 0 || y.CompareTo(dhParams.P.Subtract(BigInteger.Two)) > 0)
+ throw new ArgumentException("invalid DH public key", "y");
+
+ // we can't validate without Q.
+ if (dhParams.Q != null
+ && !y.ModPow(dhParams.Q, dhParams.P).Equals(BigInteger.One))
+ {
+ throw new ArgumentException("y value does not appear to be in correct group", "y");
+ }
+
+ return y;
+ }
+
+ private readonly BigInteger y;
+
+ public DHPublicKeyParameters(
+ BigInteger y,
+ DHParameters parameters)
+ : base(false, parameters)
+ {
+ this.y = Validate(y, parameters);
+ }
+
+ public DHPublicKeyParameters(
+ BigInteger y,
+ DHParameters parameters,
+ DerObjectIdentifier algorithmOid)
+ : base(false, parameters, algorithmOid)
+ {
+ this.y = Validate(y, parameters);
+ }
+
+ public virtual BigInteger Y
+ {
+ get { return y; }
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return true;
+
+ DHPublicKeyParameters other = obj as DHPublicKeyParameters;
+
+ if (other == null)
+ return false;
+
+ return Equals(other);
+ }
+
+ protected bool Equals(
+ DHPublicKeyParameters other)
+ {
+ return y.Equals(other.y) && base.Equals(other);
+ }
+
+ public override int GetHashCode()
+ {
+ return y.GetHashCode() ^ base.GetHashCode();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHPublicKeyParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHPublicKeyParameters.cs.meta
new file mode 100644
index 00000000..d11fcd3f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHPublicKeyParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: dcdcc5dd36103a347803778660e62bac
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHValidationParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHValidationParameters.cs
new file mode 100644
index 00000000..35f12007
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHValidationParameters.cs
@@ -0,0 +1,63 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class DHValidationParameters
+ {
+ private readonly byte[] seed;
+ private readonly int counter;
+
+ public DHValidationParameters(
+ byte[] seed,
+ int counter)
+ {
+ if (seed == null)
+ throw new ArgumentNullException("seed");
+
+ this.seed = (byte[]) seed.Clone();
+ this.counter = counter;
+ }
+
+ public byte[] GetSeed()
+ {
+ return (byte[]) seed.Clone();
+ }
+
+ public int Counter
+ {
+ get { return counter; }
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return true;
+
+ DHValidationParameters other = obj as DHValidationParameters;
+
+ if (other == null)
+ return false;
+
+ return Equals(other);
+ }
+
+ protected bool Equals(
+ DHValidationParameters other)
+ {
+ return counter == other.counter
+ && Arrays.AreEqual(this.seed, other.seed);
+ }
+
+ public override int GetHashCode()
+ {
+ return counter.GetHashCode() ^ Arrays.GetHashCode(seed);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHValidationParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHValidationParameters.cs.meta
new file mode 100644
index 00000000..3b59ad5b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DHValidationParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: bcfe09e6364f2824ea27955a589ae4b2
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DSAParameterGenerationParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DSAParameterGenerationParameters.cs
new file mode 100644
index 00000000..97bd2db9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DSAParameterGenerationParameters.cs
@@ -0,0 +1,78 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class DsaParameterGenerationParameters
+ {
+ public const int DigitalSignatureUsage = 1;
+ public const int KeyEstablishmentUsage = 2;
+
+ private readonly int l;
+ private readonly int n;
+ private readonly int certainty;
+ private readonly SecureRandom random;
+ private readonly int usageIndex;
+
+ /**
+ * Construct without a usage index, this will do a random construction of G.
+ *
+ * @param L desired length of prime P in bits (the effective key size).
+ * @param N desired length of prime Q in bits.
+ * @param certainty certainty level for prime number generation.
+ * @param random the source of randomness to use.
+ */
+ public DsaParameterGenerationParameters(int L, int N, int certainty, SecureRandom random)
+ : this(L, N, certainty, random, -1)
+ {
+ }
+
+ /**
+ * Construct for a specific usage index - this has the effect of using verifiable canonical generation of G.
+ *
+ * @param L desired length of prime P in bits (the effective key size).
+ * @param N desired length of prime Q in bits.
+ * @param certainty certainty level for prime number generation.
+ * @param random the source of randomness to use.
+ * @param usageIndex a valid usage index.
+ */
+ public DsaParameterGenerationParameters(int L, int N, int certainty, SecureRandom random, int usageIndex)
+ {
+ this.l = L;
+ this.n = N;
+ this.certainty = certainty;
+ this.random = random;
+ this.usageIndex = usageIndex;
+ }
+
+ public virtual int L
+ {
+ get { return l; }
+ }
+
+ public virtual int N
+ {
+ get { return n; }
+ }
+
+ public virtual int UsageIndex
+ {
+ get { return usageIndex; }
+ }
+
+ public virtual int Certainty
+ {
+ get { return certainty; }
+ }
+
+ public virtual SecureRandom Random
+ {
+ get { return random; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DSAParameterGenerationParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DSAParameterGenerationParameters.cs.meta
new file mode 100644
index 00000000..41a2240f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DSAParameterGenerationParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 5bae2087e40f1ca4497d9a252aff83c8
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DesEdeParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DesEdeParameters.cs
new file mode 100644
index 00000000..cc3eafc0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DesEdeParameters.cs
@@ -0,0 +1,144 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class DesEdeParameters
+ : DesParameters
+ {
+ /*
+ * DES-EDE Key length in bytes.
+ */
+ public const int DesEdeKeyLength = 24;
+
+ private static byte[] FixKey(
+ byte[] key,
+ int keyOff,
+ int keyLen)
+ {
+ byte[] tmp = new byte[24];
+
+ switch (keyLen)
+ {
+ case 16:
+ Array.Copy(key, keyOff, tmp, 0, 16);
+ Array.Copy(key, keyOff, tmp, 16, 8);
+ break;
+ case 24:
+ Array.Copy(key, keyOff, tmp, 0, 24);
+ break;
+ default:
+ throw new ArgumentException("Bad length for DESede key: " + keyLen, "keyLen");
+ }
+
+ if (IsWeakKey(tmp))
+ throw new ArgumentException("attempt to create weak DESede key");
+
+ return tmp;
+ }
+
+ public DesEdeParameters(
+ byte[] key)
+ : base(FixKey(key, 0, key.Length))
+ {
+ }
+
+ public DesEdeParameters(
+ byte[] key,
+ int keyOff,
+ int keyLen)
+ : base(FixKey(key, keyOff, keyLen))
+ {
+ }
+
+ /**
+ * return true if the passed in key is a DES-EDE weak key.
+ *
+ * @param key bytes making up the key
+ * @param offset offset into the byte array the key starts at
+ * @param length number of bytes making up the key
+ */
+ public static bool IsWeakKey(
+ byte[] key,
+ int offset,
+ int length)
+ {
+ for (int i = offset; i < length; i += DesKeyLength)
+ {
+ if (DesParameters.IsWeakKey(key, i))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * return true if the passed in key is a DES-EDE weak key.
+ *
+ * @param key bytes making up the key
+ * @param offset offset into the byte array the key starts at
+ */
+ public static new bool IsWeakKey(
+ byte[] key,
+ int offset)
+ {
+ return IsWeakKey(key, offset, key.Length - offset);
+ }
+
+ public static new bool IsWeakKey(
+ byte[] key)
+ {
+ return IsWeakKey(key, 0, key.Length);
+ }
+
+ /**
+ * return true if the passed in key is a real 2/3 part DES-EDE key.
+ *
+ * @param key bytes making up the key
+ * @param offset offset into the byte array the key starts at
+ */
+ public static bool IsRealEdeKey(byte[] key, int offset)
+ {
+ return key.Length == 16 ? IsReal2Key(key, offset) : IsReal3Key(key, offset);
+ }
+
+ /**
+ * return true if the passed in key is a real 2 part DES-EDE key.
+ *
+ * @param key bytes making up the key
+ * @param offset offset into the byte array the key starts at
+ */
+ public static bool IsReal2Key(byte[] key, int offset)
+ {
+ bool isValid = false;
+ for (int i = offset; i != offset + 8; i++)
+ {
+ isValid |= (key[i] != key[i + 8]);
+ }
+ return isValid;
+ }
+
+ /**
+ * return true if the passed in key is a real 3 part DES-EDE key.
+ *
+ * @param key bytes making up the key
+ * @param offset offset into the byte array the key starts at
+ */
+ public static bool IsReal3Key(byte[] key, int offset)
+ {
+ bool diff12 = false, diff13 = false, diff23 = false;
+ for (int i = offset; i != offset + 8; i++)
+ {
+ diff12 |= (key[i] != key[i + 8]);
+ diff13 |= (key[i] != key[i + 16]);
+ diff23 |= (key[i + 8] != key[i + 16]);
+ }
+ return diff12 && diff13 && diff23;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DesEdeParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DesEdeParameters.cs.meta
new file mode 100644
index 00000000..10eb11a9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DesEdeParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 4749e39c2006221438acbd5317e3f77c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DesParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DesParameters.cs
new file mode 100644
index 00000000..a43b0132
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DesParameters.cs
@@ -0,0 +1,143 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class DesParameters
+ : KeyParameter
+ {
+ public DesParameters(
+ byte[] key)
+ : base(key)
+ {
+ if (IsWeakKey(key))
+ throw new ArgumentException("attempt to create weak DES key");
+ }
+
+ public DesParameters(
+ byte[] key,
+ int keyOff,
+ int keyLen)
+ : base(key, keyOff, keyLen)
+ {
+ if (IsWeakKey(key, keyOff))
+ throw new ArgumentException("attempt to create weak DES key");
+ }
+
+ /*
+ * DES Key Length in bytes.
+ */
+ public const int DesKeyLength = 8;
+
+ /*
+ * Table of weak and semi-weak keys taken from Schneier pp281
+ */
+ private const int N_DES_WEAK_KEYS = 16;
+
+ private static readonly byte[] DES_weak_keys =
+ {
+ /* weak keys */
+ (byte)0x01,(byte)0x01,(byte)0x01,(byte)0x01, (byte)0x01,(byte)0x01,(byte)0x01,(byte)0x01,
+ (byte)0x1f,(byte)0x1f,(byte)0x1f,(byte)0x1f, (byte)0x0e,(byte)0x0e,(byte)0x0e,(byte)0x0e,
+ (byte)0xe0,(byte)0xe0,(byte)0xe0,(byte)0xe0, (byte)0xf1,(byte)0xf1,(byte)0xf1,(byte)0xf1,
+ (byte)0xfe,(byte)0xfe,(byte)0xfe,(byte)0xfe, (byte)0xfe,(byte)0xfe,(byte)0xfe,(byte)0xfe,
+
+ /* semi-weak keys */
+ (byte)0x01,(byte)0xfe,(byte)0x01,(byte)0xfe, (byte)0x01,(byte)0xfe,(byte)0x01,(byte)0xfe,
+ (byte)0x1f,(byte)0xe0,(byte)0x1f,(byte)0xe0, (byte)0x0e,(byte)0xf1,(byte)0x0e,(byte)0xf1,
+ (byte)0x01,(byte)0xe0,(byte)0x01,(byte)0xe0, (byte)0x01,(byte)0xf1,(byte)0x01,(byte)0xf1,
+ (byte)0x1f,(byte)0xfe,(byte)0x1f,(byte)0xfe, (byte)0x0e,(byte)0xfe,(byte)0x0e,(byte)0xfe,
+ (byte)0x01,(byte)0x1f,(byte)0x01,(byte)0x1f, (byte)0x01,(byte)0x0e,(byte)0x01,(byte)0x0e,
+ (byte)0xe0,(byte)0xfe,(byte)0xe0,(byte)0xfe, (byte)0xf1,(byte)0xfe,(byte)0xf1,(byte)0xfe,
+ (byte)0xfe,(byte)0x01,(byte)0xfe,(byte)0x01, (byte)0xfe,(byte)0x01,(byte)0xfe,(byte)0x01,
+ (byte)0xe0,(byte)0x1f,(byte)0xe0,(byte)0x1f, (byte)0xf1,(byte)0x0e,(byte)0xf1,(byte)0x0e,
+ (byte)0xe0,(byte)0x01,(byte)0xe0,(byte)0x01, (byte)0xf1,(byte)0x01,(byte)0xf1,(byte)0x01,
+ (byte)0xfe,(byte)0x1f,(byte)0xfe,(byte)0x1f, (byte)0xfe,(byte)0x0e,(byte)0xfe,(byte)0x0e,
+ (byte)0x1f,(byte)0x01,(byte)0x1f,(byte)0x01, (byte)0x0e,(byte)0x01,(byte)0x0e,(byte)0x01,
+ (byte)0xfe,(byte)0xe0,(byte)0xfe,(byte)0xe0, (byte)0xfe,(byte)0xf1,(byte)0xfe,(byte)0xf1
+ };
+
+ /**
+ * DES has 16 weak keys. This method will check
+ * if the given DES key material is weak or semi-weak.
+ * Key material that is too short is regarded as weak.
+ *
+ * @return true if the given DES key material is weak or semi-weak,
+ * false otherwise.
+ */
+ public static bool IsWeakKey(
+ byte[] key,
+ int offset)
+ {
+ if (key.Length - offset < DesKeyLength)
+ throw new ArgumentException("key material too short.");
+
+ //nextkey:
+ for (int i = 0; i < N_DES_WEAK_KEYS; i++)
+ {
+ bool unmatch = false;
+ for (int j = 0; j < DesKeyLength; j++)
+ {
+ if (key[j + offset] != DES_weak_keys[i * DesKeyLength + j])
+ {
+ //continue nextkey;
+ unmatch = true;
+ break;
+ }
+ }
+
+ if (!unmatch)
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ public static bool IsWeakKey(
+ byte[] key)
+ {
+ return IsWeakKey(key, 0);
+ }
+
+ public static byte SetOddParity(byte b)
+ {
+ uint parity = b ^ 1U;
+ parity ^= (parity >> 4);
+ parity ^= (parity >> 2);
+ parity ^= (parity >> 1);
+ parity &= 1U;
+
+ return (byte)(b ^ parity);
+ }
+
+ /**
+ * DES Keys use the LSB as the odd parity bit. This can
+ * be used to check for corrupt keys.
+ *
+ * @param bytes the byte array to set the parity on.
+ */
+ public static void SetOddParity(byte[] bytes)
+ {
+ for (int i = 0; i < bytes.Length; i++)
+ {
+ bytes[i] = SetOddParity(bytes[i]);
+ }
+ }
+
+ public static void SetOddParity(byte[] bytes, int off, int len)
+ {
+ for (int i = 0; i < len; i++)
+ {
+ bytes[off + i] = SetOddParity(bytes[off + i]);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DesParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DesParameters.cs.meta
new file mode 100644
index 00000000..08c231d1
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DesParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: b00a12c88d7bcc248b4ca2f26e3aa06d
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaKeyGenerationParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaKeyGenerationParameters.cs
new file mode 100644
index 00000000..d94c2edb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaKeyGenerationParameters.cs
@@ -0,0 +1,30 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class DsaKeyGenerationParameters
+ : KeyGenerationParameters
+ {
+ private readonly DsaParameters parameters;
+
+ public DsaKeyGenerationParameters(
+ SecureRandom random,
+ DsaParameters parameters)
+ : base(random, parameters.P.BitLength - 1)
+ {
+ this.parameters = parameters;
+ }
+
+ public DsaParameters Parameters
+ {
+ get { return parameters; }
+ }
+ }
+
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaKeyGenerationParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaKeyGenerationParameters.cs.meta
new file mode 100644
index 00000000..52c08ac3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaKeyGenerationParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 276581811002f3e4c9cb17ec0a51d092
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaKeyParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaKeyParameters.cs
new file mode 100644
index 00000000..6511a09d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaKeyParameters.cs
@@ -0,0 +1,63 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public abstract class DsaKeyParameters
+ : AsymmetricKeyParameter
+ {
+ private readonly DsaParameters parameters;
+
+ protected DsaKeyParameters(
+ bool isPrivate,
+ DsaParameters parameters)
+ : base(isPrivate)
+ {
+ // Note: parameters may be null
+ this.parameters = parameters;
+ }
+
+ public DsaParameters Parameters
+ {
+ get { return parameters; }
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return true;
+
+ DsaKeyParameters other = obj as DsaKeyParameters;
+
+ if (other == null)
+ return false;
+
+ return Equals(other);
+ }
+
+ protected bool Equals(
+ DsaKeyParameters other)
+ {
+ return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(parameters, other.parameters)
+ && base.Equals(other);
+ }
+
+ public override int GetHashCode()
+ {
+ int hc = base.GetHashCode();
+
+ if (parameters != null)
+ {
+ hc ^= parameters.GetHashCode();
+ }
+
+ return hc;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaKeyParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaKeyParameters.cs.meta
new file mode 100644
index 00000000..89884033
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaKeyParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0f1017d8a70458545aa4e27a696f2df5
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaParameters.cs
new file mode 100644
index 00000000..6006e691
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaParameters.cs
@@ -0,0 +1,89 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class DsaParameters
+ : ICipherParameters
+ {
+ private readonly BigInteger p, q , g;
+ private readonly DsaValidationParameters validation;
+
+ public DsaParameters(
+ BigInteger p,
+ BigInteger q,
+ BigInteger g)
+ : this(p, q, g, null)
+ {
+ }
+
+ public DsaParameters(
+ BigInteger p,
+ BigInteger q,
+ BigInteger g,
+ DsaValidationParameters parameters)
+ {
+ if (p == null)
+ throw new ArgumentNullException("p");
+ if (q == null)
+ throw new ArgumentNullException("q");
+ if (g == null)
+ throw new ArgumentNullException("g");
+
+ this.p = p;
+ this.q = q;
+ this.g = g;
+ this.validation = parameters;
+ }
+
+ public BigInteger P
+ {
+ get { return p; }
+ }
+
+ public BigInteger Q
+ {
+ get { return q; }
+ }
+
+ public BigInteger G
+ {
+ get { return g; }
+ }
+
+ public DsaValidationParameters ValidationParameters
+ {
+ get { return validation; }
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return true;
+
+ DsaParameters other = obj as DsaParameters;
+
+ if (other == null)
+ return false;
+
+ return Equals(other);
+ }
+
+ protected bool Equals(
+ DsaParameters other)
+ {
+ return p.Equals(other.p) && q.Equals(other.q) && g.Equals(other.g);
+ }
+
+ public override int GetHashCode()
+ {
+ return p.GetHashCode() ^ q.GetHashCode() ^ g.GetHashCode();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaParameters.cs.meta
new file mode 100644
index 00000000..da0fc5dd
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ee680943739e3ab4abee72f41f4cb6e3
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaPrivateKeyParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaPrivateKeyParameters.cs
new file mode 100644
index 00000000..b7e91eeb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaPrivateKeyParameters.cs
@@ -0,0 +1,57 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class DsaPrivateKeyParameters
+ : DsaKeyParameters
+ {
+ private readonly BigInteger x;
+
+ public DsaPrivateKeyParameters(
+ BigInteger x,
+ DsaParameters parameters)
+ : base(true, parameters)
+ {
+ if (x == null)
+ throw new ArgumentNullException("x");
+
+ this.x = x;
+ }
+
+ public BigInteger X
+ {
+ get { return x; }
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return true;
+
+ DsaPrivateKeyParameters other = obj as DsaPrivateKeyParameters;
+
+ if (other == null)
+ return false;
+
+ return Equals(other);
+ }
+
+ protected bool Equals(
+ DsaPrivateKeyParameters other)
+ {
+ return x.Equals(other.x) && base.Equals(other);
+ }
+
+ public override int GetHashCode()
+ {
+ return x.GetHashCode() ^ base.GetHashCode();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaPrivateKeyParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaPrivateKeyParameters.cs.meta
new file mode 100644
index 00000000..7a083fa0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaPrivateKeyParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: d4f0cb0e77323ee4b94fdb6249c169d1
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaPublicKeyParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaPublicKeyParameters.cs
new file mode 100644
index 00000000..308ab13c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaPublicKeyParameters.cs
@@ -0,0 +1,72 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class DsaPublicKeyParameters
+ : DsaKeyParameters
+ {
+ private static BigInteger Validate(BigInteger y, DsaParameters parameters)
+ {
+ // we can't validate without params, fortunately we can't use the key either...
+ if (parameters != null)
+ {
+ if (y.CompareTo(BigInteger.Two) < 0
+ || y.CompareTo(parameters.P.Subtract(BigInteger.Two)) > 0
+ || !y.ModPow(parameters.Q, parameters.P).Equals(BigInteger.One))
+ {
+ throw new ArgumentException("y value does not appear to be in correct group");
+ }
+ }
+
+ return y;
+ }
+
+ private readonly BigInteger y;
+
+ public DsaPublicKeyParameters(
+ BigInteger y,
+ DsaParameters parameters)
+ : base(false, parameters)
+ {
+ if (y == null)
+ throw new ArgumentNullException("y");
+
+ this.y = Validate(y, parameters);
+ }
+
+ public BigInteger Y
+ {
+ get { return y; }
+ }
+
+ public override bool Equals(object obj)
+ {
+ if (obj == this)
+ return true;
+
+ DsaPublicKeyParameters other = obj as DsaPublicKeyParameters;
+
+ if (other == null)
+ return false;
+
+ return Equals(other);
+ }
+
+ protected bool Equals(
+ DsaPublicKeyParameters other)
+ {
+ return y.Equals(other.y) && base.Equals(other);
+ }
+
+ public override int GetHashCode()
+ {
+ return y.GetHashCode() ^ base.GetHashCode();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaPublicKeyParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaPublicKeyParameters.cs.meta
new file mode 100644
index 00000000..8ff9118e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaPublicKeyParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 1afe3462c21af6a4ca12ef6e3169445f
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaValidationParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaValidationParameters.cs
new file mode 100644
index 00000000..a4bc0e30
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaValidationParameters.cs
@@ -0,0 +1,76 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class DsaValidationParameters
+ {
+ private readonly byte[] seed;
+ private readonly int counter;
+ private readonly int usageIndex;
+
+ public DsaValidationParameters(byte[] seed, int counter)
+ : this(seed, counter, -1)
+ {
+ }
+
+ public DsaValidationParameters(
+ byte[] seed,
+ int counter,
+ int usageIndex)
+ {
+ if (seed == null)
+ throw new ArgumentNullException("seed");
+
+ this.seed = (byte[]) seed.Clone();
+ this.counter = counter;
+ this.usageIndex = usageIndex;
+ }
+
+ public virtual byte[] GetSeed()
+ {
+ return (byte[]) seed.Clone();
+ }
+
+ public virtual int Counter
+ {
+ get { return counter; }
+ }
+
+ public virtual int UsageIndex
+ {
+ get { return usageIndex; }
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return true;
+
+ DsaValidationParameters other = obj as DsaValidationParameters;
+
+ if (other == null)
+ return false;
+
+ return Equals(other);
+ }
+
+ protected virtual bool Equals(
+ DsaValidationParameters other)
+ {
+ return counter == other.counter
+ && Arrays.AreEqual(seed, other.seed);
+ }
+
+ public override int GetHashCode()
+ {
+ return counter.GetHashCode() ^ Arrays.GetHashCode(seed);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaValidationParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaValidationParameters.cs.meta
new file mode 100644
index 00000000..d7d330a6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/DsaValidationParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 66dbc197d770cc74da7061f3a853ea1d
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECDomainParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECDomainParameters.cs
new file mode 100644
index 00000000..b24bace7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECDomainParameters.cs
@@ -0,0 +1,152 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class ECDomainParameters
+ {
+ internal ECCurve curve;
+ internal byte[] seed;
+ internal ECPoint g;
+ internal BigInteger n;
+ internal BigInteger h;
+ internal BigInteger hInv;
+
+ public ECDomainParameters(
+ ECCurve curve,
+ ECPoint g,
+ BigInteger n)
+ : this(curve, g, n, BigInteger.One, null)
+ {
+ }
+
+ public ECDomainParameters(
+ ECCurve curve,
+ ECPoint g,
+ BigInteger n,
+ BigInteger h)
+ : this(curve, g, n, h, null)
+ {
+ }
+
+ public ECDomainParameters(
+ ECCurve curve,
+ ECPoint g,
+ BigInteger n,
+ BigInteger h,
+ byte[] seed)
+ {
+ if (curve == null)
+ throw new ArgumentNullException("curve");
+ if (g == null)
+ throw new ArgumentNullException("g");
+ if (n == null)
+ throw new ArgumentNullException("n");
+ // we can't check for h == null here as h is optional in X9.62 as it is not required for ECDSA
+
+ this.curve = curve;
+ this.g = Validate(curve, g);
+ this.n = n;
+ this.h = h;
+ this.seed = Arrays.Clone(seed);
+ }
+
+ public ECCurve Curve
+ {
+ get { return curve; }
+ }
+
+ public ECPoint G
+ {
+ get { return g; }
+ }
+
+ public BigInteger N
+ {
+ get { return n; }
+ }
+
+ public BigInteger H
+ {
+ get { return h; }
+ }
+
+ public BigInteger HInv
+ {
+ get
+ {
+ lock (this)
+ {
+ if (hInv == null)
+ {
+ hInv = h.ModInverse(n);
+ }
+ return hInv;
+ }
+ }
+ }
+
+ public byte[] GetSeed()
+ {
+ return Arrays.Clone(seed);
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return true;
+
+ ECDomainParameters other = obj as ECDomainParameters;
+
+ if (other == null)
+ return false;
+
+ return Equals(other);
+ }
+
+ protected virtual bool Equals(
+ ECDomainParameters other)
+ {
+ return curve.Equals(other.curve)
+ && g.Equals(other.g)
+ && n.Equals(other.n)
+ && h.Equals(other.h);
+ }
+
+ public override int GetHashCode()
+ {
+ int hc = curve.GetHashCode();
+ hc *= 37;
+ hc ^= g.GetHashCode();
+ hc *= 37;
+ hc ^= n.GetHashCode();
+ hc *= 37;
+ hc ^= h.GetHashCode();
+ return hc;
+ }
+
+ internal static ECPoint Validate(ECCurve c, ECPoint q)
+ {
+ if (q == null)
+ throw new ArgumentException("Point has null value", "q");
+
+ q = ECAlgorithms.ImportPoint(c, q).Normalize();
+
+ if (q.IsInfinity)
+ throw new ArgumentException("Point at infinity", "q");
+
+ if (!q.IsValid())
+ throw new ArgumentException("Point not on curve", "q");
+
+ return q;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECDomainParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECDomainParameters.cs.meta
new file mode 100644
index 00000000..9ae6fef6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECDomainParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 3beb4f5cf7c45294aae379ff966dee7f
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECKeyGenerationParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECKeyGenerationParameters.cs
new file mode 100644
index 00000000..7c95b7d0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECKeyGenerationParameters.cs
@@ -0,0 +1,45 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class ECKeyGenerationParameters
+ : KeyGenerationParameters
+ {
+ private readonly ECDomainParameters domainParams;
+ private readonly DerObjectIdentifier publicKeyParamSet;
+
+ public ECKeyGenerationParameters(
+ ECDomainParameters domainParameters,
+ SecureRandom random)
+ : base(random, domainParameters.N.BitLength)
+ {
+ this.domainParams = domainParameters;
+ }
+
+ public ECKeyGenerationParameters(
+ DerObjectIdentifier publicKeyParamSet,
+ SecureRandom random)
+ : this(ECKeyParameters.LookupParameters(publicKeyParamSet), random)
+ {
+ this.publicKeyParamSet = publicKeyParamSet;
+ }
+
+ public ECDomainParameters DomainParameters
+ {
+ get { return domainParams; }
+ }
+
+ public DerObjectIdentifier PublicKeyParamSet
+ {
+ get { return publicKeyParamSet; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECKeyGenerationParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECKeyGenerationParameters.cs.meta
new file mode 100644
index 00000000..75934100
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECKeyGenerationParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ab3ecd7ab43e33a458ea35a383957a07
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECKeyParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECKeyParameters.cs
new file mode 100644
index 00000000..50badba6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECKeyParameters.cs
@@ -0,0 +1,140 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public abstract class ECKeyParameters
+ : AsymmetricKeyParameter
+ {
+ private static readonly string[] algorithms = { "EC", "ECDSA", "ECDH", "ECDHC", "ECGOST3410", "ECMQV" };
+
+ private readonly string algorithm;
+ private readonly ECDomainParameters parameters;
+ private readonly DerObjectIdentifier publicKeyParamSet;
+
+ protected ECKeyParameters(
+ string algorithm,
+ bool isPrivate,
+ ECDomainParameters parameters)
+ : base(isPrivate)
+ {
+ if (algorithm == null)
+ throw new ArgumentNullException("algorithm");
+ if (parameters == null)
+ throw new ArgumentNullException("parameters");
+
+ this.algorithm = VerifyAlgorithmName(algorithm);
+ this.parameters = parameters;
+ }
+
+ protected ECKeyParameters(
+ string algorithm,
+ bool isPrivate,
+ DerObjectIdentifier publicKeyParamSet)
+ : base(isPrivate)
+ {
+ if (algorithm == null)
+ throw new ArgumentNullException("algorithm");
+ if (publicKeyParamSet == null)
+ throw new ArgumentNullException("publicKeyParamSet");
+
+ this.algorithm = VerifyAlgorithmName(algorithm);
+ this.parameters = LookupParameters(publicKeyParamSet);
+ this.publicKeyParamSet = publicKeyParamSet;
+ }
+
+ public string AlgorithmName
+ {
+ get { return algorithm; }
+ }
+
+ public ECDomainParameters Parameters
+ {
+ get { return parameters; }
+ }
+
+ public DerObjectIdentifier PublicKeyParamSet
+ {
+ get { return publicKeyParamSet; }
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return true;
+
+ ECDomainParameters other = obj as ECDomainParameters;
+
+ if (other == null)
+ return false;
+
+ return Equals(other);
+ }
+
+ protected bool Equals(
+ ECKeyParameters other)
+ {
+ return parameters.Equals(other.parameters) && base.Equals(other);
+ }
+
+ public override int GetHashCode()
+ {
+ return parameters.GetHashCode() ^ base.GetHashCode();
+ }
+
+ internal ECKeyGenerationParameters CreateKeyGenerationParameters(
+ SecureRandom random)
+ {
+ if (publicKeyParamSet != null)
+ {
+ return new ECKeyGenerationParameters(publicKeyParamSet, random);
+ }
+
+ return new ECKeyGenerationParameters(parameters, random);
+ }
+
+ internal static string VerifyAlgorithmName(string algorithm)
+ {
+ string upper = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm);
+ if (Array.IndexOf(algorithms, algorithm, 0, algorithms.Length) < 0)
+ throw new ArgumentException("unrecognised algorithm: " + algorithm, "algorithm");
+ return upper;
+ }
+
+ internal static ECDomainParameters LookupParameters(
+ DerObjectIdentifier publicKeyParamSet)
+ {
+ if (publicKeyParamSet == null)
+ throw new ArgumentNullException("publicKeyParamSet");
+
+ ECDomainParameters p = ECGost3410NamedCurves.GetByOid(publicKeyParamSet);
+
+ if (p == null)
+ {
+ X9ECParameters x9 = ECKeyPairGenerator.FindECCurveByOid(publicKeyParamSet);
+
+ if (x9 == null)
+ {
+ throw new ArgumentException("OID is not a valid public key parameter set", "publicKeyParamSet");
+ }
+
+ p = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed());
+ }
+
+ return p;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECKeyParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECKeyParameters.cs.meta
new file mode 100644
index 00000000..3bb8bb83
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECKeyParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 7082d8fbbed75824585e4b8956c19af4
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECPrivateKeyParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECPrivateKeyParameters.cs
new file mode 100644
index 00000000..a909e412
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECPrivateKeyParameters.cs
@@ -0,0 +1,91 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Globalization;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class ECPrivateKeyParameters
+ : ECKeyParameters
+ {
+ private readonly BigInteger d;
+
+ public ECPrivateKeyParameters(
+ BigInteger d,
+ ECDomainParameters parameters)
+ : this("EC", d, parameters)
+ {
+ }
+
+ [Obsolete("Use version with explicit 'algorithm' parameter")]
+ public ECPrivateKeyParameters(
+ BigInteger d,
+ DerObjectIdentifier publicKeyParamSet)
+ : base("ECGOST3410", true, publicKeyParamSet)
+ {
+ if (d == null)
+ throw new ArgumentNullException("d");
+
+ this.d = d;
+ }
+
+ public ECPrivateKeyParameters(
+ string algorithm,
+ BigInteger d,
+ ECDomainParameters parameters)
+ : base(algorithm, true, parameters)
+ {
+ if (d == null)
+ throw new ArgumentNullException("d");
+
+ this.d = d;
+ }
+
+ public ECPrivateKeyParameters(
+ string algorithm,
+ BigInteger d,
+ DerObjectIdentifier publicKeyParamSet)
+ : base(algorithm, true, publicKeyParamSet)
+ {
+ if (d == null)
+ throw new ArgumentNullException("d");
+
+ this.d = d;
+ }
+
+ public BigInteger D
+ {
+ get { return d; }
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return true;
+
+ ECPrivateKeyParameters other = obj as ECPrivateKeyParameters;
+
+ if (other == null)
+ return false;
+
+ return Equals(other);
+ }
+
+ protected bool Equals(
+ ECPrivateKeyParameters other)
+ {
+ return d.Equals(other.d) && base.Equals(other);
+ }
+
+ public override int GetHashCode()
+ {
+ return d.GetHashCode() ^ base.GetHashCode();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECPrivateKeyParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECPrivateKeyParameters.cs.meta
new file mode 100644
index 00000000..876b4c07
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECPrivateKeyParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 8f9d84f447cca6e4080ff2469a3642d2
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECPublicKeyParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECPublicKeyParameters.cs
new file mode 100644
index 00000000..15467320
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECPublicKeyParameters.cs
@@ -0,0 +1,90 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Globalization;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class ECPublicKeyParameters
+ : ECKeyParameters
+ {
+ private readonly ECPoint q;
+
+ public ECPublicKeyParameters(
+ ECPoint q,
+ ECDomainParameters parameters)
+ : this("EC", q, parameters)
+ {
+ }
+
+ [Obsolete("Use version with explicit 'algorithm' parameter")]
+ public ECPublicKeyParameters(
+ ECPoint q,
+ DerObjectIdentifier publicKeyParamSet)
+ : base("ECGOST3410", false, publicKeyParamSet)
+ {
+ if (q == null)
+ throw new ArgumentNullException("q");
+
+ this.q = ECDomainParameters.Validate(Parameters.Curve, q);
+ }
+
+ public ECPublicKeyParameters(
+ string algorithm,
+ ECPoint q,
+ ECDomainParameters parameters)
+ : base(algorithm, false, parameters)
+ {
+ if (q == null)
+ throw new ArgumentNullException("q");
+
+ this.q = ECDomainParameters.Validate(Parameters.Curve, q);
+ }
+
+ public ECPublicKeyParameters(
+ string algorithm,
+ ECPoint q,
+ DerObjectIdentifier publicKeyParamSet)
+ : base(algorithm, false, publicKeyParamSet)
+ {
+ if (q == null)
+ throw new ArgumentNullException("q");
+
+ this.q = ECDomainParameters.Validate(Parameters.Curve, q);
+ }
+
+ public ECPoint Q
+ {
+ get { return q; }
+ }
+
+ public override bool Equals(object obj)
+ {
+ if (obj == this)
+ return true;
+
+ ECPublicKeyParameters other = obj as ECPublicKeyParameters;
+
+ if (other == null)
+ return false;
+
+ return Equals(other);
+ }
+
+ protected bool Equals(
+ ECPublicKeyParameters other)
+ {
+ return q.Equals(other.q) && base.Equals(other);
+ }
+
+ public override int GetHashCode()
+ {
+ return q.GetHashCode() ^ base.GetHashCode();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECPublicKeyParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECPublicKeyParameters.cs.meta
new file mode 100644
index 00000000..d73a5c61
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ECPublicKeyParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 03c066cb5e3c19d4eb02383352313fd5
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed25519KeyGenerationParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed25519KeyGenerationParameters.cs
new file mode 100644
index 00000000..a1a056e5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed25519KeyGenerationParameters.cs
@@ -0,0 +1,19 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class Ed25519KeyGenerationParameters
+ : KeyGenerationParameters
+ {
+ public Ed25519KeyGenerationParameters(SecureRandom random)
+ : base(random, 256)
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed25519KeyGenerationParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed25519KeyGenerationParameters.cs.meta
new file mode 100644
index 00000000..33bb6d17
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed25519KeyGenerationParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 9b1b969ec9bb03545b94b55e5a159259
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed25519PrivateKeyParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed25519PrivateKeyParameters.cs
new file mode 100644
index 00000000..50534708
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed25519PrivateKeyParameters.cs
@@ -0,0 +1,102 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Rfc8032;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public sealed class Ed25519PrivateKeyParameters
+ : AsymmetricKeyParameter
+ {
+ public static readonly int KeySize = Ed25519.SecretKeySize;
+ public static readonly int SignatureSize = Ed25519.SignatureSize;
+
+ private readonly byte[] data = new byte[KeySize];
+
+ public Ed25519PrivateKeyParameters(SecureRandom random)
+ : base(true)
+ {
+ Ed25519.GeneratePrivateKey(random, data);
+ }
+
+ public Ed25519PrivateKeyParameters(byte[] buf, int off)
+ : base(true)
+ {
+ Array.Copy(buf, off, data, 0, KeySize);
+ }
+
+ public Ed25519PrivateKeyParameters(Stream input)
+ : base(true)
+ {
+ if (KeySize != Streams.ReadFully(input, data))
+ throw new EndOfStreamException("EOF encountered in middle of Ed25519 private key");
+ }
+
+ public void Encode(byte[] buf, int off)
+ {
+ Array.Copy(data, 0, buf, off, KeySize);
+ }
+
+ public byte[] GetEncoded()
+ {
+ return Arrays.Clone(data);
+ }
+
+ public Ed25519PublicKeyParameters GeneratePublicKey()
+ {
+ byte[] publicKey = new byte[Ed25519.PublicKeySize];
+ Ed25519.GeneratePublicKey(data, 0, publicKey, 0);
+ return new Ed25519PublicKeyParameters(publicKey, 0);
+ }
+
+ public void Sign(Ed25519.Algorithm algorithm, Ed25519PublicKeyParameters publicKey, byte[] ctx, byte[] msg, int msgOff, int msgLen,
+ byte[] sig, int sigOff)
+ {
+ byte[] pk = new byte[Ed25519.PublicKeySize];
+ if (null == publicKey)
+ {
+ Ed25519.GeneratePublicKey(data, 0, pk, 0);
+ }
+ else
+ {
+ publicKey.Encode(pk, 0);
+ }
+
+ switch (algorithm)
+ {
+ case Ed25519.Algorithm.Ed25519:
+ {
+ if (null != ctx)
+ throw new ArgumentException("ctx");
+
+ Ed25519.Sign(data, 0, pk, 0, msg, msgOff, msgLen, sig, sigOff);
+ break;
+ }
+ case Ed25519.Algorithm.Ed25519ctx:
+ {
+ Ed25519.Sign(data, 0, pk, 0, ctx, msg, msgOff, msgLen, sig, sigOff);
+ break;
+ }
+ case Ed25519.Algorithm.Ed25519ph:
+ {
+ if (Ed25519.PrehashSize != msgLen)
+ throw new ArgumentException("msgLen");
+
+ Ed25519.SignPrehash(data, 0, pk, 0, ctx, msg, msgOff, sig, sigOff);
+ break;
+ }
+ default:
+ {
+ throw new ArgumentException("algorithm");
+ }
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed25519PrivateKeyParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed25519PrivateKeyParameters.cs.meta
new file mode 100644
index 00000000..ff197afa
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed25519PrivateKeyParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 60049b51ce5e74c47b9f0a552eab4608
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed25519PublicKeyParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed25519PublicKeyParameters.cs
new file mode 100644
index 00000000..c8f20631
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed25519PublicKeyParameters.cs
@@ -0,0 +1,44 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Rfc8032;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public sealed class Ed25519PublicKeyParameters
+ : AsymmetricKeyParameter
+ {
+ public static readonly int KeySize = Ed25519.PublicKeySize;
+
+ private readonly byte[] data = new byte[KeySize];
+
+ public Ed25519PublicKeyParameters(byte[] buf, int off)
+ : base(false)
+ {
+ Array.Copy(buf, off, data, 0, KeySize);
+ }
+
+ public Ed25519PublicKeyParameters(Stream input)
+ : base(false)
+ {
+ if (KeySize != Streams.ReadFully(input, data))
+ throw new EndOfStreamException("EOF encountered in middle of Ed25519 public key");
+ }
+
+ public void Encode(byte[] buf, int off)
+ {
+ Array.Copy(data, 0, buf, off, KeySize);
+ }
+
+ public byte[] GetEncoded()
+ {
+ return Arrays.Clone(data);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed25519PublicKeyParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed25519PublicKeyParameters.cs.meta
new file mode 100644
index 00000000..007d4f96
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed25519PublicKeyParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0d246edc11614ac4eac1f7f7f2fec905
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed448KeyGenerationParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed448KeyGenerationParameters.cs
new file mode 100644
index 00000000..e07c0792
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed448KeyGenerationParameters.cs
@@ -0,0 +1,19 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class Ed448KeyGenerationParameters
+ : KeyGenerationParameters
+ {
+ public Ed448KeyGenerationParameters(SecureRandom random)
+ : base(random, 448)
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed448KeyGenerationParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed448KeyGenerationParameters.cs.meta
new file mode 100644
index 00000000..6d85173e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed448KeyGenerationParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: e70fb91643687874f855792db265a440
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed448PrivateKeyParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed448PrivateKeyParameters.cs
new file mode 100644
index 00000000..b348a017
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed448PrivateKeyParameters.cs
@@ -0,0 +1,94 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Rfc8032;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public sealed class Ed448PrivateKeyParameters
+ : AsymmetricKeyParameter
+ {
+ public static readonly int KeySize = Ed448.SecretKeySize;
+ public static readonly int SignatureSize = Ed448.SignatureSize;
+
+ private readonly byte[] data = new byte[KeySize];
+
+ public Ed448PrivateKeyParameters(SecureRandom random)
+ : base(true)
+ {
+ Ed448.GeneratePrivateKey(random, data);
+ }
+
+ public Ed448PrivateKeyParameters(byte[] buf, int off)
+ : base(true)
+ {
+ Array.Copy(buf, off, data, 0, KeySize);
+ }
+
+ public Ed448PrivateKeyParameters(Stream input)
+ : base(true)
+ {
+ if (KeySize != Streams.ReadFully(input, data))
+ throw new EndOfStreamException("EOF encountered in middle of Ed448 private key");
+ }
+
+ public void Encode(byte[] buf, int off)
+ {
+ Array.Copy(data, 0, buf, off, KeySize);
+ }
+
+ public byte[] GetEncoded()
+ {
+ return Arrays.Clone(data);
+ }
+
+ public Ed448PublicKeyParameters GeneratePublicKey()
+ {
+ byte[] publicKey = new byte[Ed448.PublicKeySize];
+ Ed448.GeneratePublicKey(data, 0, publicKey, 0);
+ return new Ed448PublicKeyParameters(publicKey, 0);
+ }
+
+ public void Sign(Ed448.Algorithm algorithm, Ed448PublicKeyParameters publicKey, byte[] ctx, byte[] msg, int msgOff, int msgLen,
+ byte[] sig, int sigOff)
+ {
+ byte[] pk = new byte[Ed448.PublicKeySize];
+ if (null == publicKey)
+ {
+ Ed448.GeneratePublicKey(data, 0, pk, 0);
+ }
+ else
+ {
+ publicKey.Encode(pk, 0);
+ }
+
+ switch (algorithm)
+ {
+ case Ed448.Algorithm.Ed448:
+ {
+ Ed448.Sign(data, 0, pk, 0, ctx, msg, msgOff, msgLen, sig, sigOff);
+ break;
+ }
+ case Ed448.Algorithm.Ed448ph:
+ {
+ if (Ed448.PrehashSize != msgLen)
+ throw new ArgumentException("msgLen");
+
+ Ed448.SignPrehash(data, 0, pk, 0, ctx, msg, msgOff, sig, sigOff);
+ break;
+ }
+ default:
+ {
+ throw new ArgumentException("algorithm");
+ }
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed448PrivateKeyParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed448PrivateKeyParameters.cs.meta
new file mode 100644
index 00000000..802b44f6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed448PrivateKeyParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: b4c976aa9828651448913498d4f1418c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed448PublicKeyParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed448PublicKeyParameters.cs
new file mode 100644
index 00000000..fb39d592
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed448PublicKeyParameters.cs
@@ -0,0 +1,44 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Rfc8032;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public sealed class Ed448PublicKeyParameters
+ : AsymmetricKeyParameter
+ {
+ public static readonly int KeySize = Ed448.PublicKeySize;
+
+ private readonly byte[] data = new byte[KeySize];
+
+ public Ed448PublicKeyParameters(byte[] buf, int off)
+ : base(false)
+ {
+ Array.Copy(buf, off, data, 0, KeySize);
+ }
+
+ public Ed448PublicKeyParameters(Stream input)
+ : base(false)
+ {
+ if (KeySize != Streams.ReadFully(input, data))
+ throw new EndOfStreamException("EOF encountered in middle of Ed448 public key");
+ }
+
+ public void Encode(byte[] buf, int off)
+ {
+ Array.Copy(data, 0, buf, off, KeySize);
+ }
+
+ public byte[] GetEncoded()
+ {
+ return Arrays.Clone(data);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed448PublicKeyParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed448PublicKeyParameters.cs.meta
new file mode 100644
index 00000000..b7e372e7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Ed448PublicKeyParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: f94469426783edb40b4a167fe5bfaea7
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalKeyGenerationParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalKeyGenerationParameters.cs
new file mode 100644
index 00000000..e0b918c4
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalKeyGenerationParameters.cs
@@ -0,0 +1,35 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class ElGamalKeyGenerationParameters
+ : KeyGenerationParameters
+ {
+ private readonly ElGamalParameters parameters;
+
+ public ElGamalKeyGenerationParameters(
+ SecureRandom random,
+ ElGamalParameters parameters)
+ : base(random, GetStrength(parameters))
+ {
+ this.parameters = parameters;
+ }
+
+ public ElGamalParameters Parameters
+ {
+ get { return parameters; }
+ }
+
+ internal static int GetStrength(
+ ElGamalParameters parameters)
+ {
+ return parameters.L != 0 ? parameters.L : parameters.P.BitLength;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalKeyGenerationParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalKeyGenerationParameters.cs.meta
new file mode 100644
index 00000000..89a4daea
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalKeyGenerationParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 605fe530d358a834b87bd5618b3592eb
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalKeyParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalKeyParameters.cs
new file mode 100644
index 00000000..04b6ae06
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalKeyParameters.cs
@@ -0,0 +1,63 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class ElGamalKeyParameters
+ : AsymmetricKeyParameter
+ {
+ private readonly ElGamalParameters parameters;
+
+ protected ElGamalKeyParameters(
+ bool isPrivate,
+ ElGamalParameters parameters)
+ : base(isPrivate)
+ {
+ // TODO Should we allow 'parameters' to be null?
+ this.parameters = parameters;
+ }
+
+ public ElGamalParameters Parameters
+ {
+ get { return parameters; }
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return true;
+
+ ElGamalKeyParameters other = obj as ElGamalKeyParameters;
+
+ if (other == null)
+ return false;
+
+ return Equals(other);
+ }
+
+ protected bool Equals(
+ ElGamalKeyParameters other)
+ {
+ return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(parameters, other.parameters)
+ && base.Equals(other);
+ }
+
+ public override int GetHashCode()
+ {
+ int hc = base.GetHashCode();
+
+ if (parameters != null)
+ {
+ hc ^= parameters.GetHashCode();
+ }
+
+ return hc;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalKeyParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalKeyParameters.cs.meta
new file mode 100644
index 00000000..4263fd10
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalKeyParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 7cf4458861963154489ccdb128696971
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalParameters.cs
new file mode 100644
index 00000000..bc59ce91
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalParameters.cs
@@ -0,0 +1,85 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class ElGamalParameters
+ : ICipherParameters
+ {
+ private readonly BigInteger p, g;
+ private readonly int l;
+
+ public ElGamalParameters(
+ BigInteger p,
+ BigInteger g)
+ : this(p, g, 0)
+ {
+ }
+
+ public ElGamalParameters(
+ BigInteger p,
+ BigInteger g,
+ int l)
+ {
+ if (p == null)
+ throw new ArgumentNullException("p");
+ if (g == null)
+ throw new ArgumentNullException("g");
+
+ this.p = p;
+ this.g = g;
+ this.l = l;
+ }
+
+ public BigInteger P
+ {
+ get { return p; }
+ }
+
+ /**
+ * return the generator - g
+ */
+ public BigInteger G
+ {
+ get { return g; }
+ }
+
+ /**
+ * return private value limit - l
+ */
+ public int L
+ {
+ get { return l; }
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return true;
+
+ ElGamalParameters other = obj as ElGamalParameters;
+
+ if (other == null)
+ return false;
+
+ return Equals(other);
+ }
+
+ protected bool Equals(
+ ElGamalParameters other)
+ {
+ return p.Equals(other.p) && g.Equals(other.g) && l == other.l;
+ }
+
+ public override int GetHashCode()
+ {
+ return p.GetHashCode() ^ g.GetHashCode() ^ l;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalParameters.cs.meta
new file mode 100644
index 00000000..8cf37eed
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 3e46c9305cb7e5e49a27049f3f2018ae
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalPrivateKeyParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalPrivateKeyParameters.cs
new file mode 100644
index 00000000..c28b94d1
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalPrivateKeyParameters.cs
@@ -0,0 +1,57 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class ElGamalPrivateKeyParameters
+ : ElGamalKeyParameters
+ {
+ private readonly BigInteger x;
+
+ public ElGamalPrivateKeyParameters(
+ BigInteger x,
+ ElGamalParameters parameters)
+ : base(true, parameters)
+ {
+ if (x == null)
+ throw new ArgumentNullException("x");
+
+ this.x = x;
+ }
+
+ public BigInteger X
+ {
+ get { return x; }
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return true;
+
+ ElGamalPrivateKeyParameters other = obj as ElGamalPrivateKeyParameters;
+
+ if (other == null)
+ return false;
+
+ return Equals(other);
+ }
+
+ protected bool Equals(
+ ElGamalPrivateKeyParameters other)
+ {
+ return other.x.Equals(x) && base.Equals(other);
+ }
+
+ public override int GetHashCode()
+ {
+ return x.GetHashCode() ^ base.GetHashCode();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalPrivateKeyParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalPrivateKeyParameters.cs.meta
new file mode 100644
index 00000000..4ca414ee
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalPrivateKeyParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 334db63a79120bd4a8c4f2fa512f5b35
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalPublicKeyParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalPublicKeyParameters.cs
new file mode 100644
index 00000000..71fe9c56
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalPublicKeyParameters.cs
@@ -0,0 +1,57 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class ElGamalPublicKeyParameters
+ : ElGamalKeyParameters
+ {
+ private readonly BigInteger y;
+
+ public ElGamalPublicKeyParameters(
+ BigInteger y,
+ ElGamalParameters parameters)
+ : base(false, parameters)
+ {
+ if (y == null)
+ throw new ArgumentNullException("y");
+
+ this.y = y;
+ }
+
+ public BigInteger Y
+ {
+ get { return y; }
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return true;
+
+ ElGamalPublicKeyParameters other = obj as ElGamalPublicKeyParameters;
+
+ if (other == null)
+ return false;
+
+ return Equals(other);
+ }
+
+ protected bool Equals(
+ ElGamalPublicKeyParameters other)
+ {
+ return y.Equals(other.y) && base.Equals(other);
+ }
+
+ public override int GetHashCode()
+ {
+ return y.GetHashCode() ^ base.GetHashCode();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalPublicKeyParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalPublicKeyParameters.cs.meta
new file mode 100644
index 00000000..8837bf5f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ElGamalPublicKeyParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 66e505fdb6b021e4f826fcdbac27d43f
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410KeyGenerationParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410KeyGenerationParameters.cs
new file mode 100644
index 00000000..1861da5b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410KeyGenerationParameters.cs
@@ -0,0 +1,59 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class Gost3410KeyGenerationParameters
+ : KeyGenerationParameters
+ {
+ private readonly Gost3410Parameters parameters;
+ private readonly DerObjectIdentifier publicKeyParamSet;
+
+ public Gost3410KeyGenerationParameters(
+ SecureRandom random,
+ Gost3410Parameters parameters)
+ : base(random, parameters.P.BitLength - 1)
+ {
+ this.parameters = parameters;
+ }
+
+ public Gost3410KeyGenerationParameters(
+ SecureRandom random,
+ DerObjectIdentifier publicKeyParamSet)
+ : this(random, LookupParameters(publicKeyParamSet))
+ {
+ this.publicKeyParamSet = publicKeyParamSet;
+ }
+
+ public Gost3410Parameters Parameters
+ {
+ get { return parameters; }
+ }
+
+ public DerObjectIdentifier PublicKeyParamSet
+ {
+ get { return publicKeyParamSet; }
+ }
+
+ private static Gost3410Parameters LookupParameters(
+ DerObjectIdentifier publicKeyParamSet)
+ {
+ if (publicKeyParamSet == null)
+ throw new ArgumentNullException("publicKeyParamSet");
+
+ Gost3410ParamSetParameters p = Gost3410NamedParameters.GetByOid(publicKeyParamSet);
+
+ if (p == null)
+ throw new ArgumentException("OID is not a valid CryptoPro public key parameter set", "publicKeyParamSet");
+
+ return new Gost3410Parameters(p.P, p.Q, p.A);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410KeyGenerationParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410KeyGenerationParameters.cs.meta
new file mode 100644
index 00000000..a6d585c9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410KeyGenerationParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 1d2b36972901f8645b70cec28ad5541b
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410KeyParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410KeyParameters.cs
new file mode 100644
index 00000000..f4958a78
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410KeyParameters.cs
@@ -0,0 +1,62 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public abstract class Gost3410KeyParameters
+ : AsymmetricKeyParameter
+ {
+ private readonly Gost3410Parameters parameters;
+ private readonly DerObjectIdentifier publicKeyParamSet;
+
+ protected Gost3410KeyParameters(
+ bool isPrivate,
+ Gost3410Parameters parameters)
+ : base(isPrivate)
+ {
+ this.parameters = parameters;
+ }
+
+ protected Gost3410KeyParameters(
+ bool isPrivate,
+ DerObjectIdentifier publicKeyParamSet)
+ : base(isPrivate)
+ {
+ this.parameters = LookupParameters(publicKeyParamSet);
+ this.publicKeyParamSet = publicKeyParamSet;
+ }
+
+ public Gost3410Parameters Parameters
+ {
+ get { return parameters; }
+ }
+
+ public DerObjectIdentifier PublicKeyParamSet
+ {
+ get { return publicKeyParamSet; }
+ }
+
+ // TODO Implement Equals/GetHashCode
+
+ private static Gost3410Parameters LookupParameters(
+ DerObjectIdentifier publicKeyParamSet)
+ {
+ if (publicKeyParamSet == null)
+ throw new ArgumentNullException("publicKeyParamSet");
+
+ Gost3410ParamSetParameters p = Gost3410NamedParameters.GetByOid(publicKeyParamSet);
+
+ if (p == null)
+ throw new ArgumentException("OID is not a valid CryptoPro public key parameter set", "publicKeyParamSet");
+
+ return new Gost3410Parameters(p.P, p.Q, p.A);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410KeyParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410KeyParameters.cs.meta
new file mode 100644
index 00000000..703d58c7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410KeyParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 1dc6988914e81bd46905d8ebc7b82e2a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410Parameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410Parameters.cs
new file mode 100644
index 00000000..19fe07ef
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410Parameters.cs
@@ -0,0 +1,90 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class Gost3410Parameters
+ : ICipherParameters
+ {
+ private readonly BigInteger p, q, a;
+ private readonly Gost3410ValidationParameters validation;
+
+ public Gost3410Parameters(
+ BigInteger p,
+ BigInteger q,
+ BigInteger a)
+ : this(p, q, a, null)
+ {
+ }
+
+ public Gost3410Parameters(
+ BigInteger p,
+ BigInteger q,
+ BigInteger a,
+ Gost3410ValidationParameters validation)
+ {
+ if (p == null)
+ throw new ArgumentNullException("p");
+ if (q == null)
+ throw new ArgumentNullException("q");
+ if (a == null)
+ throw new ArgumentNullException("a");
+
+ this.p = p;
+ this.q = q;
+ this.a = a;
+ this.validation = validation;
+ }
+
+ public BigInteger P
+ {
+ get { return p; }
+ }
+
+ public BigInteger Q
+ {
+ get { return q; }
+ }
+
+ public BigInteger A
+ {
+ get { return a; }
+ }
+
+ public Gost3410ValidationParameters ValidationParameters
+ {
+ get { return validation; }
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return true;
+
+ Gost3410Parameters other = obj as Gost3410Parameters;
+
+ if (other == null)
+ return false;
+
+ return Equals(other);
+ }
+
+ protected bool Equals(
+ Gost3410Parameters other)
+ {
+ return p.Equals(other.p) && q.Equals(other.q) && a.Equals(other.a);
+ }
+
+ public override int GetHashCode()
+ {
+ return p.GetHashCode() ^ q.GetHashCode() ^ a.GetHashCode();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410Parameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410Parameters.cs.meta
new file mode 100644
index 00000000..95555580
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410Parameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 5dbdc652c3f5f944f87efef0cff09e1e
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410PrivateKeyParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410PrivateKeyParameters.cs
new file mode 100644
index 00000000..8ca4f554
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410PrivateKeyParameters.cs
@@ -0,0 +1,45 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class Gost3410PrivateKeyParameters
+ : Gost3410KeyParameters
+ {
+ private readonly BigInteger x;
+
+ public Gost3410PrivateKeyParameters(
+ BigInteger x,
+ Gost3410Parameters parameters)
+ : base(true, parameters)
+ {
+ if (x.SignValue < 1 || x.BitLength > 256 || x.CompareTo(Parameters.Q) >= 0)
+ throw new ArgumentException("Invalid x for GOST3410 private key", "x");
+
+ this.x = x;
+ }
+
+ public Gost3410PrivateKeyParameters(
+ BigInteger x,
+ DerObjectIdentifier publicKeyParamSet)
+ : base(true, publicKeyParamSet)
+ {
+ if (x.SignValue < 1 || x.BitLength > 256 || x.CompareTo(Parameters.Q) >= 0)
+ throw new ArgumentException("Invalid x for GOST3410 private key", "x");
+
+ this.x = x;
+ }
+
+ public BigInteger X
+ {
+ get { return x; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410PrivateKeyParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410PrivateKeyParameters.cs.meta
new file mode 100644
index 00000000..4e475ad0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410PrivateKeyParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: f6711979a24300844aa8670163e40905
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410PublicKeyParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410PublicKeyParameters.cs
new file mode 100644
index 00000000..31f70538
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410PublicKeyParameters.cs
@@ -0,0 +1,44 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class Gost3410PublicKeyParameters
+ : Gost3410KeyParameters
+ {
+ private readonly BigInteger y;
+
+ public Gost3410PublicKeyParameters(
+ BigInteger y,
+ Gost3410Parameters parameters)
+ : base(false, parameters)
+ {
+ if (y.SignValue < 1 || y.CompareTo(Parameters.P) >= 0)
+ throw new ArgumentException("Invalid y for GOST3410 public key", "y");
+
+ this.y = y;
+ }
+
+ public Gost3410PublicKeyParameters(
+ BigInteger y,
+ DerObjectIdentifier publicKeyParamSet)
+ : base(false, publicKeyParamSet)
+ {
+ if (y.SignValue < 1 || y.CompareTo(Parameters.P) >= 0)
+ throw new ArgumentException("Invalid y for GOST3410 public key", "y");
+
+ this.y = y;
+ }
+
+ public BigInteger Y
+ {
+ get { return y; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410PublicKeyParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410PublicKeyParameters.cs.meta
new file mode 100644
index 00000000..3117dfd4
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410PublicKeyParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 4d46ac587d55b6046a73f3d32ed2c8a0
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410ValidationParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410ValidationParameters.cs
new file mode 100644
index 00000000..71dd73a6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410ValidationParameters.cs
@@ -0,0 +1,55 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class Gost3410ValidationParameters
+ {
+ private int x0;
+ private int c;
+ private long x0L;
+ private long cL;
+
+ public Gost3410ValidationParameters(
+ int x0,
+ int c)
+ {
+ this.x0 = x0;
+ this.c = c;
+ }
+
+ public Gost3410ValidationParameters(
+ long x0L,
+ long cL)
+ {
+ this.x0L = x0L;
+ this.cL = cL;
+ }
+
+ public int C { get { return c; } }
+ public int X0 { get { return x0; } }
+ public long CL { get { return cL; } }
+ public long X0L { get { return x0L; } }
+
+ public override bool Equals(
+ object obj)
+ {
+ Gost3410ValidationParameters other = obj as Gost3410ValidationParameters;
+
+ return other != null
+ && other.c == this.c
+ && other.x0 == this.x0
+ && other.cL == this.cL
+ && other.x0L == this.x0L;
+ }
+
+ public override int GetHashCode()
+ {
+ return c.GetHashCode() ^ x0.GetHashCode() ^ cL.GetHashCode() ^ x0L.GetHashCode();
+ }
+
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410ValidationParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410ValidationParameters.cs.meta
new file mode 100644
index 00000000..3e32abc2
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/GOST3410ValidationParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 3c64f65e9276e6e4785c41edb30a4d8b
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/HKDFParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/HKDFParameters.cs
new file mode 100644
index 00000000..b83bd63b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/HKDFParameters.cs
@@ -0,0 +1,123 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ /**
+ * Parameter class for the HkdfBytesGenerator class.
+ */
+ public class HkdfParameters
+ : IDerivationParameters
+ {
+ private readonly byte[] ikm;
+ private readonly bool skipExpand;
+ private readonly byte[] salt;
+ private readonly byte[] info;
+
+ private HkdfParameters(byte[] ikm, bool skip, byte[] salt, byte[] info)
+ {
+ if (ikm == null)
+ throw new ArgumentNullException("ikm");
+
+ this.ikm = Arrays.Clone(ikm);
+ this.skipExpand = skip;
+
+ if (salt == null || salt.Length == 0)
+ {
+ this.salt = null;
+ }
+ else
+ {
+ this.salt = Arrays.Clone(salt);
+ }
+
+ if (info == null)
+ {
+ this.info = new byte[0];
+ }
+ else
+ {
+ this.info = Arrays.Clone(info);
+ }
+ }
+
+ /**
+ * Generates parameters for HKDF, specifying both the optional salt and
+ * optional info. Step 1: Extract won't be skipped.
+ *
+ * @param ikm the input keying material or seed
+ * @param salt the salt to use, may be null for a salt for hashLen zeros
+ * @param info the info to use, may be null for an info field of zero bytes
+ */
+ public HkdfParameters(byte[] ikm, byte[] salt, byte[] info)
+ : this(ikm, false, salt, info)
+ {
+ }
+
+ /**
+ * Factory method that makes the HKDF skip the extract part of the key
+ * derivation function.
+ *
+ * @param ikm the input keying material or seed, directly used for step 2:
+ * Expand
+ * @param info the info to use, may be null for an info field of zero bytes
+ * @return HKDFParameters that makes the implementation skip step 1
+ */
+ public static HkdfParameters SkipExtractParameters(byte[] ikm, byte[] info)
+ {
+ return new HkdfParameters(ikm, true, null, info);
+ }
+
+ public static HkdfParameters DefaultParameters(byte[] ikm)
+ {
+ return new HkdfParameters(ikm, false, null, null);
+ }
+
+ /**
+ * Returns the input keying material or seed.
+ *
+ * @return the keying material
+ */
+ public virtual byte[] GetIkm()
+ {
+ return Arrays.Clone(ikm);
+ }
+
+ /**
+ * Returns if step 1: extract has to be skipped or not
+ *
+ * @return true for skipping, false for no skipping of step 1
+ */
+ public virtual bool SkipExtract
+ {
+ get { return skipExpand; }
+ }
+
+ /**
+ * Returns the salt, or null if the salt should be generated as a byte array
+ * of HashLen zeros.
+ *
+ * @return the salt, or null
+ */
+ public virtual byte[] GetSalt()
+ {
+ return Arrays.Clone(salt);
+ }
+
+ /**
+ * Returns the info field, which may be empty (null is converted to empty).
+ *
+ * @return the info field, never null
+ */
+ public virtual byte[] GetInfo()
+ {
+ return Arrays.Clone(info);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/HKDFParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/HKDFParameters.cs.meta
new file mode 100644
index 00000000..429b3e1e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/HKDFParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 293360ebd6a248a49be4e61a3bb9a636
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ISO18033KDFParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ISO18033KDFParameters.cs
new file mode 100644
index 00000000..c5a86863
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ISO18033KDFParameters.cs
@@ -0,0 +1,29 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ /**
+ * parameters for Key derivation functions for ISO-18033
+ */
+ public class Iso18033KdfParameters
+ : IDerivationParameters
+ {
+ byte[] seed;
+
+ public Iso18033KdfParameters(
+ byte[] seed)
+ {
+ this.seed = seed;
+ }
+
+ public byte[] GetSeed()
+ {
+ return seed;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ISO18033KDFParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ISO18033KDFParameters.cs.meta
new file mode 100644
index 00000000..a0c89771
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ISO18033KDFParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 1841ab6676510b84a9a6154b0c8c6004
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/IesParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/IesParameters.cs
new file mode 100644
index 00000000..53b4cfa4
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/IesParameters.cs
@@ -0,0 +1,53 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ /**
+ * parameters for using an integrated cipher in stream mode.
+ */
+ public class IesParameters : ICipherParameters
+ {
+ private byte[] derivation;
+ private byte[] encoding;
+ private int macKeySize;
+
+ /**
+ * @param derivation the derivation parameter for the KDF function.
+ * @param encoding the encoding parameter for the KDF function.
+ * @param macKeySize the size of the MAC key (in bits).
+ */
+ public IesParameters(
+ byte[] derivation,
+ byte[] encoding,
+ int macKeySize)
+ {
+ this.derivation = derivation;
+ this.encoding = encoding;
+ this.macKeySize = macKeySize;
+ }
+
+ public byte[] GetDerivationV()
+ {
+ return derivation;
+ }
+
+ public byte[] GetEncodingV()
+ {
+ return encoding;
+ }
+
+ public int MacKeySize
+ {
+ get
+ {
+ return macKeySize;
+ }
+ }
+ }
+
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/IesParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/IesParameters.cs.meta
new file mode 100644
index 00000000..09c63ac5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/IesParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 7c03aa52286eafd459b8fc92fa4177e8
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/IesWithCipherParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/IesWithCipherParameters.cs
new file mode 100644
index 00000000..dc3c220e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/IesWithCipherParameters.cs
@@ -0,0 +1,37 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class IesWithCipherParameters : IesParameters
+ {
+ private int cipherKeySize;
+
+ /**
+ * @param derivation the derivation parameter for the KDF function.
+ * @param encoding the encoding parameter for the KDF function.
+ * @param macKeySize the size of the MAC key (in bits).
+ * @param cipherKeySize the size of the associated Cipher key (in bits).
+ */
+ public IesWithCipherParameters(
+ byte[] derivation,
+ byte[] encoding,
+ int macKeySize,
+ int cipherKeySize) : base(derivation, encoding, macKeySize)
+ {
+ this.cipherKeySize = cipherKeySize;
+ }
+
+ public int CipherKeySize
+ {
+ get
+ {
+ return cipherKeySize;
+ }
+ }
+ }
+
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/IesWithCipherParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/IesWithCipherParameters.cs.meta
new file mode 100644
index 00000000..73334ffb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/IesWithCipherParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c3413d4030dee0b47a112e722521d66c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/KdfParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/KdfParameters.cs
new file mode 100644
index 00000000..ed66588f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/KdfParameters.cs
@@ -0,0 +1,37 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ /**
+ * parameters for Key derivation functions for IEEE P1363a
+ */
+ public class KdfParameters : IDerivationParameters
+ {
+ byte[] iv;
+ byte[] shared;
+
+ public KdfParameters(
+ byte[] shared,
+ byte[] iv)
+ {
+ this.shared = shared;
+ this.iv = iv;
+ }
+
+ public byte[] GetSharedSecret()
+ {
+ return shared;
+ }
+
+ public byte[] GetIV()
+ {
+ return iv;
+ }
+ }
+
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/KdfParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/KdfParameters.cs.meta
new file mode 100644
index 00000000..0371bc4c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/KdfParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 26a35bd34dbec4c4c8291c90a9e688d4
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/KeyParameter.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/KeyParameter.cs
new file mode 100644
index 00000000..8475f6e8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/KeyParameter.cs
@@ -0,0 +1,47 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class KeyParameter
+ : ICipherParameters
+ {
+ private readonly byte[] key;
+
+ public KeyParameter(
+ byte[] key)
+ {
+ if (key == null)
+ throw new ArgumentNullException("key");
+
+ this.key = (byte[]) key.Clone();
+ }
+
+ public KeyParameter(
+ byte[] key,
+ int keyOff,
+ int keyLen)
+ {
+ if (key == null)
+ throw new ArgumentNullException("key");
+ if (keyOff < 0 || keyOff > key.Length)
+ throw new ArgumentOutOfRangeException("keyOff");
+ if (keyLen < 0 || keyLen > (key.Length - keyOff))
+ throw new ArgumentOutOfRangeException("keyLen");
+
+ this.key = new byte[keyLen];
+ Array.Copy(key, keyOff, this.key, 0, keyLen);
+ }
+
+ public byte[] GetKey()
+ {
+ return (byte[]) key.Clone();
+ }
+ }
+
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/KeyParameter.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/KeyParameter.cs.meta
new file mode 100644
index 00000000..f508c555
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/KeyParameter.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: fd79ff15a5360d745bdc45b2083e2958
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/MgfParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/MgfParameters.cs
new file mode 100644
index 00000000..51e86ab5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/MgfParameters.cs
@@ -0,0 +1,35 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ /// Parameters for mask derivation functions.
+ public class MgfParameters
+ : IDerivationParameters
+ {
+ private readonly byte[] seed;
+
+ public MgfParameters(
+ byte[] seed)
+ : this(seed, 0, seed.Length)
+ {
+ }
+
+ public MgfParameters(
+ byte[] seed,
+ int off,
+ int len)
+ {
+ this.seed = new byte[len];
+ Array.Copy(seed, off, this.seed, 0, len);
+ }
+
+ public byte[] GetSeed()
+ {
+ return (byte[]) seed.Clone();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/MgfParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/MgfParameters.cs.meta
new file mode 100644
index 00000000..d792a526
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/MgfParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 75c55f2fe09e5404eac96fe38d1d0a40
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/MqvPrivateParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/MqvPrivateParameters.cs
new file mode 100644
index 00000000..cb8a4c3a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/MqvPrivateParameters.cs
@@ -0,0 +1,68 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class MqvPrivateParameters
+ : ICipherParameters
+ {
+ private readonly ECPrivateKeyParameters staticPrivateKey;
+ private readonly ECPrivateKeyParameters ephemeralPrivateKey;
+ private readonly ECPublicKeyParameters ephemeralPublicKey;
+
+ public MqvPrivateParameters(
+ ECPrivateKeyParameters staticPrivateKey,
+ ECPrivateKeyParameters ephemeralPrivateKey)
+ : this(staticPrivateKey, ephemeralPrivateKey, null)
+ {
+ }
+
+ public MqvPrivateParameters(
+ ECPrivateKeyParameters staticPrivateKey,
+ ECPrivateKeyParameters ephemeralPrivateKey,
+ ECPublicKeyParameters ephemeralPublicKey)
+ {
+ if (staticPrivateKey == null)
+ throw new ArgumentNullException("staticPrivateKey");
+ if (ephemeralPrivateKey == null)
+ throw new ArgumentNullException("ephemeralPrivateKey");
+
+ ECDomainParameters parameters = staticPrivateKey.Parameters;
+ if (!parameters.Equals(ephemeralPrivateKey.Parameters))
+ throw new ArgumentException("Static and ephemeral private keys have different domain parameters");
+
+ if (ephemeralPublicKey == null)
+ {
+ ephemeralPublicKey = new ECPublicKeyParameters(
+ parameters.G.Multiply(ephemeralPrivateKey.D),
+ parameters);
+ }
+ else if (!parameters.Equals(ephemeralPublicKey.Parameters))
+ {
+ throw new ArgumentException("Ephemeral public key has different domain parameters");
+ }
+
+ this.staticPrivateKey = staticPrivateKey;
+ this.ephemeralPrivateKey = ephemeralPrivateKey;
+ this.ephemeralPublicKey = ephemeralPublicKey;
+ }
+
+ public virtual ECPrivateKeyParameters StaticPrivateKey
+ {
+ get { return staticPrivateKey; }
+ }
+
+ public virtual ECPrivateKeyParameters EphemeralPrivateKey
+ {
+ get { return ephemeralPrivateKey; }
+ }
+
+ public virtual ECPublicKeyParameters EphemeralPublicKey
+ {
+ get { return ephemeralPublicKey; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/MqvPrivateParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/MqvPrivateParameters.cs.meta
new file mode 100644
index 00000000..ceb57df8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/MqvPrivateParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 48e1468458832e9438b4568785726d43
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/MqvPublicParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/MqvPublicParameters.cs
new file mode 100644
index 00000000..2cf2c943
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/MqvPublicParameters.cs
@@ -0,0 +1,40 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class MqvPublicParameters
+ : ICipherParameters
+ {
+ private readonly ECPublicKeyParameters staticPublicKey;
+ private readonly ECPublicKeyParameters ephemeralPublicKey;
+
+ public MqvPublicParameters(
+ ECPublicKeyParameters staticPublicKey,
+ ECPublicKeyParameters ephemeralPublicKey)
+ {
+ if (staticPublicKey == null)
+ throw new ArgumentNullException("staticPublicKey");
+ if (ephemeralPublicKey == null)
+ throw new ArgumentNullException("ephemeralPublicKey");
+ if (!staticPublicKey.Parameters.Equals(ephemeralPublicKey.Parameters))
+ throw new ArgumentException("Static and ephemeral public keys have different domain parameters");
+
+ this.staticPublicKey = staticPublicKey;
+ this.ephemeralPublicKey = ephemeralPublicKey;
+ }
+
+ public virtual ECPublicKeyParameters StaticPublicKey
+ {
+ get { return staticPublicKey; }
+ }
+
+ public virtual ECPublicKeyParameters EphemeralPublicKey
+ {
+ get { return ephemeralPublicKey; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/MqvPublicParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/MqvPublicParameters.cs.meta
new file mode 100644
index 00000000..dfa86a67
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/MqvPublicParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: e50ff85b1ca76d8428cde7f72e9d9d34
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/NaccacheSternKeyGenerationParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/NaccacheSternKeyGenerationParameters.cs
new file mode 100644
index 00000000..cb56f457
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/NaccacheSternKeyGenerationParameters.cs
@@ -0,0 +1,102 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ /**
+ * Parameters for NaccacheStern public private key generation. For details on
+ * this cipher, please see
+ *
+ * http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf
+ */
+ public class NaccacheSternKeyGenerationParameters : KeyGenerationParameters
+ {
+ // private BigInteger publicExponent;
+ private readonly int certainty;
+ private readonly int countSmallPrimes;
+
+ /**
+ * Parameters for generating a NaccacheStern KeyPair.
+ *
+ * @param random
+ * The source of randomness
+ * @param strength
+ * The desired strength of the Key in Bits
+ * @param certainty
+ * the probability that the generated primes are not really prime
+ * as integer: 2^(-certainty) is then the probability
+ * @param countSmallPrimes
+ * How many small key factors are desired
+ */
+ public NaccacheSternKeyGenerationParameters(
+ SecureRandom random,
+ int strength,
+ int certainty,
+ int countSmallPrimes)
+ : base(random, strength)
+ {
+ if (countSmallPrimes % 2 == 1)
+ throw new ArgumentException("countSmallPrimes must be a multiple of 2");
+ if (countSmallPrimes < 30)
+ throw new ArgumentException("countSmallPrimes must be >= 30 for security reasons");
+
+ this.certainty = certainty;
+ this.countSmallPrimes = countSmallPrimes;
+ }
+
+ /**
+ * Parameters for a NaccacheStern KeyPair.
+ *
+ * @param random
+ * The source of randomness
+ * @param strength
+ * The desired strength of the Key in Bits
+ * @param certainty
+ * the probability that the generated primes are not really prime
+ * as integer: 2^(-certainty) is then the probability
+ * @param cntSmallPrimes
+ * How many small key factors are desired
+ * @param debug
+ * Ignored
+ */
+ [Obsolete("Use version without 'debug' parameter")]
+ public NaccacheSternKeyGenerationParameters(
+ SecureRandom random,
+ int strength,
+ int certainty,
+ int countSmallPrimes,
+ bool debug)
+ : this(random, strength, certainty, countSmallPrimes)
+ {
+ }
+
+ /**
+ * @return Returns the certainty.
+ */
+ public int Certainty
+ {
+ get { return certainty; }
+ }
+
+ /**
+ * @return Returns the countSmallPrimes.
+ */
+ public int CountSmallPrimes
+ {
+ get { return countSmallPrimes; }
+ }
+
+ [Obsolete("Remove: always false")]
+ public bool IsDebug
+ {
+ get { return false; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/NaccacheSternKeyGenerationParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/NaccacheSternKeyGenerationParameters.cs.meta
new file mode 100644
index 00000000..91605a69
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/NaccacheSternKeyGenerationParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0ee6bf0ab7004704a8e12912a0b65335
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/NaccacheSternKeyParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/NaccacheSternKeyParameters.cs
new file mode 100644
index 00000000..a88c6d54
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/NaccacheSternKeyParameters.cs
@@ -0,0 +1,48 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ /**
+ * Public key parameters for NaccacheStern cipher. For details on this cipher,
+ * please see
+ *
+ * http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf
+ */
+ public class NaccacheSternKeyParameters : AsymmetricKeyParameter
+ {
+ private readonly BigInteger g, n;
+ private readonly int lowerSigmaBound;
+
+ /**
+ * @param privateKey
+ */
+ public NaccacheSternKeyParameters(bool privateKey, BigInteger g, BigInteger n, int lowerSigmaBound)
+ : base(privateKey)
+ {
+ this.g = g;
+ this.n = n;
+ this.lowerSigmaBound = lowerSigmaBound;
+ }
+
+ /**
+ * @return Returns the g.
+ */
+ public BigInteger G { get { return g; } }
+
+ /**
+ * @return Returns the lowerSigmaBound.
+ */
+ public int LowerSigmaBound { get { return lowerSigmaBound; } }
+
+ /**
+ * @return Returns the n.
+ */
+ public BigInteger Modulus { get { return n; } }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/NaccacheSternKeyParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/NaccacheSternKeyParameters.cs.meta
new file mode 100644
index 00000000..b4c99db7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/NaccacheSternKeyParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c608e6e37c22c2c45bae901d561cf8ca
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/NaccacheSternPrivateKeyParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/NaccacheSternPrivateKeyParameters.cs
new file mode 100644
index 00000000..6b43f8a3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/NaccacheSternPrivateKeyParameters.cs
@@ -0,0 +1,83 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ /**
+ * Private key parameters for NaccacheStern cipher. For details on this cipher,
+ * please see
+ *
+ * http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf
+ */
+ public class NaccacheSternPrivateKeyParameters : NaccacheSternKeyParameters
+ {
+ private readonly BigInteger phiN;
+ private readonly IList smallPrimes;
+
+#if !(SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Obsolete]
+ public NaccacheSternPrivateKeyParameters(
+ BigInteger g,
+ BigInteger n,
+ int lowerSigmaBound,
+ ArrayList smallPrimes,
+ BigInteger phiN)
+ : base(true, g, n, lowerSigmaBound)
+ {
+ this.smallPrimes = smallPrimes;
+ this.phiN = phiN;
+ }
+#endif
+
+ /**
+ * Constructs a NaccacheSternPrivateKey
+ *
+ * @param g
+ * the public enryption parameter g
+ * @param n
+ * the public modulus n = p*q
+ * @param lowerSigmaBound
+ * the public lower sigma bound up to which data can be encrypted
+ * @param smallPrimes
+ * the small primes, of which sigma is constructed in the right
+ * order
+ * @param phi_n
+ * the private modulus phi(n) = (p-1)(q-1)
+ */
+ public NaccacheSternPrivateKeyParameters(
+ BigInteger g,
+ BigInteger n,
+ int lowerSigmaBound,
+ IList smallPrimes,
+ BigInteger phiN)
+ : base(true, g, n, lowerSigmaBound)
+ {
+ this.smallPrimes = smallPrimes;
+ this.phiN = phiN;
+ }
+
+ public BigInteger PhiN
+ {
+ get { return phiN; }
+ }
+
+#if !(SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Obsolete("Use 'SmallPrimesList' instead")]
+ public ArrayList SmallPrimes
+ {
+ get { return new ArrayList(smallPrimes); }
+ }
+#endif
+
+ public IList SmallPrimesList
+ {
+ get { return smallPrimes; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/NaccacheSternPrivateKeyParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/NaccacheSternPrivateKeyParameters.cs.meta
new file mode 100644
index 00000000..52e0cab9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/NaccacheSternPrivateKeyParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: bf5a274ff3cb7634f810983e35f3bfde
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithID.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithID.cs
new file mode 100644
index 00000000..cf57afd2
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithID.cs
@@ -0,0 +1,40 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class ParametersWithID
+ : ICipherParameters
+ {
+ private readonly ICipherParameters parameters;
+ private readonly byte[] id;
+
+ public ParametersWithID(ICipherParameters parameters,
+ byte[] id)
+ : this(parameters, id, 0, id.Length)
+ {
+ }
+
+ public ParametersWithID(ICipherParameters parameters,
+ byte[] id, int idOff, int idLen)
+ {
+ this.parameters = parameters;
+ this.id = Arrays.CopyOfRange(id, idOff, idOff + idLen);
+ }
+
+ public byte[] GetID()
+ {
+ return id;
+ }
+
+ public ICipherParameters Parameters
+ {
+ get { return parameters; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithID.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithID.cs.meta
new file mode 100644
index 00000000..a5ab6226
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithID.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c0f143d4cda38054f897e6d8a00c3491
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithIV.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithIV.cs
new file mode 100644
index 00000000..ea03ebe5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithIV.cs
@@ -0,0 +1,44 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class ParametersWithIV
+ : ICipherParameters
+ {
+ private readonly ICipherParameters parameters;
+ private readonly byte[] iv;
+
+ public ParametersWithIV(ICipherParameters parameters,
+ byte[] iv)
+ : this(parameters, iv, 0, iv.Length)
+ {
+ }
+
+ public ParametersWithIV(ICipherParameters parameters,
+ byte[] iv, int ivOff, int ivLen)
+ {
+ // NOTE: 'parameters' may be null to imply key re-use
+ if (iv == null)
+ throw new ArgumentNullException("iv");
+
+ this.parameters = parameters;
+ this.iv = Arrays.CopyOfRange(iv, ivOff, ivOff + ivLen);
+ }
+
+ public byte[] GetIV()
+ {
+ return (byte[])iv.Clone();
+ }
+
+ public ICipherParameters Parameters
+ {
+ get { return parameters; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithIV.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithIV.cs.meta
new file mode 100644
index 00000000..2e8332a3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithIV.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 68fc549489833994d859f97f7f947591
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithRandom.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithRandom.cs
new file mode 100644
index 00000000..719c39c3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithRandom.cs
@@ -0,0 +1,52 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class ParametersWithRandom
+ : ICipherParameters
+ {
+ private readonly ICipherParameters parameters;
+ private readonly SecureRandom random;
+
+ public ParametersWithRandom(
+ ICipherParameters parameters,
+ SecureRandom random)
+ {
+ if (parameters == null)
+ throw new ArgumentNullException("parameters");
+ if (random == null)
+ throw new ArgumentNullException("random");
+
+ this.parameters = parameters;
+ this.random = random;
+ }
+
+ public ParametersWithRandom(
+ ICipherParameters parameters)
+ : this(parameters, new SecureRandom())
+ {
+ }
+
+ [Obsolete("Use Random property instead")]
+ public SecureRandom GetRandom()
+ {
+ return Random;
+ }
+
+ public SecureRandom Random
+ {
+ get { return random; }
+ }
+
+ public ICipherParameters Parameters
+ {
+ get { return parameters; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithRandom.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithRandom.cs.meta
new file mode 100644
index 00000000..854caeeb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithRandom.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 9ce4f2340d8a7d944a7ea4678b7c69ff
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithSBox.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithSBox.cs
new file mode 100644
index 00000000..5ac99850
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithSBox.cs
@@ -0,0 +1,28 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class ParametersWithSBox : ICipherParameters
+ {
+ private ICipherParameters parameters;
+ private byte[] sBox;
+
+ public ParametersWithSBox(
+ ICipherParameters parameters,
+ byte[] sBox)
+ {
+ this.parameters = parameters;
+ this.sBox = sBox;
+ }
+
+ public byte[] GetSBox() { return sBox; }
+
+ public ICipherParameters Parameters { get { return parameters; } }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithSBox.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithSBox.cs.meta
new file mode 100644
index 00000000..af279fb4
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithSBox.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 638195a3abd1d6a46b904b329c8245af
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithSalt.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithSalt.cs
new file mode 100644
index 00000000..84352f3b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithSalt.cs
@@ -0,0 +1,43 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+
+ /// Cipher parameters with a fixed salt value associated with them.
+ public class ParametersWithSalt : ICipherParameters
+ {
+ private byte[] salt;
+ private ICipherParameters parameters;
+
+ public ParametersWithSalt(ICipherParameters parameters, byte[] salt):this(parameters, salt, 0, salt.Length)
+ {
+ }
+
+ public ParametersWithSalt(ICipherParameters parameters, byte[] salt, int saltOff, int saltLen)
+ {
+ this.salt = new byte[saltLen];
+ this.parameters = parameters;
+
+ Array.Copy(salt, saltOff, this.salt, 0, saltLen);
+ }
+
+ public byte[] GetSalt()
+ {
+ return salt;
+ }
+
+ public ICipherParameters Parameters
+ {
+ get
+ {
+ return parameters;
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithSalt.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithSalt.cs.meta
new file mode 100644
index 00000000..b1f4c65c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/ParametersWithSalt.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 46fe3e74d88b9a94892a247fbc85f040
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RC2Parameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RC2Parameters.cs
new file mode 100644
index 00000000..64064ee4
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RC2Parameters.cs
@@ -0,0 +1,51 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class RC2Parameters
+ : KeyParameter
+ {
+ private readonly int bits;
+
+ public RC2Parameters(
+ byte[] key)
+ : this(key, (key.Length > 128) ? 1024 : (key.Length * 8))
+ {
+ }
+
+ public RC2Parameters(
+ byte[] key,
+ int keyOff,
+ int keyLen)
+ : this(key, keyOff, keyLen, (keyLen > 128) ? 1024 : (keyLen * 8))
+ {
+ }
+
+ public RC2Parameters(
+ byte[] key,
+ int bits)
+ : base(key)
+ {
+ this.bits = bits;
+ }
+
+ public RC2Parameters(
+ byte[] key,
+ int keyOff,
+ int keyLen,
+ int bits)
+ : base(key, keyOff, keyLen)
+ {
+ this.bits = bits;
+ }
+
+ public int EffectiveKeyBits
+ {
+ get { return bits; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RC2Parameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RC2Parameters.cs.meta
new file mode 100644
index 00000000..3a73b743
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RC2Parameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 383dd2f6afb5c064e937be5dd2cb7ec8
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RC5Parameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RC5Parameters.cs
new file mode 100644
index 00000000..40137181
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RC5Parameters.cs
@@ -0,0 +1,31 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class RC5Parameters
+ : KeyParameter
+ {
+ private readonly int rounds;
+
+ public RC5Parameters(
+ byte[] key,
+ int rounds)
+ : base(key)
+ {
+ if (key.Length > 255)
+ throw new ArgumentException("RC5 key length can be no greater than 255");
+
+ this.rounds = rounds;
+ }
+
+ public int Rounds
+ {
+ get { return rounds; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RC5Parameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RC5Parameters.cs.meta
new file mode 100644
index 00000000..98206a19
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RC5Parameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 71a86e01a87befa429932b5ce00b9fa6
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RSABlindingParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RSABlindingParameters.cs
new file mode 100644
index 00000000..52a8fe20
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RSABlindingParameters.cs
@@ -0,0 +1,38 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class RsaBlindingParameters
+ : ICipherParameters
+ {
+ private readonly RsaKeyParameters publicKey;
+ private readonly BigInteger blindingFactor;
+
+ public RsaBlindingParameters(
+ RsaKeyParameters publicKey,
+ BigInteger blindingFactor)
+ {
+ if (publicKey.IsPrivate)
+ throw new ArgumentException("RSA parameters should be for a public key");
+
+ this.publicKey = publicKey;
+ this.blindingFactor = blindingFactor;
+ }
+
+ public RsaKeyParameters PublicKey
+ {
+ get { return publicKey; }
+ }
+
+ public BigInteger BlindingFactor
+ {
+ get { return blindingFactor; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RSABlindingParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RSABlindingParameters.cs.meta
new file mode 100644
index 00000000..c573abc1
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RSABlindingParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 64139b13faf91484d84de884824f3b4f
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RsaKeyGenerationParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RsaKeyGenerationParameters.cs
new file mode 100644
index 00000000..9c4cfcc6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RsaKeyGenerationParameters.cs
@@ -0,0 +1,59 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class RsaKeyGenerationParameters
+ : KeyGenerationParameters
+ {
+ private readonly BigInteger publicExponent;
+ private readonly int certainty;
+
+ public RsaKeyGenerationParameters(
+ BigInteger publicExponent,
+ SecureRandom random,
+ int strength,
+ int certainty)
+ : base(random, strength)
+ {
+ this.publicExponent = publicExponent;
+ this.certainty = certainty;
+ }
+
+ public BigInteger PublicExponent
+ {
+ get { return publicExponent; }
+ }
+
+ public int Certainty
+ {
+ get { return certainty; }
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ RsaKeyGenerationParameters other = obj as RsaKeyGenerationParameters;
+
+ if (other == null)
+ {
+ return false;
+ }
+
+ return certainty == other.certainty
+ && publicExponent.Equals(other.publicExponent);
+ }
+
+ public override int GetHashCode()
+ {
+ return certainty.GetHashCode() ^ publicExponent.GetHashCode();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RsaKeyGenerationParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RsaKeyGenerationParameters.cs.meta
new file mode 100644
index 00000000..fb8472c8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RsaKeyGenerationParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 2dfb8ecda9194534ebe72fd378a0a6ba
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RsaKeyParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RsaKeyParameters.cs
new file mode 100644
index 00000000..18827591
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RsaKeyParameters.cs
@@ -0,0 +1,89 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class RsaKeyParameters
+ : AsymmetricKeyParameter
+ {
+ // the value is the product of the 132 smallest primes from 3 to 751
+ private static BigInteger SmallPrimesProduct = new BigInteger(
+ "8138E8A0FCF3A4E84A771D40FD305D7F4AA59306D7251DE54D98AF8FE95729A1" +
+ "F73D893FA424CD2EDC8636A6C3285E022B0E3866A565AE8108EED8591CD4FE8D" +
+ "2CE86165A978D719EBF647F362D33FCA29CD179FB42401CBAF3DF0C614056F9C" +
+ "8F3CFD51E474AFB6BC6974F78DB8ABA8E9E517FDED658591AB7502BD41849462F",
+ 16);
+
+ private static BigInteger Validate(BigInteger modulus)
+ {
+ if ((modulus.IntValue & 1) == 0)
+ throw new ArgumentException("RSA modulus is even", "modulus");
+ if (!modulus.Gcd(SmallPrimesProduct).Equals(BigInteger.One))
+ throw new ArgumentException("RSA modulus has a small prime factor");
+
+ // TODO: add additional primePower/Composite test - expensive!!
+
+ return modulus;
+ }
+
+ private readonly BigInteger modulus;
+ private readonly BigInteger exponent;
+
+ public RsaKeyParameters(
+ bool isPrivate,
+ BigInteger modulus,
+ BigInteger exponent)
+ : base(isPrivate)
+ {
+ if (modulus == null)
+ throw new ArgumentNullException("modulus");
+ if (exponent == null)
+ throw new ArgumentNullException("exponent");
+ if (modulus.SignValue <= 0)
+ throw new ArgumentException("Not a valid RSA modulus", "modulus");
+ if (exponent.SignValue <= 0)
+ throw new ArgumentException("Not a valid RSA exponent", "exponent");
+ if (!isPrivate && (exponent.IntValue & 1) == 0)
+ throw new ArgumentException("RSA publicExponent is even", "exponent");
+
+ this.modulus = Validate(modulus);
+ this.exponent = exponent;
+ }
+
+ public BigInteger Modulus
+ {
+ get { return modulus; }
+ }
+
+ public BigInteger Exponent
+ {
+ get { return exponent; }
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ RsaKeyParameters kp = obj as RsaKeyParameters;
+
+ if (kp == null)
+ {
+ return false;
+ }
+
+ return kp.IsPrivate == this.IsPrivate
+ && kp.Modulus.Equals(this.modulus)
+ && kp.Exponent.Equals(this.exponent);
+ }
+
+ public override int GetHashCode()
+ {
+ return modulus.GetHashCode() ^ exponent.GetHashCode() ^ IsPrivate.GetHashCode();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RsaKeyParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RsaKeyParameters.cs.meta
new file mode 100644
index 00000000..96405082
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RsaKeyParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 8fbdd0c93dcb1ea49b65b46b26c2d1db
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RsaPrivateCrtKeyParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RsaPrivateCrtKeyParameters.cs
new file mode 100644
index 00000000..85e028a9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RsaPrivateCrtKeyParameters.cs
@@ -0,0 +1,122 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class RsaPrivateCrtKeyParameters
+ : RsaKeyParameters
+ {
+ private readonly BigInteger e, p, q, dP, dQ, qInv;
+
+ public RsaPrivateCrtKeyParameters(
+ BigInteger modulus,
+ BigInteger publicExponent,
+ BigInteger privateExponent,
+ BigInteger p,
+ BigInteger q,
+ BigInteger dP,
+ BigInteger dQ,
+ BigInteger qInv)
+ : base(true, modulus, privateExponent)
+ {
+ ValidateValue(publicExponent, "publicExponent", "exponent");
+ ValidateValue(p, "p", "P value");
+ ValidateValue(q, "q", "Q value");
+ ValidateValue(dP, "dP", "DP value");
+ ValidateValue(dQ, "dQ", "DQ value");
+ ValidateValue(qInv, "qInv", "InverseQ value");
+
+ this.e = publicExponent;
+ this.p = p;
+ this.q = q;
+ this.dP = dP;
+ this.dQ = dQ;
+ this.qInv = qInv;
+ }
+
+ public RsaPrivateCrtKeyParameters(RsaPrivateKeyStructure rsaPrivateKey)
+ : this(
+ rsaPrivateKey.Modulus,
+ rsaPrivateKey.PublicExponent,
+ rsaPrivateKey.PrivateExponent,
+ rsaPrivateKey.Prime1,
+ rsaPrivateKey.Prime2,
+ rsaPrivateKey.Exponent1,
+ rsaPrivateKey.Exponent2,
+ rsaPrivateKey.Coefficient)
+ {
+ }
+
+ public BigInteger PublicExponent
+ {
+ get { return e; }
+ }
+
+ public BigInteger P
+ {
+ get { return p; }
+ }
+
+ public BigInteger Q
+ {
+ get { return q; }
+ }
+
+ public BigInteger DP
+ {
+ get { return dP; }
+ }
+
+ public BigInteger DQ
+ {
+ get { return dQ; }
+ }
+
+ public BigInteger QInv
+ {
+ get { return qInv; }
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return true;
+
+ RsaPrivateCrtKeyParameters kp = obj as RsaPrivateCrtKeyParameters;
+
+ if (kp == null)
+ return false;
+
+ return kp.DP.Equals(dP)
+ && kp.DQ.Equals(dQ)
+ && kp.Exponent.Equals(this.Exponent)
+ && kp.Modulus.Equals(this.Modulus)
+ && kp.P.Equals(p)
+ && kp.Q.Equals(q)
+ && kp.PublicExponent.Equals(e)
+ && kp.QInv.Equals(qInv);
+ }
+
+ public override int GetHashCode()
+ {
+ return DP.GetHashCode() ^ DQ.GetHashCode() ^ Exponent.GetHashCode() ^ Modulus.GetHashCode()
+ ^ P.GetHashCode() ^ Q.GetHashCode() ^ PublicExponent.GetHashCode() ^ QInv.GetHashCode();
+ }
+
+ private static void ValidateValue(BigInteger x, string name, string desc)
+ {
+ if (x == null)
+ throw new ArgumentNullException(name);
+ if (x.SignValue <= 0)
+ throw new ArgumentException("Not a valid RSA " + desc, name);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RsaPrivateCrtKeyParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RsaPrivateCrtKeyParameters.cs.meta
new file mode 100644
index 00000000..03893cab
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/RsaPrivateCrtKeyParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: b78b91bb256c288459bcb8c8aeb11f63
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/SM2KeyExchangePrivateParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/SM2KeyExchangePrivateParameters.cs
new file mode 100644
index 00000000..178f0db7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/SM2KeyExchangePrivateParameters.cs
@@ -0,0 +1,68 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ /// Private parameters for an SM2 key exchange.
+ /// The ephemeralPrivateKey is used to calculate the random point used in the algorithm.
+ public class SM2KeyExchangePrivateParameters
+ : ICipherParameters
+ {
+ private readonly bool mInitiator;
+ private readonly ECPrivateKeyParameters mStaticPrivateKey;
+ private readonly ECPoint mStaticPublicPoint;
+ private readonly ECPrivateKeyParameters mEphemeralPrivateKey;
+ private readonly ECPoint mEphemeralPublicPoint;
+
+ public SM2KeyExchangePrivateParameters(
+ bool initiator,
+ ECPrivateKeyParameters staticPrivateKey,
+ ECPrivateKeyParameters ephemeralPrivateKey)
+ {
+ if (staticPrivateKey == null)
+ throw new ArgumentNullException("staticPrivateKey");
+ if (ephemeralPrivateKey == null)
+ throw new ArgumentNullException("ephemeralPrivateKey");
+
+ ECDomainParameters parameters = staticPrivateKey.Parameters;
+ if (!parameters.Equals(ephemeralPrivateKey.Parameters))
+ throw new ArgumentException("Static and ephemeral private keys have different domain parameters");
+
+ this.mInitiator = initiator;
+ this.mStaticPrivateKey = staticPrivateKey;
+ this.mStaticPublicPoint = parameters.G.Multiply(staticPrivateKey.D).Normalize();
+ this.mEphemeralPrivateKey = ephemeralPrivateKey;
+ this.mEphemeralPublicPoint = parameters.G.Multiply(ephemeralPrivateKey.D).Normalize();
+ }
+
+ public virtual bool IsInitiator
+ {
+ get { return mInitiator; }
+ }
+
+ public virtual ECPrivateKeyParameters StaticPrivateKey
+ {
+ get { return mStaticPrivateKey; }
+ }
+
+ public virtual ECPoint StaticPublicPoint
+ {
+ get { return mStaticPublicPoint; }
+ }
+
+ public virtual ECPrivateKeyParameters EphemeralPrivateKey
+ {
+ get { return mEphemeralPrivateKey; }
+ }
+
+ public virtual ECPoint EphemeralPublicPoint
+ {
+ get { return mEphemeralPublicPoint; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/SM2KeyExchangePrivateParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/SM2KeyExchangePrivateParameters.cs.meta
new file mode 100644
index 00000000..c8bf417d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/SM2KeyExchangePrivateParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: e8b2b11f2864c51499f5b2c0cad414b4
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/SM2KeyExchangePublicParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/SM2KeyExchangePublicParameters.cs
new file mode 100644
index 00000000..f39eb380
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/SM2KeyExchangePublicParameters.cs
@@ -0,0 +1,44 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ /// Public parameters for an SM2 key exchange.
+ /// In this case the ephemeralPublicKey provides the random point used in the algorithm.
+ public class SM2KeyExchangePublicParameters
+ : ICipherParameters
+ {
+ private readonly ECPublicKeyParameters mStaticPublicKey;
+ private readonly ECPublicKeyParameters mEphemeralPublicKey;
+
+ public SM2KeyExchangePublicParameters(
+ ECPublicKeyParameters staticPublicKey,
+ ECPublicKeyParameters ephemeralPublicKey)
+ {
+ if (staticPublicKey == null)
+ throw new ArgumentNullException("staticPublicKey");
+ if (ephemeralPublicKey == null)
+ throw new ArgumentNullException("ephemeralPublicKey");
+ if (!staticPublicKey.Parameters.Equals(ephemeralPublicKey.Parameters))
+ throw new ArgumentException("Static and ephemeral public keys have different domain parameters");
+
+ this.mStaticPublicKey = staticPublicKey;
+ this.mEphemeralPublicKey = ephemeralPublicKey;
+ }
+
+ public virtual ECPublicKeyParameters StaticPublicKey
+ {
+ get { return mStaticPublicKey; }
+ }
+
+ public virtual ECPublicKeyParameters EphemeralPublicKey
+ {
+ get { return mEphemeralPublicKey; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/SM2KeyExchangePublicParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/SM2KeyExchangePublicParameters.cs.meta
new file mode 100644
index 00000000..71a3933c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/SM2KeyExchangePublicParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 64f9f4869ef3631459fffa7cffcff1cc
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/SkeinParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/SkeinParameters.cs
new file mode 100644
index 00000000..a93a8acc
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/SkeinParameters.cs
@@ -0,0 +1,290 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.Globalization;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+
+ ///
+ /// Parameters for the Skein hash function - a series of byte[] strings identified by integer tags.
+ ///
+ ///
+ /// Parameterised Skein can be used for:
+ ///
+ ///
MAC generation, by providing a key.
+ ///
Randomised hashing, by providing a nonce.
+ ///
A hash function for digital signatures, associating a
+ /// public key with the message digest.
+ ///
A key derivation function, by providing a
+ /// key identifier.
+ ///
Personalised hashing, by providing a
+ /// recommended format or
+ /// arbitrary personalisation string.
+ ///
+ ///
+ ///
+ ///
+ ///
+ public class SkeinParameters
+ : ICipherParameters
+ {
+ ///
+ /// The parameter type for a secret key, supporting MAC or KDF functions: 0
+ ///
+ public const int PARAM_TYPE_KEY = 0;
+
+ ///
+ /// The parameter type for the Skein configuration block: 4
+ ///
+ public const int PARAM_TYPE_CONFIG = 4;
+
+ ///
+ /// The parameter type for a personalisation string: 8
+ ///
+ public const int PARAM_TYPE_PERSONALISATION = 8;
+
+ ///
+ /// The parameter type for a public key: 12
+ ///
+ public const int PARAM_TYPE_PUBLIC_KEY = 12;
+
+ ///
+ /// The parameter type for a key identifier string: 16
+ ///
+ public const int PARAM_TYPE_KEY_IDENTIFIER = 16;
+
+ ///
+ /// The parameter type for a nonce: 20
+ ///
+ public const int PARAM_TYPE_NONCE = 20;
+
+ ///
+ /// The parameter type for the message: 48
+ ///
+ public const int PARAM_TYPE_MESSAGE = 48;
+
+ ///
+ /// The parameter type for the output transformation: 63
+ ///
+ public const int PARAM_TYPE_OUTPUT = 63;
+
+ private IDictionary parameters;
+
+ public SkeinParameters()
+ : this(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable())
+
+ {
+ }
+
+ private SkeinParameters(IDictionary parameters)
+ {
+ this.parameters = parameters;
+ }
+
+ ///
+ /// Obtains a map of type (int) to value (byte[]) for the parameters tracked in this object.
+ ///
+ public IDictionary GetParameters()
+ {
+ return parameters;
+ }
+
+ ///
+ /// Obtains the value of the key parameter, or null if not
+ /// set.
+ ///
+ /// The key.
+ public byte[] GetKey()
+ {
+ return (byte[])parameters[PARAM_TYPE_KEY];
+ }
+
+ ///
+ /// Obtains the value of the personalisation parameter, or
+ /// null if not set.
+ ///
+ public byte[] GetPersonalisation()
+ {
+ return (byte[])parameters[PARAM_TYPE_PERSONALISATION];
+ }
+
+ ///
+ /// Obtains the value of the public key parameter, or
+ /// null if not set.
+ ///
+ public byte[] GetPublicKey()
+ {
+ return (byte[])parameters[PARAM_TYPE_PUBLIC_KEY];
+ }
+
+ ///
+ /// Obtains the value of the key identifier parameter, or
+ /// null if not set.
+ ///
+ public byte[] GetKeyIdentifier()
+ {
+ return (byte[])parameters[PARAM_TYPE_KEY_IDENTIFIER];
+ }
+
+ ///
+ /// Obtains the value of the nonce parameter, or null if
+ /// not set.
+ ///
+ public byte[] GetNonce()
+ {
+ return (byte[])parameters[PARAM_TYPE_NONCE];
+ }
+
+ ///
+ /// A builder for .
+ ///
+ public class Builder
+ {
+ private IDictionary parameters = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+
+ public Builder()
+ {
+ }
+
+ public Builder(IDictionary paramsMap)
+ {
+ IEnumerator keys = paramsMap.Keys.GetEnumerator();
+ while (keys.MoveNext())
+ {
+ int key = (int)keys.Current;
+ parameters.Add(key, paramsMap[key]);
+ }
+ }
+
+ public Builder(SkeinParameters parameters)
+ {
+ IEnumerator keys = parameters.parameters.Keys.GetEnumerator();
+ while (keys.MoveNext())
+ {
+ int key = (int)keys.Current;
+ this.parameters.Add(key, parameters.parameters[key]);
+ }
+ }
+
+ ///
+ /// Sets a parameters to apply to the Skein hash function.
+ ///
+ ///
+ /// Parameter types must be in the range 0,5..62, and cannot use the value 48
+ /// (reserved for message body).
+ ///
+ /// Parameters with type < 48 are processed before
+ /// the message content, parameters with type > 48
+ /// are processed after the message and prior to output.
+ ///
+ /// the type of the parameter, in the range 5..62.
+ /// the byte sequence of the parameter.
+ public Builder Set(int type, byte[] value)
+ {
+ if (value == null)
+ {
+ throw new ArgumentException("Parameter value must not be null.");
+ }
+ if ((type != PARAM_TYPE_KEY)
+ && (type <= PARAM_TYPE_CONFIG || type >= PARAM_TYPE_OUTPUT || type == PARAM_TYPE_MESSAGE))
+ {
+ throw new ArgumentException("Parameter types must be in the range 0,5..47,49..62.");
+ }
+ if (type == PARAM_TYPE_CONFIG)
+ {
+ throw new ArgumentException("Parameter type " + PARAM_TYPE_CONFIG
+ + " is reserved for internal use.");
+ }
+ this.parameters.Add(type, value);
+ return this;
+ }
+
+ ///
+ /// Sets the parameter.
+ ///
+ public Builder SetKey(byte[] key)
+ {
+ return Set(PARAM_TYPE_KEY, key);
+ }
+
+ ///
+ /// Sets the parameter.
+ ///
+ public Builder SetPersonalisation(byte[] personalisation)
+ {
+ return Set(PARAM_TYPE_PERSONALISATION, personalisation);
+ }
+
+ ///
+ /// Implements the recommended personalisation format for Skein defined in Section 4.11 of
+ /// the Skein 1.3 specification.
+ ///
+ ///
+ /// The format is YYYYMMDD email@address distinguisher, encoded to a byte
+ /// sequence using UTF-8 encoding.
+ ///
+ /// the date the personalised application of the Skein was defined.
+ /// the email address of the creation of the personalised application.
+ /// an arbitrary personalisation string distinguishing the application.
+ public Builder SetPersonalisation(DateTime date, string emailAddress, string distinguisher)
+ {
+ try
+ {
+ MemoryStream bout = new MemoryStream();
+ StreamWriter outBytes = new StreamWriter(bout, System.Text.Encoding.UTF8);
+ outBytes.Write(date.ToString("YYYYMMDD", CultureInfo.InvariantCulture));
+ outBytes.Write(" ");
+ outBytes.Write(emailAddress);
+ outBytes.Write(" ");
+ outBytes.Write(distinguisher);
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(outBytes);
+ return Set(PARAM_TYPE_PERSONALISATION, bout.ToArray());
+ }
+ catch (IOException e)
+ {
+ throw new InvalidOperationException("Byte I/O failed.", e);
+ }
+ }
+
+ ///
+ /// Sets the parameter.
+ ///
+ public Builder SetPublicKey(byte[] publicKey)
+ {
+ return Set(PARAM_TYPE_PUBLIC_KEY, publicKey);
+ }
+
+ ///
+ /// Sets the parameter.
+ ///
+ public Builder SetKeyIdentifier(byte[] keyIdentifier)
+ {
+ return Set(PARAM_TYPE_KEY_IDENTIFIER, keyIdentifier);
+ }
+
+ ///
+ /// Sets the parameter.
+ ///
+ public Builder SetNonce(byte[] nonce)
+ {
+ return Set(PARAM_TYPE_NONCE, nonce);
+ }
+
+ ///
+ /// Constructs a new instance with the parameters provided to this
+ /// builder.
+ ///
+ public SkeinParameters Build()
+ {
+ return new SkeinParameters(parameters);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/SkeinParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/SkeinParameters.cs.meta
new file mode 100644
index 00000000..258bb2a5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/SkeinParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 04b73b990c8ab224b97961b1dd1fb4f2
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Srp6GroupParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Srp6GroupParameters.cs
new file mode 100644
index 00000000..f37abe61
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Srp6GroupParameters.cs
@@ -0,0 +1,31 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public sealed class Srp6GroupParameters
+ {
+ private readonly BigInteger n, g;
+
+ public Srp6GroupParameters(BigInteger N, BigInteger g)
+ {
+ this.n = N;
+ this.g = g;
+ }
+
+ public BigInteger G
+ {
+ get { return g; }
+ }
+
+ public BigInteger N
+ {
+ get { return n; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Srp6GroupParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Srp6GroupParameters.cs.meta
new file mode 100644
index 00000000..345ab156
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/Srp6GroupParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 04d30757713732143b4d9cc5087b8682
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/TweakableBlockCipherParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/TweakableBlockCipherParameters.cs
new file mode 100644
index 00000000..53f0308c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/TweakableBlockCipherParameters.cs
@@ -0,0 +1,44 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+
+ ///
+ /// Parameters for tweakable block ciphers.
+ ///
+ public class TweakableBlockCipherParameters
+ : ICipherParameters
+ {
+ private readonly byte[] tweak;
+ private readonly KeyParameter key;
+
+ public TweakableBlockCipherParameters(KeyParameter key, byte[] tweak)
+ {
+ this.key = key;
+ this.tweak = Arrays.Clone(tweak);
+ }
+
+ ///
+ /// Gets the key.
+ ///
+ /// the key to use, or null to use the current key.
+ public KeyParameter Key
+ {
+ get { return key; }
+ }
+
+ ///
+ /// Gets the tweak value.
+ ///
+ /// The tweak to use, or null to use the current tweak.
+ public byte[] Tweak
+ {
+ get { return tweak; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/TweakableBlockCipherParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/TweakableBlockCipherParameters.cs.meta
new file mode 100644
index 00000000..5ea901ac
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/TweakableBlockCipherParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 8535be3fd9fd37f4387792c8e64eb4b0
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X25519KeyGenerationParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X25519KeyGenerationParameters.cs
new file mode 100644
index 00000000..718d57a1
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X25519KeyGenerationParameters.cs
@@ -0,0 +1,19 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class X25519KeyGenerationParameters
+ : KeyGenerationParameters
+ {
+ public X25519KeyGenerationParameters(SecureRandom random)
+ : base(random, 255)
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X25519KeyGenerationParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X25519KeyGenerationParameters.cs.meta
new file mode 100644
index 00000000..fbae2b1a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X25519KeyGenerationParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 34b65ca852361294a88bedf107bfbb97
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X25519PrivateKeyParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X25519PrivateKeyParameters.cs
new file mode 100644
index 00000000..6dbf9c06
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X25519PrivateKeyParameters.cs
@@ -0,0 +1,67 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Rfc7748;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public sealed class X25519PrivateKeyParameters
+ : AsymmetricKeyParameter
+ {
+ public static readonly int KeySize = X25519.ScalarSize;
+ public static readonly int SecretSize = X25519.PointSize;
+
+ private readonly byte[] data = new byte[KeySize];
+
+ public X25519PrivateKeyParameters(SecureRandom random)
+ : base(true)
+ {
+ X25519.GeneratePrivateKey(random, data);
+ }
+
+ public X25519PrivateKeyParameters(byte[] buf, int off)
+ : base(true)
+ {
+ Array.Copy(buf, off, data, 0, KeySize);
+ }
+
+ public X25519PrivateKeyParameters(Stream input)
+ : base(true)
+ {
+ if (KeySize != Streams.ReadFully(input, data))
+ throw new EndOfStreamException("EOF encountered in middle of X25519 private key");
+ }
+
+ public void Encode(byte[] buf, int off)
+ {
+ Array.Copy(data, 0, buf, off, KeySize);
+ }
+
+ public byte[] GetEncoded()
+ {
+ return Arrays.Clone(data);
+ }
+
+ public X25519PublicKeyParameters GeneratePublicKey()
+ {
+ byte[] publicKey = new byte[X25519.PointSize];
+ X25519.GeneratePublicKey(data, 0, publicKey, 0);
+ return new X25519PublicKeyParameters(publicKey, 0);
+ }
+
+ public void GenerateSecret(X25519PublicKeyParameters publicKey, byte[] buf, int off)
+ {
+ byte[] encoded = new byte[X25519.PointSize];
+ publicKey.Encode(encoded, 0);
+ if (!X25519.CalculateAgreement(data, 0, encoded, 0, buf, off))
+ throw new InvalidOperationException("X25519 agreement failed");
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X25519PrivateKeyParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X25519PrivateKeyParameters.cs.meta
new file mode 100644
index 00000000..c907832f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X25519PrivateKeyParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a01dc8b4999799642ba9fc316dccb701
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X25519PublicKeyParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X25519PublicKeyParameters.cs
new file mode 100644
index 00000000..2fc13afc
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X25519PublicKeyParameters.cs
@@ -0,0 +1,44 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Rfc7748;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public sealed class X25519PublicKeyParameters
+ : AsymmetricKeyParameter
+ {
+ public static readonly int KeySize = X25519.PointSize;
+
+ private readonly byte[] data = new byte[KeySize];
+
+ public X25519PublicKeyParameters(byte[] buf, int off)
+ : base(false)
+ {
+ Array.Copy(buf, off, data, 0, KeySize);
+ }
+
+ public X25519PublicKeyParameters(Stream input)
+ : base(false)
+ {
+ if (KeySize != Streams.ReadFully(input, data))
+ throw new EndOfStreamException("EOF encountered in middle of X25519 public key");
+ }
+
+ public void Encode(byte[] buf, int off)
+ {
+ Array.Copy(data, 0, buf, off, KeySize);
+ }
+
+ public byte[] GetEncoded()
+ {
+ return Arrays.Clone(data);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X25519PublicKeyParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X25519PublicKeyParameters.cs.meta
new file mode 100644
index 00000000..4e952bff
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X25519PublicKeyParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: adb017b96c708f947bdfd05e8ed09197
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X448KeyGenerationParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X448KeyGenerationParameters.cs
new file mode 100644
index 00000000..87749fa8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X448KeyGenerationParameters.cs
@@ -0,0 +1,19 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public class X448KeyGenerationParameters
+ : KeyGenerationParameters
+ {
+ public X448KeyGenerationParameters(SecureRandom random)
+ : base(random, 448)
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X448KeyGenerationParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X448KeyGenerationParameters.cs.meta
new file mode 100644
index 00000000..67b6f3b8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X448KeyGenerationParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 28e1826bc7c435c4c90c3a42d42b3641
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X448PrivateKeyParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X448PrivateKeyParameters.cs
new file mode 100644
index 00000000..f1abb297
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X448PrivateKeyParameters.cs
@@ -0,0 +1,67 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Rfc7748;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public sealed class X448PrivateKeyParameters
+ : AsymmetricKeyParameter
+ {
+ public static readonly int KeySize = X448.ScalarSize;
+ public static readonly int SecretSize = X448.PointSize;
+
+ private readonly byte[] data = new byte[KeySize];
+
+ public X448PrivateKeyParameters(SecureRandom random)
+ : base(true)
+ {
+ X448.GeneratePrivateKey(random, data);
+ }
+
+ public X448PrivateKeyParameters(byte[] buf, int off)
+ : base(true)
+ {
+ Array.Copy(buf, off, data, 0, KeySize);
+ }
+
+ public X448PrivateKeyParameters(Stream input)
+ : base(true)
+ {
+ if (KeySize != Streams.ReadFully(input, data))
+ throw new EndOfStreamException("EOF encountered in middle of X448 private key");
+ }
+
+ public void Encode(byte[] buf, int off)
+ {
+ Array.Copy(data, 0, buf, off, KeySize);
+ }
+
+ public byte[] GetEncoded()
+ {
+ return Arrays.Clone(data);
+ }
+
+ public X448PublicKeyParameters GeneratePublicKey()
+ {
+ byte[] publicKey = new byte[X448.PointSize];
+ X448.GeneratePublicKey(data, 0, publicKey, 0);
+ return new X448PublicKeyParameters(publicKey, 0);
+ }
+
+ public void GenerateSecret(X448PublicKeyParameters publicKey, byte[] buf, int off)
+ {
+ byte[] encoded = new byte[X448.PointSize];
+ publicKey.Encode(encoded, 0);
+ if (!X448.CalculateAgreement(data, 0, encoded, 0, buf, off))
+ throw new InvalidOperationException("X448 agreement failed");
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X448PrivateKeyParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X448PrivateKeyParameters.cs.meta
new file mode 100644
index 00000000..ffd26a69
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X448PrivateKeyParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 9bfb9abfbe5e9144192249ae8d52c553
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X448PublicKeyParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X448PublicKeyParameters.cs
new file mode 100644
index 00000000..4ea87ea5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X448PublicKeyParameters.cs
@@ -0,0 +1,44 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Rfc7748;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters
+{
+ public sealed class X448PublicKeyParameters
+ : AsymmetricKeyParameter
+ {
+ public static readonly int KeySize = X448.PointSize;
+
+ private readonly byte[] data = new byte[KeySize];
+
+ public X448PublicKeyParameters(byte[] buf, int off)
+ : base(false)
+ {
+ Array.Copy(buf, off, data, 0, KeySize);
+ }
+
+ public X448PublicKeyParameters(Stream input)
+ : base(false)
+ {
+ if (KeySize != Streams.ReadFully(input, data))
+ throw new EndOfStreamException("EOF encountered in middle of X448 public key");
+ }
+
+ public void Encode(byte[] buf, int off)
+ {
+ Array.Copy(data, 0, buf, off, KeySize);
+ }
+
+ public byte[] GetEncoded()
+ {
+ return Arrays.Clone(data);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X448PublicKeyParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X448PublicKeyParameters.cs.meta
new file mode 100644
index 00000000..3e0f9144
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/parameters/X448PublicKeyParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 2f1678e519b7aad4bb9fa3e9eadd39c9
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng.meta
new file mode 100644
index 00000000..90986746
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 0a4df581a93a3a246848f91de3e20edf
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/BasicEntropySourceProvider.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/BasicEntropySourceProvider.cs
new file mode 100644
index 00000000..06866218
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/BasicEntropySourceProvider.cs
@@ -0,0 +1,75 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng
+{
+ /**
+ * An EntropySourceProvider where entropy generation is based on a SecureRandom output using SecureRandom.generateSeed().
+ */
+ public class BasicEntropySourceProvider
+ : IEntropySourceProvider
+ {
+ private readonly SecureRandom mSecureRandom;
+ private readonly bool mPredictionResistant;
+
+ /**
+ * Create a entropy source provider based on the passed in SecureRandom.
+ *
+ * @param secureRandom the SecureRandom to base EntropySource construction on.
+ * @param isPredictionResistant boolean indicating if the SecureRandom is based on prediction resistant entropy or not (true if it is).
+ */
+ public BasicEntropySourceProvider(SecureRandom secureRandom, bool isPredictionResistant)
+ {
+ mSecureRandom = secureRandom;
+ mPredictionResistant = isPredictionResistant;
+ }
+
+ /**
+ * Return an entropy source that will create bitsRequired bits of entropy on
+ * each invocation of getEntropy().
+ *
+ * @param bitsRequired size (in bits) of entropy to be created by the provided source.
+ * @return an EntropySource that generates bitsRequired bits of entropy on each call to its getEntropy() method.
+ */
+ public IEntropySource Get(int bitsRequired)
+ {
+ return new BasicEntropySource(mSecureRandom, mPredictionResistant, bitsRequired);
+ }
+
+ private class BasicEntropySource
+ : IEntropySource
+ {
+ private readonly SecureRandom mSecureRandom;
+ private readonly bool mPredictionResistant;
+ private readonly int mEntropySize;
+
+ internal BasicEntropySource(SecureRandom secureRandom, bool predictionResistant, int entropySize)
+ {
+ this.mSecureRandom = secureRandom;
+ this.mPredictionResistant = predictionResistant;
+ this.mEntropySize = entropySize;
+ }
+
+ bool IEntropySource.IsPredictionResistant
+ {
+ get { return mPredictionResistant; }
+ }
+
+ byte[] IEntropySource.GetEntropy()
+ {
+ // TODO[FIPS] Not all SecureRandom implementations are considered valid entropy sources
+ return SecureRandom.GetNextBytes(mSecureRandom, (mEntropySize + 7) / 8);
+ }
+
+ int IEntropySource.EntropySize
+ {
+ get { return mEntropySize; }
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/BasicEntropySourceProvider.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/BasicEntropySourceProvider.cs.meta
new file mode 100644
index 00000000..94715764
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/BasicEntropySourceProvider.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 7f55c9b6e8b6c844ca193d3ee8949628
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/CryptoApiEntropySourceProvider.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/CryptoApiEntropySourceProvider.cs
new file mode 100644
index 00000000..f717ac60
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/CryptoApiEntropySourceProvider.cs
@@ -0,0 +1,74 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+#if !(NETCF_1_0 || PORTABLE || NETFX_CORE)
+using System;
+using System.Security.Cryptography;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng
+{
+ public class CryptoApiEntropySourceProvider
+ : IEntropySourceProvider
+ {
+ private readonly RandomNumberGenerator mRng;
+ private readonly bool mPredictionResistant;
+
+ public CryptoApiEntropySourceProvider()
+ : this(RandomNumberGenerator.Create(), true)
+ {
+ }
+
+ public CryptoApiEntropySourceProvider(RandomNumberGenerator rng, bool isPredictionResistant)
+ {
+ if (rng == null)
+ throw new ArgumentNullException("rng");
+
+ mRng = rng;
+ mPredictionResistant = isPredictionResistant;
+ }
+
+ public IEntropySource Get(int bitsRequired)
+ {
+ return new CryptoApiEntropySource(mRng, mPredictionResistant, bitsRequired);
+ }
+
+ private class CryptoApiEntropySource
+ : IEntropySource
+ {
+ private readonly RandomNumberGenerator mRng;
+ private readonly bool mPredictionResistant;
+ private readonly int mEntropySize;
+
+ internal CryptoApiEntropySource(RandomNumberGenerator rng, bool predictionResistant, int entropySize)
+ {
+ this.mRng = rng;
+ this.mPredictionResistant = predictionResistant;
+ this.mEntropySize = entropySize;
+ }
+
+ #region IEntropySource Members
+
+ bool IEntropySource.IsPredictionResistant
+ {
+ get { return mPredictionResistant; }
+ }
+
+ byte[] IEntropySource.GetEntropy()
+ {
+ byte[] result = new byte[(mEntropySize + 7) / 8];
+ mRng.GetBytes(result);
+ return result;
+ }
+
+ int IEntropySource.EntropySize
+ {
+ get { return mEntropySize; }
+ }
+
+ #endregion
+ }
+ }
+}
+
+#endif
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/CryptoApiEntropySourceProvider.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/CryptoApiEntropySourceProvider.cs.meta
new file mode 100644
index 00000000..785dec23
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/CryptoApiEntropySourceProvider.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 25ec2a0632ecc8449b1d88c41c111fe2
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/CryptoApiRandomGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/CryptoApiRandomGenerator.cs
new file mode 100644
index 00000000..16366c52
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/CryptoApiRandomGenerator.cs
@@ -0,0 +1,70 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+#if !(NETCF_1_0 || PORTABLE || NETFX_CORE)
+
+using System;
+using System.Security.Cryptography;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng
+{
+ ///
+ /// Uses RandomNumberGenerator.Create() to get randomness generator
+ ///
+ public class CryptoApiRandomGenerator
+ : IRandomGenerator
+ {
+ private readonly RandomNumberGenerator rndProv;
+
+ public CryptoApiRandomGenerator()
+ : this(RandomNumberGenerator.Create())
+ {
+ }
+
+ public CryptoApiRandomGenerator(RandomNumberGenerator rng)
+ {
+ this.rndProv = rng;
+ }
+
+ #region IRandomGenerator Members
+
+ public virtual void AddSeedMaterial(byte[] seed)
+ {
+ // We don't care about the seed
+ }
+
+ public virtual void AddSeedMaterial(long seed)
+ {
+ // We don't care about the seed
+ }
+
+ public virtual void NextBytes(byte[] bytes)
+ {
+ rndProv.GetBytes(bytes);
+ }
+
+ public virtual void NextBytes(byte[] bytes, int start, int len)
+ {
+ if (start < 0)
+ throw new ArgumentException("Start offset cannot be negative", "start");
+ if (bytes.Length < (start + len))
+ throw new ArgumentException("Byte array too small for requested offset and length");
+
+ if (bytes.Length == len && start == 0)
+ {
+ NextBytes(bytes);
+ }
+ else
+ {
+ byte[] tmpBuf = new byte[len];
+ NextBytes(tmpBuf);
+ Array.Copy(tmpBuf, 0, bytes, start, len);
+ }
+ }
+
+ #endregion
+ }
+}
+
+#endif
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/CryptoApiRandomGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/CryptoApiRandomGenerator.cs.meta
new file mode 100644
index 00000000..74923c7c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/CryptoApiRandomGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ccbe3ba15c23a8a4d94f9d684f23a748
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/DigestRandomGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/DigestRandomGenerator.cs
new file mode 100644
index 00000000..5c3e5780
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/DigestRandomGenerator.cs
@@ -0,0 +1,131 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng
+{
+ /**
+ * Random generation based on the digest with counter. Calling AddSeedMaterial will
+ * always increase the entropy of the hash.
+ *
+ * Internal access to the digest is synchronized so a single one of these can be shared.
+ *
+ */
+ public class DigestRandomGenerator
+ : IRandomGenerator
+ {
+ private const long CYCLE_COUNT = 10;
+
+ private long stateCounter;
+ private long seedCounter;
+ private IDigest digest;
+ private byte[] state;
+ private byte[] seed;
+
+ public DigestRandomGenerator(
+ IDigest digest)
+ {
+ this.digest = digest;
+
+ this.seed = new byte[digest.GetDigestSize()];
+ this.seedCounter = 1;
+
+ this.state = new byte[digest.GetDigestSize()];
+ this.stateCounter = 1;
+ }
+
+ public void AddSeedMaterial(
+ byte[] inSeed)
+ {
+ lock (this)
+ {
+ DigestUpdate(inSeed);
+ DigestUpdate(seed);
+ DigestDoFinal(seed);
+ }
+ }
+
+ public void AddSeedMaterial(
+ long rSeed)
+ {
+ lock (this)
+ {
+ DigestAddCounter(rSeed);
+ DigestUpdate(seed);
+ DigestDoFinal(seed);
+ }
+ }
+
+ public void NextBytes(
+ byte[] bytes)
+ {
+ NextBytes(bytes, 0, bytes.Length);
+ }
+
+ public void NextBytes(
+ byte[] bytes,
+ int start,
+ int len)
+ {
+ lock (this)
+ {
+ int stateOff = 0;
+
+ GenerateState();
+
+ int end = start + len;
+ for (int i = start; i < end; ++i)
+ {
+ if (stateOff == state.Length)
+ {
+ GenerateState();
+ stateOff = 0;
+ }
+ bytes[i] = state[stateOff++];
+ }
+ }
+ }
+
+ private void CycleSeed()
+ {
+ DigestUpdate(seed);
+ DigestAddCounter(seedCounter++);
+ DigestDoFinal(seed);
+ }
+
+ private void GenerateState()
+ {
+ DigestAddCounter(stateCounter++);
+ DigestUpdate(state);
+ DigestUpdate(seed);
+ DigestDoFinal(state);
+
+ if ((stateCounter % CYCLE_COUNT) == 0)
+ {
+ CycleSeed();
+ }
+ }
+
+ private void DigestAddCounter(long seedVal)
+ {
+ byte[] bytes = new byte[8];
+ Pack.UInt64_To_LE((ulong)seedVal, bytes);
+ digest.BlockUpdate(bytes, 0, bytes.Length);
+ }
+
+ private void DigestUpdate(byte[] inSeed)
+ {
+ digest.BlockUpdate(inSeed, 0, inSeed.Length);
+ }
+
+ private void DigestDoFinal(byte[] result)
+ {
+ digest.DoFinal(result, 0);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/DigestRandomGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/DigestRandomGenerator.cs.meta
new file mode 100644
index 00000000..41699862
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/DigestRandomGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 7979612bf0f2722478158ecadb846f1d
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/EntropyUtilities.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/EntropyUtilities.cs
new file mode 100644
index 00000000..a0818027
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/EntropyUtilities.cs
@@ -0,0 +1,34 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng
+{
+ public abstract class EntropyUtilities
+ {
+ /**
+ * Generate numBytes worth of entropy from the passed in entropy source.
+ *
+ * @param entropySource the entropy source to request the data from.
+ * @param numBytes the number of bytes of entropy requested.
+ * @return a byte array populated with the random data.
+ */
+ public static byte[] GenerateSeed(IEntropySource entropySource, int numBytes)
+ {
+ byte[] bytes = new byte[numBytes];
+ int count = 0;
+ while (count < numBytes)
+ {
+ byte[] entropy = entropySource.GetEntropy();
+ int toCopy = System.Math.Min(bytes.Length, numBytes - count);
+ Array.Copy(entropy, 0, bytes, count, toCopy);
+ count += toCopy;
+ }
+ return bytes;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/EntropyUtilities.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/EntropyUtilities.cs.meta
new file mode 100644
index 00000000..862ddfdc
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/EntropyUtilities.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 49e236d42630bab4fa9185520ecc86be
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/IDrbgProvider.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/IDrbgProvider.cs
new file mode 100644
index 00000000..1f05d88c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/IDrbgProvider.cs
@@ -0,0 +1,15 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng.Drbg;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng
+{
+ internal interface IDrbgProvider
+ {
+ ISP80090Drbg Get(IEntropySource entropySource);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/IDrbgProvider.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/IDrbgProvider.cs.meta
new file mode 100644
index 00000000..0f39ba86
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/IDrbgProvider.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: d4a6b6d841dbe6e4d9b5e05bbb356b42
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/IRandomGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/IRandomGenerator.cs
new file mode 100644
index 00000000..ebc5cbd6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/IRandomGenerator.cs
@@ -0,0 +1,30 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng
+{
+ /// Generic interface for objects generating random bytes.
+ public interface IRandomGenerator
+ {
+ /// Add more seed material to the generator.
+ /// A byte array to be mixed into the generator's state.
+ void AddSeedMaterial(byte[] seed);
+
+ /// Add more seed material to the generator.
+ /// A long value to be mixed into the generator's state.
+ void AddSeedMaterial(long seed);
+
+ /// Fill byte array with random values.
+ /// Array to be filled.
+ void NextBytes(byte[] bytes);
+
+ /// Fill byte array with random values.
+ /// Array to receive bytes.
+ /// Index to start filling at.
+ /// Length of segment to fill.
+ void NextBytes(byte[] bytes, int start, int len);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/IRandomGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/IRandomGenerator.cs.meta
new file mode 100644
index 00000000..49efec88
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/IRandomGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 4455377f4c3b6cf4fb000aca48c08ab8
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/ReversedWindowGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/ReversedWindowGenerator.cs
new file mode 100644
index 00000000..02e092e4
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/ReversedWindowGenerator.cs
@@ -0,0 +1,102 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng
+{
+ ///
+ /// Takes bytes generated by an underling RandomGenerator and reverses the order in
+ /// each small window (of configurable size).
+ ///
+ /// Access to internals is synchronized so a single one of these can be shared.
+ ///
+ ///
+ public class ReversedWindowGenerator
+ : IRandomGenerator
+ {
+ private readonly IRandomGenerator generator;
+
+ private byte[] window;
+ private int windowCount;
+
+ public ReversedWindowGenerator(
+ IRandomGenerator generator,
+ int windowSize)
+ {
+ if (generator == null)
+ throw new ArgumentNullException("generator");
+ if (windowSize < 2)
+ throw new ArgumentException("Window size must be at least 2", "windowSize");
+
+ this.generator = generator;
+ this.window = new byte[windowSize];
+ }
+
+ /// Add more seed material to the generator.
+ /// A byte array to be mixed into the generator's state.
+ public virtual void AddSeedMaterial(
+ byte[] seed)
+ {
+ lock (this)
+ {
+ windowCount = 0;
+ generator.AddSeedMaterial(seed);
+ }
+ }
+
+ /// Add more seed material to the generator.
+ /// A long value to be mixed into the generator's state.
+ public virtual void AddSeedMaterial(
+ long seed)
+ {
+ lock (this)
+ {
+ windowCount = 0;
+ generator.AddSeedMaterial(seed);
+ }
+ }
+
+ /// Fill byte array with random values.
+ /// Array to be filled.
+ public virtual void NextBytes(
+ byte[] bytes)
+ {
+ doNextBytes(bytes, 0, bytes.Length);
+ }
+
+ /// Fill byte array with random values.
+ /// Array to receive bytes.
+ /// Index to start filling at.
+ /// Length of segment to fill.
+ public virtual void NextBytes(
+ byte[] bytes,
+ int start,
+ int len)
+ {
+ doNextBytes(bytes, start, len);
+ }
+
+ private void doNextBytes(
+ byte[] bytes,
+ int start,
+ int len)
+ {
+ lock (this)
+ {
+ int done = 0;
+ while (done < len)
+ {
+ if (windowCount < 1)
+ {
+ generator.NextBytes(window, 0, window.Length);
+ windowCount = window.Length;
+ }
+
+ bytes[start + done++] = window[--windowCount];
+ }
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/ReversedWindowGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/ReversedWindowGenerator.cs.meta
new file mode 100644
index 00000000..659a1ced
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/ReversedWindowGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 9c9b45d1f0973ac4a9db88250e6d0ebb
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/SP800SecureRandom.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/SP800SecureRandom.cs
new file mode 100644
index 00000000..a2e4d3ad
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/SP800SecureRandom.cs
@@ -0,0 +1,99 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng.Drbg;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng
+{
+ public class SP800SecureRandom
+ : SecureRandom
+ {
+ private readonly IDrbgProvider mDrbgProvider;
+ private readonly bool mPredictionResistant;
+ private readonly SecureRandom mRandomSource;
+ private readonly IEntropySource mEntropySource;
+
+ private ISP80090Drbg mDrbg;
+
+ internal SP800SecureRandom(SecureRandom randomSource, IEntropySource entropySource, IDrbgProvider drbgProvider, bool predictionResistant)
+ : base((IRandomGenerator)null)
+ {
+ this.mRandomSource = randomSource;
+ this.mEntropySource = entropySource;
+ this.mDrbgProvider = drbgProvider;
+ this.mPredictionResistant = predictionResistant;
+ }
+
+ public override void SetSeed(byte[] seed)
+ {
+ lock (this)
+ {
+ if (mRandomSource != null)
+ {
+ this.mRandomSource.SetSeed(seed);
+ }
+ }
+ }
+
+ public override void SetSeed(long seed)
+ {
+ lock (this)
+ {
+ // this will happen when SecureRandom() is created
+ if (mRandomSource != null)
+ {
+ this.mRandomSource.SetSeed(seed);
+ }
+ }
+ }
+
+ public override void NextBytes(byte[] bytes)
+ {
+ lock (this)
+ {
+ if (mDrbg == null)
+ {
+ mDrbg = mDrbgProvider.Get(mEntropySource);
+ }
+
+ // check if a reseed is required...
+ if (mDrbg.Generate(bytes, null, mPredictionResistant) < 0)
+ {
+ mDrbg.Reseed(null);
+ mDrbg.Generate(bytes, null, mPredictionResistant);
+ }
+ }
+ }
+
+ public override void NextBytes(byte[] buf, int off, int len)
+ {
+ byte[] bytes = new byte[len];
+ NextBytes(bytes);
+ Array.Copy(bytes, 0, buf, off, len);
+ }
+
+ public override byte[] GenerateSeed(int numBytes)
+ {
+ return EntropyUtilities.GenerateSeed(mEntropySource, numBytes);
+ }
+
+ /// Force a reseed of the DRBG.
+ /// optional additional input
+ public virtual void Reseed(byte[] additionalInput)
+ {
+ lock (this)
+ {
+ if (mDrbg == null)
+ {
+ mDrbg = mDrbgProvider.Get(mEntropySource);
+ }
+
+ mDrbg.Reseed(additionalInput);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/SP800SecureRandom.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/SP800SecureRandom.cs.meta
new file mode 100644
index 00000000..c0ad78a7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/SP800SecureRandom.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 065a9c94a09b9e14faf04e78e06d355c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/SP800SecureRandomBuilder.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/SP800SecureRandomBuilder.cs
new file mode 100644
index 00000000..c7c9179e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/SP800SecureRandomBuilder.cs
@@ -0,0 +1,212 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng.Drbg;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng
+{
+ /**
+ * Builder class for making SecureRandom objects based on SP 800-90A Deterministic Random Bit Generators (DRBG).
+ */
+ public class SP800SecureRandomBuilder
+ {
+ private readonly SecureRandom mRandom;
+ private readonly IEntropySourceProvider mEntropySourceProvider;
+
+ private byte[] mPersonalizationString = null;
+ private int mSecurityStrength = 256;
+ private int mEntropyBitsRequired = 256;
+
+ /**
+ * Basic constructor, creates a builder using an EntropySourceProvider based on the default SecureRandom with
+ * predictionResistant set to false.
+ *
+ * Any SecureRandom created from a builder constructed like this will make use of input passed to SecureRandom.setSeed() if
+ * the default SecureRandom does for its generateSeed() call.
+ *
+ */
+ public SP800SecureRandomBuilder()
+ : this(new SecureRandom(), false)
+ {
+ }
+
+ /**
+ * Construct a builder with an EntropySourceProvider based on the passed in SecureRandom and the passed in value
+ * for prediction resistance.
+ *
+ * Any SecureRandom created from a builder constructed like this will make use of input passed to SecureRandom.setSeed() if
+ * the passed in SecureRandom does for its generateSeed() call.
+ *
+ * @param entropySource
+ * @param predictionResistant
+ */
+ public SP800SecureRandomBuilder(SecureRandom entropySource, bool predictionResistant)
+ {
+ this.mRandom = entropySource;
+ this.mEntropySourceProvider = new BasicEntropySourceProvider(entropySource, predictionResistant);
+ }
+
+ /**
+ * Create a builder which makes creates the SecureRandom objects from a specified entropy source provider.
+ *
+ * Note: If this constructor is used any calls to setSeed() in the resulting SecureRandom will be ignored.
+ *
+ * @param entropySourceProvider a provider of EntropySource objects.
+ */
+ public SP800SecureRandomBuilder(IEntropySourceProvider entropySourceProvider)
+ {
+ this.mRandom = null;
+ this.mEntropySourceProvider = entropySourceProvider;
+ }
+
+ /**
+ * Set the personalization string for DRBG SecureRandoms created by this builder
+ * @param personalizationString the personalisation string for the underlying DRBG.
+ * @return the current builder.
+ */
+ public SP800SecureRandomBuilder SetPersonalizationString(byte[] personalizationString)
+ {
+ this.mPersonalizationString = personalizationString;
+ return this;
+ }
+
+ /**
+ * Set the security strength required for DRBGs used in building SecureRandom objects.
+ *
+ * @param securityStrength the security strength (in bits)
+ * @return the current builder.
+ */
+ public SP800SecureRandomBuilder SetSecurityStrength(int securityStrength)
+ {
+ this.mSecurityStrength = securityStrength;
+ return this;
+ }
+
+ /**
+ * Set the amount of entropy bits required for seeding and reseeding DRBGs used in building SecureRandom objects.
+ *
+ * @param entropyBitsRequired the number of bits of entropy to be requested from the entropy source on each seed/reseed.
+ * @return the current builder.
+ */
+ public SP800SecureRandomBuilder SetEntropyBitsRequired(int entropyBitsRequired)
+ {
+ this.mEntropyBitsRequired = entropyBitsRequired;
+ return this;
+ }
+
+ /**
+ * Build a SecureRandom based on a SP 800-90A Hash DRBG.
+ *
+ * @param digest digest algorithm to use in the DRBG underneath the SecureRandom.
+ * @param nonce nonce value to use in DRBG construction.
+ * @param predictionResistant specify whether the underlying DRBG in the resulting SecureRandom should reseed on each request for bytes.
+ * @return a SecureRandom supported by a Hash DRBG.
+ */
+ public SP800SecureRandom BuildHash(IDigest digest, byte[] nonce, bool predictionResistant)
+ {
+ return new SP800SecureRandom(mRandom, mEntropySourceProvider.Get(mEntropyBitsRequired),
+ new HashDrbgProvider(digest, nonce, mPersonalizationString, mSecurityStrength), predictionResistant);
+ }
+
+ /**
+ * Build a SecureRandom based on a SP 800-90A CTR DRBG.
+ *
+ * @param cipher the block cipher to base the DRBG on.
+ * @param keySizeInBits key size in bits to be used with the block cipher.
+ * @param nonce nonce value to use in DRBG construction.
+ * @param predictionResistant specify whether the underlying DRBG in the resulting SecureRandom should reseed on each request for bytes.
+ * @return a SecureRandom supported by a CTR DRBG.
+ */
+ public SP800SecureRandom BuildCtr(IBlockCipher cipher, int keySizeInBits, byte[] nonce, bool predictionResistant)
+ {
+ return new SP800SecureRandom(mRandom, mEntropySourceProvider.Get(mEntropyBitsRequired),
+ new CtrDrbgProvider(cipher, keySizeInBits, nonce, mPersonalizationString, mSecurityStrength), predictionResistant);
+ }
+
+ /**
+ * Build a SecureRandom based on a SP 800-90A HMAC DRBG.
+ *
+ * @param hMac HMAC algorithm to use in the DRBG underneath the SecureRandom.
+ * @param nonce nonce value to use in DRBG construction.
+ * @param predictionResistant specify whether the underlying DRBG in the resulting SecureRandom should reseed on each request for bytes.
+ * @return a SecureRandom supported by a HMAC DRBG.
+ */
+ public SP800SecureRandom BuildHMac(IMac hMac, byte[] nonce, bool predictionResistant)
+ {
+ return new SP800SecureRandom(mRandom, mEntropySourceProvider.Get(mEntropyBitsRequired),
+ new HMacDrbgProvider(hMac, nonce, mPersonalizationString, mSecurityStrength), predictionResistant);
+ }
+
+ private class HashDrbgProvider
+ : IDrbgProvider
+ {
+ private readonly IDigest mDigest;
+ private readonly byte[] mNonce;
+ private readonly byte[] mPersonalizationString;
+ private readonly int mSecurityStrength;
+
+ public HashDrbgProvider(IDigest digest, byte[] nonce, byte[] personalizationString, int securityStrength)
+ {
+ this.mDigest = digest;
+ this.mNonce = nonce;
+ this.mPersonalizationString = personalizationString;
+ this.mSecurityStrength = securityStrength;
+ }
+
+ public ISP80090Drbg Get(IEntropySource entropySource)
+ {
+ return new HashSP800Drbg(mDigest, mSecurityStrength, entropySource, mPersonalizationString, mNonce);
+ }
+ }
+
+ private class HMacDrbgProvider
+ : IDrbgProvider
+ {
+ private readonly IMac mHMac;
+ private readonly byte[] mNonce;
+ private readonly byte[] mPersonalizationString;
+ private readonly int mSecurityStrength;
+
+ public HMacDrbgProvider(IMac hMac, byte[] nonce, byte[] personalizationString, int securityStrength)
+ {
+ this.mHMac = hMac;
+ this.mNonce = nonce;
+ this.mPersonalizationString = personalizationString;
+ this.mSecurityStrength = securityStrength;
+ }
+
+ public ISP80090Drbg Get(IEntropySource entropySource)
+ {
+ return new HMacSP800Drbg(mHMac, mSecurityStrength, entropySource, mPersonalizationString, mNonce);
+ }
+ }
+
+ private class CtrDrbgProvider
+ : IDrbgProvider
+ {
+ private readonly IBlockCipher mBlockCipher;
+ private readonly int mKeySizeInBits;
+ private readonly byte[] mNonce;
+ private readonly byte[] mPersonalizationString;
+ private readonly int mSecurityStrength;
+
+ public CtrDrbgProvider(IBlockCipher blockCipher, int keySizeInBits, byte[] nonce, byte[] personalizationString, int securityStrength)
+ {
+ this.mBlockCipher = blockCipher;
+ this.mKeySizeInBits = keySizeInBits;
+ this.mNonce = nonce;
+ this.mPersonalizationString = personalizationString;
+ this.mSecurityStrength = securityStrength;
+ }
+
+ public ISP80090Drbg Get(IEntropySource entropySource)
+ {
+ return new CtrSP800Drbg(mBlockCipher, mKeySizeInBits, mSecurityStrength, entropySource, mPersonalizationString, mNonce);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/SP800SecureRandomBuilder.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/SP800SecureRandomBuilder.cs.meta
new file mode 100644
index 00000000..708e82b5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/SP800SecureRandomBuilder.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c0226b1743b2ec34a8fdaf4c0c3017eb
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/ThreadedSeedGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/ThreadedSeedGenerator.cs
new file mode 100644
index 00000000..cc5330f6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/ThreadedSeedGenerator.cs
@@ -0,0 +1,148 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Threading;
+
+#if NO_THREADS || NETFX_CORE
+using System.Threading.Tasks;
+#endif
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng
+{
+ /**
+ * A thread based seed generator - one source of randomness.
+ *
+ * If fast is set to true, the code should be round about 8 times faster when
+ * generating a long sequence of random bytes. 20 bytes of random values using
+ * the fast mode take less than half a second on a Nokia e70. If fast is set to false,
+ * it takes round about 2500 ms.
+ *
+ * Any SecureRandom created from a builder constructed like this will make use of input passed to SecureRandom.setSeed() if
+ * the default SecureRandom does for its generateSeed() call.
+ *
+ */
+ public X931SecureRandomBuilder()
+ : this(new SecureRandom(), false)
+ {
+ }
+
+ /**
+ * Construct a builder with an EntropySourceProvider based on the passed in SecureRandom and the passed in value
+ * for prediction resistance.
+ *
+ * Any SecureRandom created from a builder constructed like this will make use of input passed to SecureRandom.setSeed() if
+ * the passed in SecureRandom does for its generateSeed() call.
+ *
+ * @param entropySource
+ * @param predictionResistant
+ */
+ public X931SecureRandomBuilder(SecureRandom entropySource, bool predictionResistant)
+ {
+ this.mRandom = entropySource;
+ this.mEntropySourceProvider = new BasicEntropySourceProvider(mRandom, predictionResistant);
+ }
+
+ /**
+ * Create a builder which makes creates the SecureRandom objects from a specified entropy source provider.
+ *
+ * Note: If this constructor is used any calls to setSeed() in the resulting SecureRandom will be ignored.
+ *
+ * @param entropySourceProvider a provider of EntropySource objects.
+ */
+ public X931SecureRandomBuilder(IEntropySourceProvider entropySourceProvider)
+ {
+ this.mRandom = null;
+ this.mEntropySourceProvider = entropySourceProvider;
+ }
+
+ public X931SecureRandomBuilder SetDateTimeVector(byte[] dateTimeVector)
+ {
+ this.mDateTimeVector = dateTimeVector;
+ return this;
+ }
+
+ /**
+ * Construct a X9.31 secure random generator using the passed in engine and key. If predictionResistant is true the
+ * generator will be reseeded on each request.
+ *
+ * @param engine a block cipher to use as the operator.
+ * @param key the block cipher key to initialise engine with.
+ * @param predictionResistant true if engine to be reseeded on each use, false otherwise.
+ * @return a SecureRandom.
+ */
+ public X931SecureRandom Build(IBlockCipher engine, KeyParameter key, bool predictionResistant)
+ {
+ if (mDateTimeVector == null)
+ {
+ mDateTimeVector = new byte[engine.GetBlockSize()];
+ Pack.UInt64_To_BE((ulong)DateTimeUtilities.CurrentUnixMs(), mDateTimeVector, 0);
+ }
+
+ engine.Init(true, key);
+
+ return new X931SecureRandom(mRandom, new X931Rng(engine, mDateTimeVector, mEntropySourceProvider.Get(engine.GetBlockSize() * 8)), predictionResistant);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/X931SecureRandomBuilder.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/X931SecureRandomBuilder.cs.meta
new file mode 100644
index 00000000..6fcb782b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/X931SecureRandomBuilder.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: fa412f39ca843ca4db9e5b10bc4a12d4
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg.meta
new file mode 100644
index 00000000..ff40ee10
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: af63aec738a072a448eee5c48d43e9f8
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/CtrSP800Drbg.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/CtrSP800Drbg.cs
new file mode 100644
index 00000000..4dcab6e1
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/CtrSP800Drbg.cs
@@ -0,0 +1,470 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng.Drbg
+{
+ /**
+ * A SP800-90A CTR DRBG.
+ */
+ public class CtrSP800Drbg
+ : ISP80090Drbg
+ {
+ private static readonly long TDEA_RESEED_MAX = 1L << (32 - 1);
+ private static readonly long AES_RESEED_MAX = 1L << (48 - 1);
+ private static readonly int TDEA_MAX_BITS_REQUEST = 1 << (13 - 1);
+ private static readonly int AES_MAX_BITS_REQUEST = 1 << (19 - 1);
+
+ private readonly IEntropySource mEntropySource;
+ private readonly IBlockCipher mEngine;
+ private readonly int mKeySizeInBits;
+ private readonly int mSeedLength;
+ private readonly int mSecurityStrength;
+
+ // internal state
+ private byte[] mKey;
+ private byte[] mV;
+ private long mReseedCounter = 0;
+ private bool mIsTdea = false;
+
+ /**
+ * Construct a SP800-90A CTR DRBG.
+ *
+ * Minimum entropy requirement is the security strength requested.
+ *
+ * @param engine underlying block cipher to use to support DRBG
+ * @param keySizeInBits size of the key to use with the block cipher.
+ * @param securityStrength security strength required (in bits)
+ * @param entropySource source of entropy to use for seeding/reseeding.
+ * @param personalizationString personalization string to distinguish this DRBG (may be null).
+ * @param nonce nonce to further distinguish this DRBG (may be null).
+ */
+ public CtrSP800Drbg(IBlockCipher engine, int keySizeInBits, int securityStrength, IEntropySource entropySource,
+ byte[] personalizationString, byte[] nonce)
+ {
+ if (securityStrength > 256)
+ throw new ArgumentException("Requested security strength is not supported by the derivation function");
+ if (GetMaxSecurityStrength(engine, keySizeInBits) < securityStrength)
+ throw new ArgumentException("Requested security strength is not supported by block cipher and key size");
+ if (entropySource.EntropySize < securityStrength)
+ throw new ArgumentException("Not enough entropy for security strength required");
+
+ mEntropySource = entropySource;
+ mEngine = engine;
+
+ mKeySizeInBits = keySizeInBits;
+ mSecurityStrength = securityStrength;
+ mSeedLength = keySizeInBits + engine.GetBlockSize() * 8;
+ mIsTdea = IsTdea(engine);
+
+ byte[] entropy = GetEntropy(); // Get_entropy_input
+
+ CTR_DRBG_Instantiate_algorithm(entropy, nonce, personalizationString);
+ }
+
+ private void CTR_DRBG_Instantiate_algorithm(byte[] entropy, byte[] nonce, byte[] personalisationString)
+ {
+ byte[] seedMaterial = Arrays.ConcatenateAll(entropy, nonce, personalisationString);
+ byte[] seed = Block_Cipher_df(seedMaterial, mSeedLength);
+
+ int outlen = mEngine.GetBlockSize();
+
+ mKey = new byte[(mKeySizeInBits + 7) / 8];
+ mV = new byte[outlen];
+
+ // mKey & mV are modified by this call
+ CTR_DRBG_Update(seed, mKey, mV);
+
+ mReseedCounter = 1;
+ }
+
+ private void CTR_DRBG_Update(byte[] seed, byte[] key, byte[] v)
+ {
+ byte[] temp = new byte[seed.Length];
+ byte[] outputBlock = new byte[mEngine.GetBlockSize()];
+
+ int i = 0;
+ int outLen = mEngine.GetBlockSize();
+
+ mEngine.Init(true, new KeyParameter(ExpandKey(key)));
+ while (i*outLen < seed.Length)
+ {
+ AddOneTo(v);
+ mEngine.ProcessBlock(v, 0, outputBlock, 0);
+
+ int bytesToCopy = ((temp.Length - i * outLen) > outLen)
+ ? outLen : (temp.Length - i * outLen);
+
+ Array.Copy(outputBlock, 0, temp, i * outLen, bytesToCopy);
+ ++i;
+ }
+
+ XOR(temp, seed, temp, 0);
+
+ Array.Copy(temp, 0, key, 0, key.Length);
+ Array.Copy(temp, key.Length, v, 0, v.Length);
+ }
+
+ private void CTR_DRBG_Reseed_algorithm(byte[] additionalInput)
+ {
+ byte[] seedMaterial = Arrays.Concatenate(GetEntropy(), additionalInput);
+
+ seedMaterial = Block_Cipher_df(seedMaterial, mSeedLength);
+
+ CTR_DRBG_Update(seedMaterial, mKey, mV);
+
+ mReseedCounter = 1;
+ }
+
+ private void XOR(byte[] output, byte[] a, byte[] b, int bOff)
+ {
+ for (int i = 0; i < output.Length; i++)
+ {
+ output[i] = (byte)(a[i] ^ b[bOff + i]);
+ }
+ }
+
+ private void AddOneTo(byte[] longer)
+ {
+ uint carry = 1;
+ int i = longer.Length;
+ while (--i >= 0)
+ {
+ carry += longer[i];
+ longer[i] = (byte)carry;
+ carry >>= 8;
+ }
+ }
+
+ private byte[] GetEntropy()
+ {
+ byte[] entropy = mEntropySource.GetEntropy();
+ if (entropy.Length < (mSecurityStrength + 7) / 8)
+ throw new InvalidOperationException("Insufficient entropy provided by entropy source");
+ return entropy;
+ }
+
+ // -- Internal state migration ---
+
+ private static readonly byte[] K_BITS = Hex.Decode("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F");
+
+ // 1. If (number_of_bits_to_return > max_number_of_bits), then return an
+ // ERROR_FLAG.
+ // 2. L = len (input_string)/8.
+ // 3. N = number_of_bits_to_return/8.
+ // Comment: L is the bitstring represention of
+ // the integer resulting from len (input_string)/8.
+ // L shall be represented as a 32-bit integer.
+ //
+ // Comment : N is the bitstring represention of
+ // the integer resulting from
+ // number_of_bits_to_return/8. N shall be
+ // represented as a 32-bit integer.
+ //
+ // 4. S = L || N || input_string || 0x80.
+ // 5. While (len (S) mod outlen)
+ // Comment : Pad S with zeros, if necessary.
+ // 0, S = S || 0x00.
+ //
+ // Comment : Compute the starting value.
+ // 6. temp = the Null string.
+ // 7. i = 0.
+ // 8. K = Leftmost keylen bits of 0x00010203...1D1E1F.
+ // 9. While len (temp) < keylen + outlen, do
+ //
+ // IV = i || 0outlen - len (i).
+ //
+ // 9.1
+ //
+ // temp = temp || BCC (K, (IV || S)).
+ //
+ // 9.2
+ //
+ // i = i + 1.
+ //
+ // 9.3
+ //
+ // Comment : i shall be represented as a 32-bit
+ // integer, i.e., len (i) = 32.
+ //
+ // Comment: The 32-bit integer represenation of
+ // i is padded with zeros to outlen bits.
+ //
+ // Comment: Compute the requested number of
+ // bits.
+ //
+ // 10. K = Leftmost keylen bits of temp.
+ //
+ // 11. X = Next outlen bits of temp.
+ //
+ // 12. temp = the Null string.
+ //
+ // 13. While len (temp) < number_of_bits_to_return, do
+ //
+ // 13.1 X = Block_Encrypt (K, X).
+ //
+ // 13.2 temp = temp || X.
+ //
+ // 14. requested_bits = Leftmost number_of_bits_to_return of temp.
+ //
+ // 15. Return SUCCESS and requested_bits.
+ private byte[] Block_Cipher_df(byte[] inputString, int bitLength)
+ {
+ int outLen = mEngine.GetBlockSize();
+ int L = inputString.Length; // already in bytes
+ int N = bitLength / 8;
+ // 4 S = L || N || inputstring || 0x80
+ int sLen = 4 + 4 + L + 1;
+ int blockLen = ((sLen + outLen - 1) / outLen) * outLen;
+ byte[] S = new byte[blockLen];
+ copyIntToByteArray(S, L, 0);
+ copyIntToByteArray(S, N, 4);
+ Array.Copy(inputString, 0, S, 8, L);
+ S[8 + L] = (byte)0x80;
+ // S already padded with zeros
+
+ byte[] temp = new byte[mKeySizeInBits / 8 + outLen];
+ byte[] bccOut = new byte[outLen];
+
+ byte[] IV = new byte[outLen];
+
+ int i = 0;
+ byte[] K = new byte[mKeySizeInBits / 8];
+ Array.Copy(K_BITS, 0, K, 0, K.Length);
+
+ while (i*outLen*8 < mKeySizeInBits + outLen *8)
+ {
+ copyIntToByteArray(IV, i, 0);
+ BCC(bccOut, K, IV, S);
+
+ int bytesToCopy = ((temp.Length - i * outLen) > outLen)
+ ? outLen
+ : (temp.Length - i * outLen);
+
+ Array.Copy(bccOut, 0, temp, i * outLen, bytesToCopy);
+ ++i;
+ }
+
+ byte[] X = new byte[outLen];
+ Array.Copy(temp, 0, K, 0, K.Length);
+ Array.Copy(temp, K.Length, X, 0, X.Length);
+
+ temp = new byte[bitLength / 2];
+
+ i = 0;
+ mEngine.Init(true, new KeyParameter(ExpandKey(K)));
+
+ while (i * outLen < temp.Length)
+ {
+ mEngine.ProcessBlock(X, 0, X, 0);
+
+ int bytesToCopy = ((temp.Length - i * outLen) > outLen)
+ ? outLen
+ : (temp.Length - i * outLen);
+
+ Array.Copy(X, 0, temp, i * outLen, bytesToCopy);
+ i++;
+ }
+
+ return temp;
+ }
+
+ /*
+ * 1. chaining_value = 0^outlen
+ * . Comment: Set the first chaining value to outlen zeros.
+ * 2. n = len (data)/outlen.
+ * 3. Starting with the leftmost bits of data, split the data into n blocks of outlen bits
+ * each, forming block(1) to block(n).
+ * 4. For i = 1 to n do
+ * 4.1 input_block = chaining_value ^ block(i) .
+ * 4.2 chaining_value = Block_Encrypt (Key, input_block).
+ * 5. output_block = chaining_value.
+ * 6. Return output_block.
+ */
+ private void BCC(byte[] bccOut, byte[] k, byte[] iV, byte[] data)
+ {
+ int outlen = mEngine.GetBlockSize();
+ byte[] chainingValue = new byte[outlen]; // initial values = 0
+ int n = data.Length / outlen;
+
+ byte[] inputBlock = new byte[outlen];
+
+ mEngine.Init(true, new KeyParameter(ExpandKey(k)));
+
+ mEngine.ProcessBlock(iV, 0, chainingValue, 0);
+
+ for (int i = 0; i < n; i++)
+ {
+ XOR(inputBlock, chainingValue, data, i*outlen);
+ mEngine.ProcessBlock(inputBlock, 0, chainingValue, 0);
+ }
+
+ Array.Copy(chainingValue, 0, bccOut, 0, bccOut.Length);
+ }
+
+ private void copyIntToByteArray(byte[] buf, int value, int offSet)
+ {
+ buf[offSet + 0] = ((byte)(value >> 24));
+ buf[offSet + 1] = ((byte)(value >> 16));
+ buf[offSet + 2] = ((byte)(value >> 8));
+ buf[offSet + 3] = ((byte)(value));
+ }
+
+ /**
+ * Return the block size (in bits) of the DRBG.
+ *
+ * @return the number of bits produced on each internal round of the DRBG.
+ */
+ public int BlockSize
+ {
+ get { return mV.Length * 8; }
+ }
+
+ /**
+ * Populate a passed in array with random data.
+ *
+ * @param output output array for generated bits.
+ * @param additionalInput additional input to be added to the DRBG in this step.
+ * @param predictionResistant true if a reseed should be forced, false otherwise.
+ *
+ * @return number of bits generated, -1 if a reseed required.
+ */
+ public int Generate(byte[] output, byte[] additionalInput, bool predictionResistant)
+ {
+ if (mIsTdea)
+ {
+ if (mReseedCounter > TDEA_RESEED_MAX)
+ return -1;
+
+ if (DrbgUtilities.IsTooLarge(output, TDEA_MAX_BITS_REQUEST / 8))
+ throw new ArgumentException("Number of bits per request limited to " + TDEA_MAX_BITS_REQUEST, "output");
+ }
+ else
+ {
+ if (mReseedCounter > AES_RESEED_MAX)
+ return -1;
+
+ if (DrbgUtilities.IsTooLarge(output, AES_MAX_BITS_REQUEST / 8))
+ throw new ArgumentException("Number of bits per request limited to " + AES_MAX_BITS_REQUEST, "output");
+ }
+
+ if (predictionResistant)
+ {
+ CTR_DRBG_Reseed_algorithm(additionalInput);
+ additionalInput = null;
+ }
+
+ if (additionalInput != null)
+ {
+ additionalInput = Block_Cipher_df(additionalInput, mSeedLength);
+ CTR_DRBG_Update(additionalInput, mKey, mV);
+ }
+ else
+ {
+ additionalInput = new byte[mSeedLength];
+ }
+
+ byte[] tmp = new byte[mV.Length];
+
+ mEngine.Init(true, new KeyParameter(ExpandKey(mKey)));
+
+ for (int i = 0; i <= output.Length / tmp.Length; i++)
+ {
+ int bytesToCopy = ((output.Length - i * tmp.Length) > tmp.Length)
+ ? tmp.Length
+ : (output.Length - i * mV.Length);
+
+ if (bytesToCopy != 0)
+ {
+ AddOneTo(mV);
+
+ mEngine.ProcessBlock(mV, 0, tmp, 0);
+
+ Array.Copy(tmp, 0, output, i * tmp.Length, bytesToCopy);
+ }
+ }
+
+ CTR_DRBG_Update(additionalInput, mKey, mV);
+
+ mReseedCounter++;
+
+ return output.Length * 8;
+ }
+
+ /**
+ * Reseed the DRBG.
+ *
+ * @param additionalInput additional input to be added to the DRBG in this step.
+ */
+ public void Reseed(byte[] additionalInput)
+ {
+ CTR_DRBG_Reseed_algorithm(additionalInput);
+ }
+
+ private bool IsTdea(IBlockCipher cipher)
+ {
+ return cipher.AlgorithmName.Equals("DESede") || cipher.AlgorithmName.Equals("TDEA");
+ }
+
+ private int GetMaxSecurityStrength(IBlockCipher cipher, int keySizeInBits)
+ {
+ if (IsTdea(cipher) && keySizeInBits == 168)
+ {
+ return 112;
+ }
+ if (cipher.AlgorithmName.Equals("AES"))
+ {
+ return keySizeInBits;
+ }
+
+ return -1;
+ }
+
+ private byte[] ExpandKey(byte[] key)
+ {
+ if (mIsTdea)
+ {
+ // expand key to 192 bits.
+ byte[] tmp = new byte[24];
+
+ PadKey(key, 0, tmp, 0);
+ PadKey(key, 7, tmp, 8);
+ PadKey(key, 14, tmp, 16);
+
+ return tmp;
+ }
+ else
+ {
+ return key;
+ }
+ }
+
+ /**
+ * Pad out a key for TDEA, setting odd parity for each byte.
+ *
+ * @param keyMaster
+ * @param keyOff
+ * @param tmp
+ * @param tmpOff
+ */
+ private void PadKey(byte[] keyMaster, int keyOff, byte[] tmp, int tmpOff)
+ {
+ tmp[tmpOff + 0] = (byte)(keyMaster[keyOff + 0] & 0xfe);
+ tmp[tmpOff + 1] = (byte)((keyMaster[keyOff + 0] << 7) | ((keyMaster[keyOff + 1] & 0xfc) >> 1));
+ tmp[tmpOff + 2] = (byte)((keyMaster[keyOff + 1] << 6) | ((keyMaster[keyOff + 2] & 0xf8) >> 2));
+ tmp[tmpOff + 3] = (byte)((keyMaster[keyOff + 2] << 5) | ((keyMaster[keyOff + 3] & 0xf0) >> 3));
+ tmp[tmpOff + 4] = (byte)((keyMaster[keyOff + 3] << 4) | ((keyMaster[keyOff + 4] & 0xe0) >> 4));
+ tmp[tmpOff + 5] = (byte)((keyMaster[keyOff + 4] << 3) | ((keyMaster[keyOff + 5] & 0xc0) >> 5));
+ tmp[tmpOff + 6] = (byte)((keyMaster[keyOff + 5] << 2) | ((keyMaster[keyOff + 6] & 0x80) >> 6));
+ tmp[tmpOff + 7] = (byte)(keyMaster[keyOff + 6] << 1);
+
+ DesParameters.SetOddParity(tmp, tmpOff, 8);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/CtrSP800Drbg.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/CtrSP800Drbg.cs.meta
new file mode 100644
index 00000000..55b69515
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/CtrSP800Drbg.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: edfb0cb793332c04897bd15f6ba5d7dd
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/DrbgUtilities.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/DrbgUtilities.cs
new file mode 100644
index 00000000..f3ef1ca3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/DrbgUtilities.cs
@@ -0,0 +1,107 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng.Drbg
+{
+ internal class DrbgUtilities
+ {
+ private static readonly IDictionary maxSecurityStrengths = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+
+ static DrbgUtilities()
+ {
+ maxSecurityStrengths.Add("SHA-1", 128);
+
+ maxSecurityStrengths.Add("SHA-224", 192);
+ maxSecurityStrengths.Add("SHA-256", 256);
+ maxSecurityStrengths.Add("SHA-384", 256);
+ maxSecurityStrengths.Add("SHA-512", 256);
+
+ maxSecurityStrengths.Add("SHA-512/224", 192);
+ maxSecurityStrengths.Add("SHA-512/256", 256);
+ }
+
+ internal static int GetMaxSecurityStrength(IDigest d)
+ {
+ return (int)maxSecurityStrengths[d.AlgorithmName];
+ }
+
+ internal static int GetMaxSecurityStrength(IMac m)
+ {
+ string name = m.AlgorithmName;
+
+ return (int)maxSecurityStrengths[name.Substring(0, name.IndexOf("/"))];
+ }
+
+ /**
+ * Used by both Dual EC and Hash.
+ */
+ internal static byte[] HashDF(IDigest digest, byte[] seedMaterial, int seedLength)
+ {
+ // 1. temp = the Null string.
+ // 2. .
+ // 3. counter = an 8-bit binary value representing the integer "1".
+ // 4. For i = 1 to len do
+ // Comment : In step 4.1, no_of_bits_to_return
+ // is used as a 32-bit string.
+ // 4.1 temp = temp || Hash (counter || no_of_bits_to_return ||
+ // input_string).
+ // 4.2 counter = counter + 1.
+ // 5. requested_bits = Leftmost (no_of_bits_to_return) of temp.
+ // 6. Return SUCCESS and requested_bits.
+ byte[] temp = new byte[(seedLength + 7) / 8];
+
+ int len = temp.Length / digest.GetDigestSize();
+ int counter = 1;
+
+ byte[] dig = new byte[digest.GetDigestSize()];
+
+ for (int i = 0; i <= len; i++)
+ {
+ digest.Update((byte)counter);
+
+ digest.Update((byte)(seedLength >> 24));
+ digest.Update((byte)(seedLength >> 16));
+ digest.Update((byte)(seedLength >> 8));
+ digest.Update((byte)seedLength);
+
+ digest.BlockUpdate(seedMaterial, 0, seedMaterial.Length);
+
+ digest.DoFinal(dig, 0);
+
+ int bytesToCopy = ((temp.Length - i * dig.Length) > dig.Length)
+ ? dig.Length
+ : (temp.Length - i * dig.Length);
+ Array.Copy(dig, 0, temp, i * dig.Length, bytesToCopy);
+
+ counter++;
+ }
+
+ // do a left shift to get rid of excess bits.
+ if (seedLength % 8 != 0)
+ {
+ int shift = 8 - (seedLength % 8);
+ uint carry = 0;
+
+ for (int i = 0; i != temp.Length; i++)
+ {
+ uint b = temp[i];
+ temp[i] = (byte)((b >> shift) | (carry << (8 - shift)));
+ carry = b;
+ }
+ }
+
+ return temp;
+ }
+
+ internal static bool IsTooLarge(byte[] bytes, int maxBytes)
+ {
+ return bytes != null && bytes.Length > maxBytes;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/DrbgUtilities.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/DrbgUtilities.cs.meta
new file mode 100644
index 00000000..d248fc17
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/DrbgUtilities.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: b7d5029db1ebd4d488a8e6d442ba71e9
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/HMacSP800Drbg.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/HMacSP800Drbg.cs
new file mode 100644
index 00000000..445c3149
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/HMacSP800Drbg.cs
@@ -0,0 +1,190 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng.Drbg
+{
+ /**
+ * A SP800-90A HMAC DRBG.
+ */
+ public class HMacSP800Drbg
+ : ISP80090Drbg
+ {
+ private readonly static long RESEED_MAX = 1L << (48 - 1);
+ private readonly static int MAX_BITS_REQUEST = 1 << (19 - 1);
+
+ private readonly byte[] mK;
+ private readonly byte[] mV;
+ private readonly IEntropySource mEntropySource;
+ private readonly IMac mHMac;
+ private readonly int mSecurityStrength;
+
+ private long mReseedCounter;
+
+ /**
+ * Construct a SP800-90A Hash DRBG.
+ *
+ * Minimum entropy requirement is the security strength requested.
+ *
+ * @param hMac Hash MAC to base the DRBG on.
+ * @param securityStrength security strength required (in bits)
+ * @param entropySource source of entropy to use for seeding/reseeding.
+ * @param personalizationString personalization string to distinguish this DRBG (may be null).
+ * @param nonce nonce to further distinguish this DRBG (may be null).
+ */
+ public HMacSP800Drbg(IMac hMac, int securityStrength, IEntropySource entropySource, byte[] personalizationString, byte[] nonce)
+ {
+ if (securityStrength > DrbgUtilities.GetMaxSecurityStrength(hMac))
+ throw new ArgumentException("Requested security strength is not supported by the derivation function");
+ if (entropySource.EntropySize < securityStrength)
+ throw new ArgumentException("Not enough entropy for security strength required");
+
+ mHMac = hMac;
+ mSecurityStrength = securityStrength;
+ mEntropySource = entropySource;
+
+ byte[] entropy = GetEntropy();
+ byte[] seedMaterial = Arrays.ConcatenateAll(entropy, nonce, personalizationString);
+
+ mK = new byte[hMac.GetMacSize()];
+ mV = new byte[mK.Length];
+ Arrays.Fill(mV, (byte)1);
+
+ hmac_DRBG_Update(seedMaterial);
+
+ mReseedCounter = 1;
+ }
+
+ private void hmac_DRBG_Update(byte[] seedMaterial)
+ {
+ hmac_DRBG_Update_Func(seedMaterial, (byte)0x00);
+ if (seedMaterial != null)
+ {
+ hmac_DRBG_Update_Func(seedMaterial, (byte)0x01);
+ }
+ }
+
+ private void hmac_DRBG_Update_Func(byte[] seedMaterial, byte vValue)
+ {
+ mHMac.Init(new KeyParameter(mK));
+
+ mHMac.BlockUpdate(mV, 0, mV.Length);
+ mHMac.Update(vValue);
+
+ if (seedMaterial != null)
+ {
+ mHMac.BlockUpdate(seedMaterial, 0, seedMaterial.Length);
+ }
+
+ mHMac.DoFinal(mK, 0);
+
+ mHMac.Init(new KeyParameter(mK));
+ mHMac.BlockUpdate(mV, 0, mV.Length);
+
+ mHMac.DoFinal(mV, 0);
+ }
+
+ /**
+ * Return the block size (in bits) of the DRBG.
+ *
+ * @return the number of bits produced on each round of the DRBG.
+ */
+ public int BlockSize
+ {
+ get { return mV.Length * 8; }
+ }
+
+ /**
+ * Populate a passed in array with random data.
+ *
+ * @param output output array for generated bits.
+ * @param additionalInput additional input to be added to the DRBG in this step.
+ * @param predictionResistant true if a reseed should be forced, false otherwise.
+ *
+ * @return number of bits generated, -1 if a reseed required.
+ */
+ public int Generate(byte[] output, byte[] additionalInput, bool predictionResistant)
+ {
+ int numberOfBits = output.Length * 8;
+
+ if (numberOfBits > MAX_BITS_REQUEST)
+ throw new ArgumentException("Number of bits per request limited to " + MAX_BITS_REQUEST, "output");
+
+ if (mReseedCounter > RESEED_MAX)
+ {
+ return -1;
+ }
+
+ if (predictionResistant)
+ {
+ Reseed(additionalInput);
+ additionalInput = null;
+ }
+
+ // 2.
+ if (additionalInput != null)
+ {
+ hmac_DRBG_Update(additionalInput);
+ }
+
+ // 3.
+ byte[] rv = new byte[output.Length];
+
+ int m = output.Length / mV.Length;
+
+ mHMac.Init(new KeyParameter(mK));
+
+ for (int i = 0; i < m; i++)
+ {
+ mHMac.BlockUpdate(mV, 0, mV.Length);
+ mHMac.DoFinal(mV, 0);
+
+ Array.Copy(mV, 0, rv, i * mV.Length, mV.Length);
+ }
+
+ if (m * mV.Length < rv.Length)
+ {
+ mHMac.BlockUpdate(mV, 0, mV.Length);
+ mHMac.DoFinal(mV, 0);
+
+ Array.Copy(mV, 0, rv, m * mV.Length, rv.Length - (m * mV.Length));
+ }
+
+ hmac_DRBG_Update(additionalInput);
+
+ mReseedCounter++;
+
+ Array.Copy(rv, 0, output, 0, output.Length);
+
+ return numberOfBits;
+ }
+
+ /**
+ * Reseed the DRBG.
+ *
+ * @param additionalInput additional input to be added to the DRBG in this step.
+ */
+ public void Reseed(byte[] additionalInput)
+ {
+ byte[] entropy = GetEntropy();
+ byte[] seedMaterial = Arrays.Concatenate(entropy, additionalInput);
+
+ hmac_DRBG_Update(seedMaterial);
+
+ mReseedCounter = 1;
+ }
+
+ private byte[] GetEntropy()
+ {
+ byte[] entropy = mEntropySource.GetEntropy();
+ if (entropy.Length < (mSecurityStrength + 7) / 8)
+ throw new InvalidOperationException("Insufficient entropy provided by entropy source");
+ return entropy;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/HMacSP800Drbg.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/HMacSP800Drbg.cs.meta
new file mode 100644
index 00000000..82d3de0f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/HMacSP800Drbg.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0531f450ee87c1344976250270fa8568
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/HashSP800Drbg.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/HashSP800Drbg.cs
new file mode 100644
index 00000000..7d244fcc
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/HashSP800Drbg.cs
@@ -0,0 +1,291 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng.Drbg
+{
+ /**
+ * A SP800-90A Hash DRBG.
+ */
+ public class HashSP800Drbg
+ : ISP80090Drbg
+ {
+ private readonly static byte[] ONE = { 0x01 };
+
+ private readonly static long RESEED_MAX = 1L << (48 - 1);
+ private readonly static int MAX_BITS_REQUEST = 1 << (19 - 1);
+
+ private static readonly IDictionary seedlens = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+
+ static HashSP800Drbg()
+ {
+ seedlens.Add("SHA-1", 440);
+ seedlens.Add("SHA-224", 440);
+ seedlens.Add("SHA-256", 440);
+ seedlens.Add("SHA-512/256", 440);
+ seedlens.Add("SHA-512/224", 440);
+ seedlens.Add("SHA-384", 888);
+ seedlens.Add("SHA-512", 888);
+ }
+
+ private readonly IDigest mDigest;
+ private readonly IEntropySource mEntropySource;
+ private readonly int mSecurityStrength;
+ private readonly int mSeedLength;
+
+ private byte[] mV;
+ private byte[] mC;
+ private long mReseedCounter;
+
+ /**
+ * Construct a SP800-90A Hash DRBG.
+ *
+ * Minimum entropy requirement is the security strength requested.
+ *
+ * @param digest source digest to use for DRB stream.
+ * @param securityStrength security strength required (in bits)
+ * @param entropySource source of entropy to use for seeding/reseeding.
+ * @param personalizationString personalization string to distinguish this DRBG (may be null).
+ * @param nonce nonce to further distinguish this DRBG (may be null).
+ */
+ public HashSP800Drbg(IDigest digest, int securityStrength, IEntropySource entropySource, byte[] personalizationString, byte[] nonce)
+ {
+ if (securityStrength > DrbgUtilities.GetMaxSecurityStrength(digest))
+ throw new ArgumentException("Requested security strength is not supported by the derivation function");
+ if (entropySource.EntropySize < securityStrength)
+ throw new ArgumentException("Not enough entropy for security strength required");
+
+ mDigest = digest;
+ mEntropySource = entropySource;
+ mSecurityStrength = securityStrength;
+ mSeedLength = (int)seedlens[digest.AlgorithmName];
+
+ // 1. seed_material = entropy_input || nonce || personalization_string.
+ // 2. seed = Hash_df (seed_material, seedlen).
+ // 3. V = seed.
+ // 4. C = Hash_df ((0x00 || V), seedlen). Comment: Preceed V with a byte
+ // of zeros.
+ // 5. reseed_counter = 1.
+ // 6. Return V, C, and reseed_counter as the initial_working_state
+
+ byte[] entropy = GetEntropy();
+ byte[] seedMaterial = Arrays.ConcatenateAll(entropy, nonce, personalizationString);
+ byte[] seed = DrbgUtilities.HashDF(mDigest, seedMaterial, mSeedLength);
+
+ mV = seed;
+ byte[] subV = new byte[mV.Length + 1];
+ Array.Copy(mV, 0, subV, 1, mV.Length);
+ mC = DrbgUtilities.HashDF(mDigest, subV, mSeedLength);
+
+ mReseedCounter = 1;
+ }
+
+ /**
+ * Return the block size (in bits) of the DRBG.
+ *
+ * @return the number of bits produced on each internal round of the DRBG.
+ */
+ public int BlockSize
+ {
+ get { return mDigest.GetDigestSize () * 8; }
+ }
+
+ /**
+ * Populate a passed in array with random data.
+ *
+ * @param output output array for generated bits.
+ * @param additionalInput additional input to be added to the DRBG in this step.
+ * @param predictionResistant true if a reseed should be forced, false otherwise.
+ *
+ * @return number of bits generated, -1 if a reseed required.
+ */
+ public int Generate(byte[] output, byte[] additionalInput, bool predictionResistant)
+ {
+ // 1. If reseed_counter > reseed_interval, then return an indication that a
+ // reseed is required.
+ // 2. If (additional_input != Null), then do
+ // 2.1 w = Hash (0x02 || V || additional_input).
+ // 2.2 V = (V + w) mod 2^seedlen
+ // .
+ // 3. (returned_bits) = Hashgen (requested_number_of_bits, V).
+ // 4. H = Hash (0x03 || V).
+ // 5. V = (V + H + C + reseed_counter) mod 2^seedlen
+ // .
+ // 6. reseed_counter = reseed_counter + 1.
+ // 7. Return SUCCESS, returned_bits, and the new values of V, C, and
+ // reseed_counter for the new_working_state.
+ int numberOfBits = output.Length * 8;
+
+ if (numberOfBits > MAX_BITS_REQUEST)
+ throw new ArgumentException("Number of bits per request limited to " + MAX_BITS_REQUEST, "output");
+
+ if (mReseedCounter > RESEED_MAX)
+ return -1;
+
+ if (predictionResistant)
+ {
+ Reseed(additionalInput);
+ additionalInput = null;
+ }
+
+ // 2.
+ if (additionalInput != null)
+ {
+ byte[] newInput = new byte[1 + mV.Length + additionalInput.Length];
+ newInput[0] = 0x02;
+ Array.Copy(mV, 0, newInput, 1, mV.Length);
+ // TODO: inOff / inLength
+ Array.Copy(additionalInput, 0, newInput, 1 + mV.Length, additionalInput.Length);
+ byte[] w = Hash(newInput);
+
+ AddTo(mV, w);
+ }
+
+ // 3.
+ byte[] rv = hashgen(mV, numberOfBits);
+
+ // 4.
+ byte[] subH = new byte[mV.Length + 1];
+ Array.Copy(mV, 0, subH, 1, mV.Length);
+ subH[0] = 0x03;
+
+ byte[] H = Hash(subH);
+
+ // 5.
+ AddTo(mV, H);
+ AddTo(mV, mC);
+ byte[] c = new byte[4];
+ c[0] = (byte)(mReseedCounter >> 24);
+ c[1] = (byte)(mReseedCounter >> 16);
+ c[2] = (byte)(mReseedCounter >> 8);
+ c[3] = (byte)mReseedCounter;
+
+ AddTo(mV, c);
+
+ mReseedCounter++;
+
+ Array.Copy(rv, 0, output, 0, output.Length);
+
+ return numberOfBits;
+ }
+
+ private byte[] GetEntropy()
+ {
+ byte[] entropy = mEntropySource.GetEntropy();
+ if (entropy.Length < (mSecurityStrength + 7) / 8)
+ throw new InvalidOperationException("Insufficient entropy provided by entropy source");
+ return entropy;
+ }
+
+ // this will always add the shorter length byte array mathematically to the
+ // longer length byte array.
+ // be careful....
+ private void AddTo(byte[] longer, byte[] shorter)
+ {
+ int off = longer.Length - shorter.Length;
+
+ uint carry = 0;
+ int i = shorter.Length;
+ while (--i >= 0)
+ {
+ carry += (uint)longer[off + i] + (uint)shorter[i];
+ longer[off + i] = (byte)carry;
+ carry >>= 8;
+ }
+
+ i = off;
+ while (--i >= 0)
+ {
+ carry += longer[i];
+ longer[i] = (byte)carry;
+ carry >>= 8;
+ }
+ }
+
+ /**
+ * Reseed the DRBG.
+ *
+ * @param additionalInput additional input to be added to the DRBG in this step.
+ */
+ public void Reseed(byte[] additionalInput)
+ {
+ // 1. seed_material = 0x01 || V || entropy_input || additional_input.
+ //
+ // 2. seed = Hash_df (seed_material, seedlen).
+ //
+ // 3. V = seed.
+ //
+ // 4. C = Hash_df ((0x00 || V), seedlen).
+ //
+ // 5. reseed_counter = 1.
+ //
+ // 6. Return V, C, and reseed_counter for the new_working_state.
+ //
+ // Comment: Precede with a byte of all zeros.
+ byte[] entropy = GetEntropy();
+ byte[] seedMaterial = Arrays.ConcatenateAll(ONE, mV, entropy, additionalInput);
+ byte[] seed = DrbgUtilities.HashDF(mDigest, seedMaterial, mSeedLength);
+
+ mV = seed;
+ byte[] subV = new byte[mV.Length + 1];
+ subV[0] = 0x00;
+ Array.Copy(mV, 0, subV, 1, mV.Length);
+ mC = DrbgUtilities.HashDF(mDigest, subV, mSeedLength);
+
+ mReseedCounter = 1;
+ }
+
+ private byte[] Hash(byte[] input)
+ {
+ byte[] hash = new byte[mDigest.GetDigestSize()];
+ DoHash(input, hash);
+ return hash;
+ }
+
+ private void DoHash(byte[] input, byte[] output)
+ {
+ mDigest.BlockUpdate(input, 0, input.Length);
+ mDigest.DoFinal(output, 0);
+ }
+
+ // 1. m = [requested_number_of_bits / outlen]
+ // 2. data = V.
+ // 3. W = the Null string.
+ // 4. For i = 1 to m
+ // 4.1 wi = Hash (data).
+ // 4.2 W = W || wi.
+ // 4.3 data = (data + 1) mod 2^seedlen
+ // .
+ // 5. returned_bits = Leftmost (requested_no_of_bits) bits of W.
+ private byte[] hashgen(byte[] input, int lengthInBits)
+ {
+ int digestSize = mDigest.GetDigestSize();
+ int m = (lengthInBits / 8) / digestSize;
+
+ byte[] data = new byte[input.Length];
+ Array.Copy(input, 0, data, 0, input.Length);
+
+ byte[] W = new byte[lengthInBits / 8];
+
+ byte[] dig = new byte[mDigest.GetDigestSize()];
+ for (int i = 0; i <= m; i++)
+ {
+ DoHash(data, dig);
+
+ int bytesToCopy = ((W.Length - i * dig.Length) > dig.Length)
+ ? dig.Length
+ : (W.Length - i * dig.Length);
+ Array.Copy(dig, 0, W, i * dig.Length, bytesToCopy);
+
+ AddTo(data, ONE);
+ }
+
+ return W;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/HashSP800Drbg.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/HashSP800Drbg.cs.meta
new file mode 100644
index 00000000..e5705360
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/HashSP800Drbg.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a85748f6547ed6342a29b17c5d5fc6eb
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/ISP80090Drbg.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/ISP80090Drbg.cs
new file mode 100644
index 00000000..b48b7fe7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/ISP80090Drbg.cs
@@ -0,0 +1,39 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng.Drbg
+{
+ /**
+ * Interface to SP800-90A deterministic random bit generators.
+ */
+ public interface ISP80090Drbg
+ {
+ /**
+ * Return the block size of the DRBG.
+ *
+ * @return the block size (in bits) produced by each round of the DRBG.
+ */
+ int BlockSize { get; }
+
+ /**
+ * Populate a passed in array with random data.
+ *
+ * @param output output array for generated bits.
+ * @param additionalInput additional input to be added to the DRBG in this step.
+ * @param predictionResistant true if a reseed should be forced, false otherwise.
+ *
+ * @return number of bits generated, -1 if a reseed required.
+ */
+ int Generate(byte[] output, byte[] additionalInput, bool predictionResistant);
+
+ /**
+ * Reseed the DRBG.
+ *
+ * @param additionalInput additional input to be added to the DRBG in this step.
+ */
+ void Reseed(byte[] additionalInput);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/ISP80090Drbg.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/ISP80090Drbg.cs.meta
new file mode 100644
index 00000000..a30836d9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/prng/drbg/ISP80090Drbg.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: b5c19a9bd75eab245b6a2d472950fd2d
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers.meta
new file mode 100644
index 00000000..09316afa
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 962655b8d2a40294bad978e6d458a24e
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/DsaDigestSigner.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/DsaDigestSigner.cs
new file mode 100644
index 00000000..036f7cb5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/DsaDigestSigner.cs
@@ -0,0 +1,150 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
+{
+ public class DsaDigestSigner
+ : ISigner
+ {
+ private readonly IDsa dsa;
+ private readonly IDigest digest;
+ private readonly IDsaEncoding encoding;
+ private bool forSigning;
+
+ public DsaDigestSigner(
+ IDsa dsa,
+ IDigest digest)
+ {
+ this.dsa = dsa;
+ this.digest = digest;
+ this.encoding = StandardDsaEncoding.Instance;
+ }
+
+ public DsaDigestSigner(
+ IDsaExt dsa,
+ IDigest digest,
+ IDsaEncoding encoding)
+ {
+ this.dsa = dsa;
+ this.digest = digest;
+ this.encoding = encoding;
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return digest.AlgorithmName + "with" + dsa.AlgorithmName; }
+ }
+
+ public virtual void Init(
+ bool forSigning,
+ ICipherParameters parameters)
+ {
+ this.forSigning = forSigning;
+
+ AsymmetricKeyParameter k;
+
+ if (parameters is ParametersWithRandom)
+ {
+ k = (AsymmetricKeyParameter)((ParametersWithRandom)parameters).Parameters;
+ }
+ else
+ {
+ k = (AsymmetricKeyParameter)parameters;
+ }
+
+ if (forSigning && !k.IsPrivate)
+ throw new InvalidKeyException("Signing Requires Private Key.");
+
+ if (!forSigning && k.IsPrivate)
+ throw new InvalidKeyException("Verification Requires Public Key.");
+
+ Reset();
+
+ dsa.Init(forSigning, parameters);
+ }
+
+ /**
+ * update the internal digest with the byte b
+ */
+ public virtual void Update(
+ byte input)
+ {
+ digest.Update(input);
+ }
+
+ /**
+ * update the internal digest with the byte array in
+ */
+ public virtual void BlockUpdate(
+ byte[] input,
+ int inOff,
+ int length)
+ {
+ digest.BlockUpdate(input, inOff, length);
+ }
+
+ /**
+ * Generate a signature for the message we've been loaded with using
+ * the key we were initialised with.
+ */
+ public virtual byte[] GenerateSignature()
+ {
+ if (!forSigning)
+ throw new InvalidOperationException("DSADigestSigner not initialised for signature generation.");
+
+ byte[] hash = new byte[digest.GetDigestSize()];
+ digest.DoFinal(hash, 0);
+
+ BigInteger[] sig = dsa.GenerateSignature(hash);
+
+ try
+ {
+ return encoding.Encode(GetOrder(), sig[0], sig[1]);
+ }
+ catch (Exception)
+ {
+ throw new InvalidOperationException("unable to encode signature");
+ }
+ }
+
+ /// true if the internal state represents the signature described in the passed in array.
+ public virtual bool VerifySignature(
+ byte[] signature)
+ {
+ if (forSigning)
+ throw new InvalidOperationException("DSADigestSigner not initialised for verification");
+
+ byte[] hash = new byte[digest.GetDigestSize()];
+ digest.DoFinal(hash, 0);
+
+ try
+ {
+ BigInteger[] sig = encoding.Decode(GetOrder(), signature);
+
+ return dsa.VerifySignature(hash, sig[0], sig[1]);
+ }
+ catch (Exception e)
+ {
+ return false;
+ }
+ }
+
+ /// Reset the internal state
+ public virtual void Reset()
+ {
+ digest.Reset();
+ }
+
+ protected virtual BigInteger GetOrder()
+ {
+ return dsa is IDsaExt ? ((IDsaExt)dsa).Order : null;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/DsaDigestSigner.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/DsaDigestSigner.cs.meta
new file mode 100644
index 00000000..645f7640
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/DsaDigestSigner.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c9905792014e74d4f8a532ab18084ac5
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/DsaSigner.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/DsaSigner.cs
new file mode 100644
index 00000000..c042e32e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/DsaSigner.cs
@@ -0,0 +1,165 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
+{
+ /**
+ * The Digital Signature Algorithm - as described in "Handbook of Applied
+ * Cryptography", pages 452 - 453.
+ */
+ public class DsaSigner
+ : IDsaExt
+ {
+ protected readonly IDsaKCalculator kCalculator;
+
+ protected DsaKeyParameters key = null;
+ protected SecureRandom random = null;
+
+ /**
+ * Default configuration, random K values.
+ */
+ public DsaSigner()
+ {
+ this.kCalculator = new RandomDsaKCalculator();
+ }
+
+ /**
+ * Configuration with an alternate, possibly deterministic calculator of K.
+ *
+ * @param kCalculator a K value calculator.
+ */
+ public DsaSigner(IDsaKCalculator kCalculator)
+ {
+ this.kCalculator = kCalculator;
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "DSA"; }
+ }
+
+ public virtual void Init(bool forSigning, ICipherParameters parameters)
+ {
+ SecureRandom providedRandom = null;
+
+ if (forSigning)
+ {
+ if (parameters is ParametersWithRandom)
+ {
+ ParametersWithRandom rParam = (ParametersWithRandom)parameters;
+
+ providedRandom = rParam.Random;
+ parameters = rParam.Parameters;
+ }
+
+ if (!(parameters is DsaPrivateKeyParameters))
+ throw new InvalidKeyException("DSA private key required for signing");
+
+ this.key = (DsaPrivateKeyParameters)parameters;
+ }
+ else
+ {
+ if (!(parameters is DsaPublicKeyParameters))
+ throw new InvalidKeyException("DSA public key required for verification");
+
+ this.key = (DsaPublicKeyParameters)parameters;
+ }
+
+ this.random = InitSecureRandom(forSigning && !kCalculator.IsDeterministic, providedRandom);
+ }
+
+ public virtual BigInteger Order
+ {
+ get { return key.Parameters.Q; }
+ }
+
+ /**
+ * Generate a signature for the given message using the key we were
+ * initialised with. For conventional DSA the message should be a SHA-1
+ * hash of the message of interest.
+ *
+ * @param message the message that will be verified later.
+ */
+ public virtual BigInteger[] GenerateSignature(byte[] message)
+ {
+ DsaParameters parameters = key.Parameters;
+ BigInteger q = parameters.Q;
+ BigInteger m = CalculateE(q, message);
+ BigInteger x = ((DsaPrivateKeyParameters)key).X;
+
+ if (kCalculator.IsDeterministic)
+ {
+ kCalculator.Init(q, x, message);
+ }
+ else
+ {
+ kCalculator.Init(q, random);
+ }
+
+ BigInteger k = kCalculator.NextK();
+
+ BigInteger r = parameters.G.ModPow(k, parameters.P).Mod(q);
+
+ k = k.ModInverse(q).Multiply(m.Add(x.Multiply(r)));
+
+ BigInteger s = k.Mod(q);
+
+ return new BigInteger[]{ r, s };
+ }
+
+ /**
+ * return true if the value r and s represent a DSA signature for
+ * the passed in message for standard DSA the message should be a
+ * SHA-1 hash of the real message to be verified.
+ */
+ public virtual bool VerifySignature(byte[] message, BigInteger r, BigInteger s)
+ {
+ DsaParameters parameters = key.Parameters;
+ BigInteger q = parameters.Q;
+ BigInteger m = CalculateE(q, message);
+
+ if (r.SignValue <= 0 || q.CompareTo(r) <= 0)
+ {
+ return false;
+ }
+
+ if (s.SignValue <= 0 || q.CompareTo(s) <= 0)
+ {
+ return false;
+ }
+
+ BigInteger w = s.ModInverse(q);
+
+ BigInteger u1 = m.Multiply(w).Mod(q);
+ BigInteger u2 = r.Multiply(w).Mod(q);
+
+ BigInteger p = parameters.P;
+ u1 = parameters.G.ModPow(u1, p);
+ u2 = ((DsaPublicKeyParameters)key).Y.ModPow(u2, p);
+
+ BigInteger v = u1.Multiply(u2).Mod(p).Mod(q);
+
+ return v.Equals(r);
+ }
+
+ protected virtual BigInteger CalculateE(BigInteger n, byte[] message)
+ {
+ int length = System.Math.Min(message.Length, n.BitLength / 8);
+
+ return new BigInteger(1, message, 0, length);
+ }
+
+ protected virtual SecureRandom InitSecureRandom(bool needed, SecureRandom provided)
+ {
+ return !needed ? null : (provided != null) ? provided : new SecureRandom();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/DsaSigner.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/DsaSigner.cs.meta
new file mode 100644
index 00000000..f2b98a82
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/DsaSigner.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 5b22a4699dfabe048aca470ec8820c46
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/ECDsaSigner.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/ECDsaSigner.cs
new file mode 100644
index 00000000..a1165ee0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/ECDsaSigner.cs
@@ -0,0 +1,249 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Multiplier;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
+{
+ /**
+ * EC-DSA as described in X9.62
+ */
+ public class ECDsaSigner
+ : IDsaExt
+ {
+ private static readonly BigInteger Eight = BigInteger.ValueOf(8);
+
+ protected readonly IDsaKCalculator kCalculator;
+
+ protected ECKeyParameters key = null;
+ protected SecureRandom random = null;
+
+ /**
+ * Default configuration, random K values.
+ */
+ public ECDsaSigner()
+ {
+ this.kCalculator = new RandomDsaKCalculator();
+ }
+
+ /**
+ * Configuration with an alternate, possibly deterministic calculator of K.
+ *
+ * @param kCalculator a K value calculator.
+ */
+ public ECDsaSigner(IDsaKCalculator kCalculator)
+ {
+ this.kCalculator = kCalculator;
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "ECDSA"; }
+ }
+
+ public virtual void Init(bool forSigning, ICipherParameters parameters)
+ {
+ SecureRandom providedRandom = null;
+
+ if (forSigning)
+ {
+ if (parameters is ParametersWithRandom)
+ {
+ ParametersWithRandom rParam = (ParametersWithRandom)parameters;
+
+ providedRandom = rParam.Random;
+ parameters = rParam.Parameters;
+ }
+
+ if (!(parameters is ECPrivateKeyParameters))
+ throw new InvalidKeyException("EC private key required for signing");
+
+ this.key = (ECPrivateKeyParameters)parameters;
+ }
+ else
+ {
+ if (!(parameters is ECPublicKeyParameters))
+ throw new InvalidKeyException("EC public key required for verification");
+
+ this.key = (ECPublicKeyParameters)parameters;
+ }
+
+ this.random = InitSecureRandom(forSigning && !kCalculator.IsDeterministic, providedRandom);
+ }
+
+ public virtual BigInteger Order
+ {
+ get { return key.Parameters.N; }
+ }
+
+ // 5.3 pg 28
+ /**
+ * Generate a signature for the given message using the key we were
+ * initialised with. For conventional DSA the message should be a SHA-1
+ * hash of the message of interest.
+ *
+ * @param message the message that will be verified later.
+ */
+ public virtual BigInteger[] GenerateSignature(byte[] message)
+ {
+ ECDomainParameters ec = key.Parameters;
+ BigInteger n = ec.N;
+ BigInteger e = CalculateE(n, message);
+ BigInteger d = ((ECPrivateKeyParameters)key).D;
+
+ if (kCalculator.IsDeterministic)
+ {
+ kCalculator.Init(n, d, message);
+ }
+ else
+ {
+ kCalculator.Init(n, random);
+ }
+
+ BigInteger r, s;
+
+ ECMultiplier basePointMultiplier = CreateBasePointMultiplier();
+
+ // 5.3.2
+ do // Generate s
+ {
+ BigInteger k;
+ do // Generate r
+ {
+ k = kCalculator.NextK();
+
+ ECPoint p = basePointMultiplier.Multiply(ec.G, k).Normalize();
+
+ // 5.3.3
+ r = p.AffineXCoord.ToBigInteger().Mod(n);
+ }
+ while (r.SignValue == 0);
+
+ s = k.ModInverse(n).Multiply(e.Add(d.Multiply(r))).Mod(n);
+ }
+ while (s.SignValue == 0);
+
+ return new BigInteger[]{ r, s };
+ }
+
+ // 5.4 pg 29
+ /**
+ * return true if the value r and s represent a DSA signature for
+ * the passed in message (for standard DSA the message should be
+ * a SHA-1 hash of the real message to be verified).
+ */
+ public virtual bool VerifySignature(byte[] message, BigInteger r, BigInteger s)
+ {
+ BigInteger n = key.Parameters.N;
+
+ // r and s should both in the range [1,n-1]
+ if (r.SignValue < 1 || s.SignValue < 1
+ || r.CompareTo(n) >= 0 || s.CompareTo(n) >= 0)
+ {
+ return false;
+ }
+
+ BigInteger e = CalculateE(n, message);
+ BigInteger c = s.ModInverse(n);
+
+ BigInteger u1 = e.Multiply(c).Mod(n);
+ BigInteger u2 = r.Multiply(c).Mod(n);
+
+ ECPoint G = key.Parameters.G;
+ ECPoint Q = ((ECPublicKeyParameters) key).Q;
+
+ ECPoint point = ECAlgorithms.SumOfTwoMultiplies(G, u1, Q, u2);
+
+ if (point.IsInfinity)
+ return false;
+
+ /*
+ * If possible, avoid normalizing the point (to save a modular inversion in the curve field).
+ *
+ * There are ~cofactor elements of the curve field that reduce (modulo the group order) to 'r'.
+ * If the cofactor is known and small, we generate those possible field values and project each
+ * of them to the same "denominator" (depending on the particular projective coordinates in use)
+ * as the calculated point.X. If any of the projected values matches point.X, then we have:
+ * (point.X / Denominator mod p) mod n == r
+ * as required, and verification succeeds.
+ *
+ * Based on an original idea by Gregory Maxwell (https://github.com/gmaxwell), as implemented in
+ * the libsecp256k1 project (https://github.com/bitcoin/secp256k1).
+ */
+ ECCurve curve = point.Curve;
+ if (curve != null)
+ {
+ BigInteger cofactor = curve.Cofactor;
+ if (cofactor != null && cofactor.CompareTo(Eight) <= 0)
+ {
+ ECFieldElement D = GetDenominator(curve.CoordinateSystem, point);
+ if (D != null && !D.IsZero)
+ {
+ ECFieldElement X = point.XCoord;
+ while (curve.IsValidFieldElement(r))
+ {
+ ECFieldElement R = curve.FromBigInteger(r).Multiply(D);
+ if (R.Equals(X))
+ {
+ return true;
+ }
+ r = r.Add(n);
+ }
+ return false;
+ }
+ }
+ }
+
+ BigInteger v = point.Normalize().AffineXCoord.ToBigInteger().Mod(n);
+ return v.Equals(r);
+ }
+
+ protected virtual BigInteger CalculateE(BigInteger n, byte[] message)
+ {
+ int messageBitLength = message.Length * 8;
+ BigInteger trunc = new BigInteger(1, message);
+
+ if (n.BitLength < messageBitLength)
+ {
+ trunc = trunc.ShiftRight(messageBitLength - n.BitLength);
+ }
+
+ return trunc;
+ }
+
+ protected virtual ECMultiplier CreateBasePointMultiplier()
+ {
+ return new FixedPointCombMultiplier();
+ }
+
+ protected virtual ECFieldElement GetDenominator(int coordinateSystem, ECPoint p)
+ {
+ switch (coordinateSystem)
+ {
+ case ECCurve.COORD_HOMOGENEOUS:
+ case ECCurve.COORD_LAMBDA_PROJECTIVE:
+ case ECCurve.COORD_SKEWED:
+ return p.GetZCoord(0);
+ case ECCurve.COORD_JACOBIAN:
+ case ECCurve.COORD_JACOBIAN_CHUDNOVSKY:
+ case ECCurve.COORD_JACOBIAN_MODIFIED:
+ return p.GetZCoord(0).Square();
+ default:
+ return null;
+ }
+ }
+
+ protected virtual SecureRandom InitSecureRandom(bool needed, SecureRandom provided)
+ {
+ return !needed ? null : (provided != null) ? provided : new SecureRandom();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/ECDsaSigner.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/ECDsaSigner.cs.meta
new file mode 100644
index 00000000..3bf6ef68
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/ECDsaSigner.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 2aeec19b82b60784b857139153cf8807
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/ECGOST3410Signer.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/ECGOST3410Signer.cs
new file mode 100644
index 00000000..44e5d1a7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/ECGOST3410Signer.cs
@@ -0,0 +1,171 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Multiplier;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
+{
+ /**
+ * GOST R 34.10-2001 Signature Algorithm
+ */
+ public class ECGost3410Signer
+ : IDsaExt
+ {
+ private ECKeyParameters key;
+ private SecureRandom random;
+
+ public virtual string AlgorithmName
+ {
+ get { return "ECGOST3410"; }
+ }
+
+ public virtual void Init(
+ bool forSigning,
+ ICipherParameters parameters)
+ {
+ if (forSigning)
+ {
+ if (parameters is ParametersWithRandom)
+ {
+ ParametersWithRandom rParam = (ParametersWithRandom)parameters;
+
+ this.random = rParam.Random;
+ parameters = rParam.Parameters;
+ }
+ else
+ {
+ this.random = new SecureRandom();
+ }
+
+ if (!(parameters is ECPrivateKeyParameters))
+ throw new InvalidKeyException("EC private key required for signing");
+
+ this.key = (ECPrivateKeyParameters) parameters;
+ }
+ else
+ {
+ if (!(parameters is ECPublicKeyParameters))
+ throw new InvalidKeyException("EC public key required for verification");
+
+ this.key = (ECPublicKeyParameters)parameters;
+ }
+ }
+
+ public virtual BigInteger Order
+ {
+ get { return key.Parameters.N; }
+ }
+
+ /**
+ * generate a signature for the given message using the key we were
+ * initialised with. For conventional GOST3410 the message should be a GOST3411
+ * hash of the message of interest.
+ *
+ * @param message the message that will be verified later.
+ */
+ public virtual BigInteger[] GenerateSignature(
+ byte[] message)
+ {
+ byte[] mRev = new byte[message.Length]; // conversion is little-endian
+ for (int i = 0; i != mRev.Length; i++)
+ {
+ mRev[i] = message[mRev.Length - 1 - i];
+ }
+
+ BigInteger e = new BigInteger(1, mRev);
+
+ ECDomainParameters ec = key.Parameters;
+ BigInteger n = ec.N;
+ BigInteger d = ((ECPrivateKeyParameters)key).D;
+
+ BigInteger r, s = null;
+
+ ECMultiplier basePointMultiplier = CreateBasePointMultiplier();
+
+ do // generate s
+ {
+ BigInteger k;
+ do // generate r
+ {
+ do
+ {
+ k = new BigInteger(n.BitLength, random);
+ }
+ while (k.SignValue == 0);
+
+ ECPoint p = basePointMultiplier.Multiply(ec.G, k).Normalize();
+
+ r = p.AffineXCoord.ToBigInteger().Mod(n);
+ }
+ while (r.SignValue == 0);
+
+ s = (k.Multiply(e)).Add(d.Multiply(r)).Mod(n);
+ }
+ while (s.SignValue == 0);
+
+ return new BigInteger[]{ r, s };
+ }
+
+ /**
+ * return true if the value r and s represent a GOST3410 signature for
+ * the passed in message (for standard GOST3410 the message should be
+ * a GOST3411 hash of the real message to be verified).
+ */
+ public virtual bool VerifySignature(
+ byte[] message,
+ BigInteger r,
+ BigInteger s)
+ {
+ byte[] mRev = new byte[message.Length]; // conversion is little-endian
+ for (int i = 0; i != mRev.Length; i++)
+ {
+ mRev[i] = message[mRev.Length - 1 - i];
+ }
+
+ BigInteger e = new BigInteger(1, mRev);
+ BigInteger n = key.Parameters.N;
+
+ // r in the range [1,n-1]
+ if (r.CompareTo(BigInteger.One) < 0 || r.CompareTo(n) >= 0)
+ {
+ return false;
+ }
+
+ // s in the range [1,n-1]
+ if (s.CompareTo(BigInteger.One) < 0 || s.CompareTo(n) >= 0)
+ {
+ return false;
+ }
+
+ BigInteger v = e.ModInverse(n);
+
+ BigInteger z1 = s.Multiply(v).Mod(n);
+ BigInteger z2 = (n.Subtract(r)).Multiply(v).Mod(n);
+
+ ECPoint G = key.Parameters.G; // P
+ ECPoint Q = ((ECPublicKeyParameters)key).Q;
+
+ ECPoint point = ECAlgorithms.SumOfTwoMultiplies(G, z1, Q, z2).Normalize();
+
+ if (point.IsInfinity)
+ return false;
+
+ BigInteger R = point.AffineXCoord.ToBigInteger().Mod(n);
+
+ return R.Equals(r);
+ }
+
+ protected virtual ECMultiplier CreateBasePointMultiplier()
+ {
+ return new FixedPointCombMultiplier();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/ECGOST3410Signer.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/ECGOST3410Signer.cs.meta
new file mode 100644
index 00000000..62116d19
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/ECGOST3410Signer.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c0fa6c431f2efb54c89b5784adc45bd7
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/ECNRSigner.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/ECNRSigner.cs
new file mode 100644
index 00000000..03fa64be
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/ECNRSigner.cs
@@ -0,0 +1,197 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
+{
+ /**
+ * EC-NR as described in IEEE 1363-2000
+ */
+ public class ECNRSigner
+ : IDsaExt
+ {
+ private bool forSigning;
+ private ECKeyParameters key;
+ private SecureRandom random;
+
+ public virtual string AlgorithmName
+ {
+ get { return "ECNR"; }
+ }
+
+ public virtual void Init(
+ bool forSigning,
+ ICipherParameters parameters)
+ {
+ this.forSigning = forSigning;
+
+ if (forSigning)
+ {
+ if (parameters is ParametersWithRandom)
+ {
+ ParametersWithRandom rParam = (ParametersWithRandom) parameters;
+
+ this.random = rParam.Random;
+ parameters = rParam.Parameters;
+ }
+ else
+ {
+ this.random = new SecureRandom();
+ }
+
+ if (!(parameters is ECPrivateKeyParameters))
+ throw new InvalidKeyException("EC private key required for signing");
+
+ this.key = (ECPrivateKeyParameters) parameters;
+ }
+ else
+ {
+ if (!(parameters is ECPublicKeyParameters))
+ throw new InvalidKeyException("EC public key required for verification");
+
+ this.key = (ECPublicKeyParameters) parameters;
+ }
+ }
+
+ public virtual BigInteger Order
+ {
+ get { return key.Parameters.N; }
+ }
+
+ // Section 7.2.5 ECSP-NR, pg 34
+ /**
+ * generate a signature for the given message using the key we were
+ * initialised with. Generally, the order of the curve should be at
+ * least as long as the hash of the message of interest, and with
+ * ECNR it *must* be at least as long.
+ *
+ * @param digest the digest to be signed.
+ * @exception DataLengthException if the digest is longer than the key allows
+ */
+ public virtual BigInteger[] GenerateSignature(
+ byte[] message)
+ {
+ if (!this.forSigning)
+ {
+ // not properly initilaized... deal with it
+ throw new InvalidOperationException("not initialised for signing");
+ }
+
+ BigInteger n = Order;
+ int nBitLength = n.BitLength;
+
+ BigInteger e = new BigInteger(1, message);
+ int eBitLength = e.BitLength;
+
+ ECPrivateKeyParameters privKey = (ECPrivateKeyParameters)key;
+
+ if (eBitLength > nBitLength)
+ {
+ throw new DataLengthException("input too large for ECNR key.");
+ }
+
+ BigInteger r = null;
+ BigInteger s = null;
+
+ AsymmetricCipherKeyPair tempPair;
+ do // generate r
+ {
+ // generate another, but very temporary, key pair using
+ // the same EC parameters
+ ECKeyPairGenerator keyGen = new ECKeyPairGenerator();
+
+ keyGen.Init(new ECKeyGenerationParameters(privKey.Parameters, this.random));
+
+ tempPair = keyGen.GenerateKeyPair();
+
+ // BigInteger Vx = tempPair.getPublic().getW().getAffineX();
+ ECPublicKeyParameters V = (ECPublicKeyParameters) tempPair.Public; // get temp's public key
+ BigInteger Vx = V.Q.AffineXCoord.ToBigInteger(); // get the point's x coordinate
+
+ r = Vx.Add(e).Mod(n);
+ }
+ while (r.SignValue == 0);
+
+ // generate s
+ BigInteger x = privKey.D; // private key value
+ BigInteger u = ((ECPrivateKeyParameters) tempPair.Private).D; // temp's private key value
+ s = u.Subtract(r.Multiply(x)).Mod(n);
+
+ return new BigInteger[]{ r, s };
+ }
+
+ // Section 7.2.6 ECVP-NR, pg 35
+ /**
+ * return true if the value r and s represent a signature for the
+ * message passed in. Generally, the order of the curve should be at
+ * least as long as the hash of the message of interest, and with
+ * ECNR, it *must* be at least as long. But just in case the signer
+ * applied mod(n) to the longer digest, this implementation will
+ * apply mod(n) during verification.
+ *
+ * @param digest the digest to be verified.
+ * @param r the r value of the signature.
+ * @param s the s value of the signature.
+ * @exception DataLengthException if the digest is longer than the key allows
+ */
+ public virtual bool VerifySignature(
+ byte[] message,
+ BigInteger r,
+ BigInteger s)
+ {
+ if (this.forSigning)
+ {
+ // not properly initilaized... deal with it
+ throw new InvalidOperationException("not initialised for verifying");
+ }
+
+ ECPublicKeyParameters pubKey = (ECPublicKeyParameters)key;
+ BigInteger n = pubKey.Parameters.N;
+ int nBitLength = n.BitLength;
+
+ BigInteger e = new BigInteger(1, message);
+ int eBitLength = e.BitLength;
+
+ if (eBitLength > nBitLength)
+ {
+ throw new DataLengthException("input too large for ECNR key.");
+ }
+
+ // r in the range [1,n-1]
+ if (r.CompareTo(BigInteger.One) < 0 || r.CompareTo(n) >= 0)
+ {
+ return false;
+ }
+
+ // s in the range [0,n-1] NB: ECNR spec says 0
+ if (s.CompareTo(BigInteger.Zero) < 0 || s.CompareTo(n) >= 0)
+ {
+ return false;
+ }
+
+ // compute P = sG + rW
+
+ ECPoint G = pubKey.Parameters.G;
+ ECPoint W = pubKey.Q;
+ // calculate P using Bouncy math
+ ECPoint P = ECAlgorithms.SumOfTwoMultiplies(G, s, W, r).Normalize();
+
+ if (P.IsInfinity)
+ return false;
+
+ BigInteger x = P.AffineXCoord.ToBigInteger();
+ BigInteger t = r.Subtract(x).Mod(n);
+
+ return t.Equals(e);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/ECNRSigner.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/ECNRSigner.cs.meta
new file mode 100644
index 00000000..7e5ffc36
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/ECNRSigner.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 7b65a3f5dbbb4a340bbc3407aa2a1316
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed25519Signer.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed25519Signer.cs
new file mode 100644
index 00000000..d2485d32
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed25519Signer.cs
@@ -0,0 +1,138 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Rfc8032;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
+{
+ public class Ed25519Signer
+ : ISigner
+ {
+ private readonly Buffer buffer = new Buffer();
+
+ private bool forSigning;
+ private Ed25519PrivateKeyParameters privateKey;
+ private Ed25519PublicKeyParameters publicKey;
+
+ public Ed25519Signer()
+ {
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "Ed25519"; }
+ }
+
+ public virtual void Init(bool forSigning, ICipherParameters parameters)
+ {
+ this.forSigning = forSigning;
+
+ if (forSigning)
+ {
+ // TODO Allow IAsymmetricCipherKeyPair to be an ICipherParameters?
+
+ this.privateKey = (Ed25519PrivateKeyParameters)parameters;
+ this.publicKey = privateKey.GeneratePublicKey();
+ }
+ else
+ {
+ this.privateKey = null;
+ this.publicKey = (Ed25519PublicKeyParameters)parameters;
+ }
+
+ Reset();
+ }
+
+ public virtual void Update(byte b)
+ {
+ buffer.WriteByte(b);
+ }
+
+ public virtual void BlockUpdate(byte[] buf, int off, int len)
+ {
+ buffer.Write(buf, off, len);
+ }
+
+ public virtual byte[] GenerateSignature()
+ {
+ if (!forSigning || null == privateKey)
+ throw new InvalidOperationException("Ed25519Signer not initialised for signature generation.");
+
+ return buffer.GenerateSignature(privateKey, publicKey);
+ }
+
+ public virtual bool VerifySignature(byte[] signature)
+ {
+ if (forSigning || null == publicKey)
+ throw new InvalidOperationException("Ed25519Signer not initialised for verification");
+
+ return buffer.VerifySignature(publicKey, signature);
+ }
+
+ public virtual void Reset()
+ {
+ buffer.Reset();
+ }
+
+ private class Buffer : MemoryStream
+ {
+ internal byte[] GenerateSignature(Ed25519PrivateKeyParameters privateKey, Ed25519PublicKeyParameters publicKey)
+ {
+ lock (this)
+ {
+#if PORTABLE || NETFX_CORE
+ byte[] buf = ToArray();
+ int count = buf.Length;
+#else
+ byte[] buf = GetBuffer();
+ int count = (int)Position;
+#endif
+ byte[] signature = new byte[Ed25519PrivateKeyParameters.SignatureSize];
+ privateKey.Sign(Ed25519.Algorithm.Ed25519, publicKey, null, buf, 0, count, signature, 0);
+ Reset();
+ return signature;
+ }
+ }
+
+ internal bool VerifySignature(Ed25519PublicKeyParameters publicKey, byte[] signature)
+ {
+ lock (this)
+ {
+#if PORTABLE || NETFX_CORE
+ byte[] buf = ToArray();
+ int count = buf.Length;
+#else
+ byte[] buf = GetBuffer();
+ int count = (int)Position;
+#endif
+ byte[] pk = publicKey.GetEncoded();
+ bool result = Ed25519.Verify(signature, 0, pk, 0, buf, 0, count);
+ Reset();
+ return result;
+ }
+ }
+
+ internal void Reset()
+ {
+ lock (this)
+ {
+ long count = Position;
+#if PORTABLE || NETFX_CORE
+ this.Position = 0L;
+ Streams.WriteZeroes(this, count);
+#else
+ Array.Clear(GetBuffer(), 0, (int)count);
+#endif
+ this.Position = 0L;
+ }
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed25519Signer.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed25519Signer.cs.meta
new file mode 100644
index 00000000..b5498a35
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed25519Signer.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c4be6eb199857ba4fbc1658655705be2
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed25519ctxSigner.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed25519ctxSigner.cs
new file mode 100644
index 00000000..c381b3c1
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed25519ctxSigner.cs
@@ -0,0 +1,140 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Rfc8032;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
+{
+ public class Ed25519ctxSigner
+ : ISigner
+ {
+ private readonly Buffer buffer = new Buffer();
+ private readonly byte[] context;
+
+ private bool forSigning;
+ private Ed25519PrivateKeyParameters privateKey;
+ private Ed25519PublicKeyParameters publicKey;
+
+ public Ed25519ctxSigner(byte[] context)
+ {
+ this.context = Arrays.Clone(context);
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "Ed25519ctx"; }
+ }
+
+ public virtual void Init(bool forSigning, ICipherParameters parameters)
+ {
+ this.forSigning = forSigning;
+
+ if (forSigning)
+ {
+ // TODO Allow IAsymmetricCipherKeyPair to be an ICipherParameters?
+
+ this.privateKey = (Ed25519PrivateKeyParameters)parameters;
+ this.publicKey = privateKey.GeneratePublicKey();
+ }
+ else
+ {
+ this.privateKey = null;
+ this.publicKey = (Ed25519PublicKeyParameters)parameters;
+ }
+
+ Reset();
+ }
+
+ public virtual void Update(byte b)
+ {
+ buffer.WriteByte(b);
+ }
+
+ public virtual void BlockUpdate(byte[] buf, int off, int len)
+ {
+ buffer.Write(buf, off, len);
+ }
+
+ public virtual byte[] GenerateSignature()
+ {
+ if (!forSigning || null == privateKey)
+ throw new InvalidOperationException("Ed25519ctxSigner not initialised for signature generation.");
+
+ return buffer.GenerateSignature(privateKey, publicKey, context);
+ }
+
+ public virtual bool VerifySignature(byte[] signature)
+ {
+ if (forSigning || null == publicKey)
+ throw new InvalidOperationException("Ed25519ctxSigner not initialised for verification");
+
+ return buffer.VerifySignature(publicKey, context, signature);
+ }
+
+ public virtual void Reset()
+ {
+ buffer.Reset();
+ }
+
+ private class Buffer : MemoryStream
+ {
+ internal byte[] GenerateSignature(Ed25519PrivateKeyParameters privateKey, Ed25519PublicKeyParameters publicKey, byte[] ctx)
+ {
+ lock (this)
+ {
+#if PORTABLE || NETFX_CORE
+ byte[] buf = ToArray();
+ int count = buf.Length;
+#else
+ byte[] buf = GetBuffer();
+ int count = (int)Position;
+#endif
+ byte[] signature = new byte[Ed25519PrivateKeyParameters.SignatureSize];
+ privateKey.Sign(Ed25519.Algorithm.Ed25519ctx, publicKey, ctx, buf, 0, count, signature, 0);
+ Reset();
+ return signature;
+ }
+ }
+
+ internal bool VerifySignature(Ed25519PublicKeyParameters publicKey, byte[] ctx, byte[] signature)
+ {
+ lock (this)
+ {
+#if PORTABLE || NETFX_CORE
+ byte[] buf = ToArray();
+ int count = buf.Length;
+#else
+ byte[] buf = GetBuffer();
+ int count = (int)Position;
+#endif
+ byte[] pk = publicKey.GetEncoded();
+ bool result = Ed25519.Verify(signature, 0, pk, 0, ctx, buf, 0, count);
+ Reset();
+ return result;
+ }
+ }
+
+ internal void Reset()
+ {
+ lock (this)
+ {
+ long count = Position;
+#if PORTABLE || NETFX_CORE
+ this.Position = 0L;
+ Streams.WriteZeroes(this, count);
+#else
+ Array.Clear(GetBuffer(), 0, (int)count);
+#endif
+ this.Position = 0L;
+ }
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed25519ctxSigner.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed25519ctxSigner.cs.meta
new file mode 100644
index 00000000..8be00c05
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed25519ctxSigner.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 6a1d3e7080838824a9ba890b627de089
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed25519phSigner.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed25519phSigner.cs
new file mode 100644
index 00000000..ce24107d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed25519phSigner.cs
@@ -0,0 +1,92 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Rfc8032;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
+{
+ public class Ed25519phSigner
+ : ISigner
+ {
+ private readonly IDigest prehash = Ed25519.CreatePrehash();
+ private readonly byte[] context;
+
+ private bool forSigning;
+ private Ed25519PrivateKeyParameters privateKey;
+ private Ed25519PublicKeyParameters publicKey;
+
+ public Ed25519phSigner(byte[] context)
+ {
+ this.context = Arrays.Clone(context);
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "Ed25519ph"; }
+ }
+
+ public virtual void Init(bool forSigning, ICipherParameters parameters)
+ {
+ this.forSigning = forSigning;
+
+ if (forSigning)
+ {
+ // TODO Allow AsymmetricCipherKeyPair to be a CipherParameters?
+
+ this.privateKey = (Ed25519PrivateKeyParameters)parameters;
+ this.publicKey = privateKey.GeneratePublicKey();
+ }
+ else
+ {
+ this.privateKey = null;
+ this.publicKey = (Ed25519PublicKeyParameters)parameters;
+ }
+
+ Reset();
+ }
+
+ public virtual void Update(byte b)
+ {
+ prehash.Update(b);
+ }
+
+ public virtual void BlockUpdate(byte[] buf, int off, int len)
+ {
+ prehash.BlockUpdate(buf, off, len);
+ }
+
+ public virtual byte[] GenerateSignature()
+ {
+ if (!forSigning || null == privateKey)
+ throw new InvalidOperationException("Ed25519phSigner not initialised for signature generation.");
+
+ byte[] msg = new byte[Ed25519.PrehashSize];
+ if (Ed25519.PrehashSize != prehash.DoFinal(msg, 0))
+ throw new InvalidOperationException("Prehash digest failed");
+
+ byte[] signature = new byte[Ed25519PrivateKeyParameters.SignatureSize];
+ privateKey.Sign(Ed25519.Algorithm.Ed25519ph, publicKey, context, msg, 0, Ed25519.PrehashSize, signature, 0);
+ return signature;
+ }
+
+ public virtual bool VerifySignature(byte[] signature)
+ {
+ if (forSigning || null == publicKey)
+ throw new InvalidOperationException("Ed25519phSigner not initialised for verification");
+
+ byte[] pk = publicKey.GetEncoded();
+ return Ed25519.VerifyPrehash(signature, 0, pk, 0, context, prehash);
+ }
+
+ public void Reset()
+ {
+ prehash.Reset();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed25519phSigner.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed25519phSigner.cs.meta
new file mode 100644
index 00000000..32d69648
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed25519phSigner.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 4cb55a2ed90089e49bf2f4a650bd0b75
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed448Signer.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed448Signer.cs
new file mode 100644
index 00000000..386c221e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed448Signer.cs
@@ -0,0 +1,140 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Rfc8032;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
+{
+ public class Ed448Signer
+ : ISigner
+ {
+ private readonly Buffer buffer = new Buffer();
+ private readonly byte[] context;
+
+ private bool forSigning;
+ private Ed448PrivateKeyParameters privateKey;
+ private Ed448PublicKeyParameters publicKey;
+
+ public Ed448Signer(byte[] context)
+ {
+ this.context = Arrays.Clone(context);
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "Ed448"; }
+ }
+
+ public virtual void Init(bool forSigning, ICipherParameters parameters)
+ {
+ this.forSigning = forSigning;
+
+ if (forSigning)
+ {
+ // TODO Allow IAsymmetricCipherKeyPair to be an ICipherParameters?
+
+ this.privateKey = (Ed448PrivateKeyParameters)parameters;
+ this.publicKey = privateKey.GeneratePublicKey();
+ }
+ else
+ {
+ this.privateKey = null;
+ this.publicKey = (Ed448PublicKeyParameters)parameters;
+ }
+
+ Reset();
+ }
+
+ public virtual void Update(byte b)
+ {
+ buffer.WriteByte(b);
+ }
+
+ public virtual void BlockUpdate(byte[] buf, int off, int len)
+ {
+ buffer.Write(buf, off, len);
+ }
+
+ public virtual byte[] GenerateSignature()
+ {
+ if (!forSigning || null == privateKey)
+ throw new InvalidOperationException("Ed448Signer not initialised for signature generation.");
+
+ return buffer.GenerateSignature(privateKey, publicKey, context);
+ }
+
+ public virtual bool VerifySignature(byte[] signature)
+ {
+ if (forSigning || null == publicKey)
+ throw new InvalidOperationException("Ed448Signer not initialised for verification");
+
+ return buffer.VerifySignature(publicKey, context, signature);
+ }
+
+ public virtual void Reset()
+ {
+ buffer.Reset();
+ }
+
+ private class Buffer : MemoryStream
+ {
+ internal byte[] GenerateSignature(Ed448PrivateKeyParameters privateKey, Ed448PublicKeyParameters publicKey, byte[] ctx)
+ {
+ lock (this)
+ {
+#if PORTABLE || NETFX_CORE
+ byte[] buf = ToArray();
+ int count = buf.Length;
+#else
+ byte[] buf = GetBuffer();
+ int count = (int)Position;
+#endif
+ byte[] signature = new byte[Ed448PrivateKeyParameters.SignatureSize];
+ privateKey.Sign(Ed448.Algorithm.Ed448, publicKey, ctx, buf, 0, count, signature, 0);
+ Reset();
+ return signature;
+ }
+ }
+
+ internal bool VerifySignature(Ed448PublicKeyParameters publicKey, byte[] ctx, byte[] signature)
+ {
+ lock (this)
+ {
+#if PORTABLE || NETFX_CORE
+ byte[] buf = ToArray();
+ int count = buf.Length;
+#else
+ byte[] buf = GetBuffer();
+ int count = (int)Position;
+#endif
+ byte[] pk = publicKey.GetEncoded();
+ bool result = Ed448.Verify(signature, 0, pk, 0, ctx, buf, 0, count);
+ Reset();
+ return result;
+ }
+ }
+
+ internal void Reset()
+ {
+ lock (this)
+ {
+ long count = Position;
+#if PORTABLE || NETFX_CORE
+ this.Position = 0L;
+ Streams.WriteZeroes(this, count);
+#else
+ Array.Clear(GetBuffer(), 0, (int)count);
+#endif
+ this.Position = 0L;
+ }
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed448Signer.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed448Signer.cs.meta
new file mode 100644
index 00000000..9f1f36e9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed448Signer.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 3f9d2c4cec709344a955e7ee6be9ef75
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed448phSigner.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed448phSigner.cs
new file mode 100644
index 00000000..5c3208ea
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed448phSigner.cs
@@ -0,0 +1,92 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Rfc8032;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
+{
+ public class Ed448phSigner
+ : ISigner
+ {
+ private readonly IXof prehash = Ed448.CreatePrehash();
+ private readonly byte[] context;
+
+ private bool forSigning;
+ private Ed448PrivateKeyParameters privateKey;
+ private Ed448PublicKeyParameters publicKey;
+
+ public Ed448phSigner(byte[] context)
+ {
+ this.context = Arrays.Clone(context);
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "Ed448ph"; }
+ }
+
+ public virtual void Init(bool forSigning, ICipherParameters parameters)
+ {
+ this.forSigning = forSigning;
+
+ if (forSigning)
+ {
+ // TODO Allow AsymmetricCipherKeyPair to be a CipherParameters?
+
+ this.privateKey = (Ed448PrivateKeyParameters)parameters;
+ this.publicKey = privateKey.GeneratePublicKey();
+ }
+ else
+ {
+ this.privateKey = null;
+ this.publicKey = (Ed448PublicKeyParameters)parameters;
+ }
+
+ Reset();
+ }
+
+ public virtual void Update(byte b)
+ {
+ prehash.Update(b);
+ }
+
+ public virtual void BlockUpdate(byte[] buf, int off, int len)
+ {
+ prehash.BlockUpdate(buf, off, len);
+ }
+
+ public virtual byte[] GenerateSignature()
+ {
+ if (!forSigning || null == privateKey)
+ throw new InvalidOperationException("Ed448phSigner not initialised for signature generation.");
+
+ byte[] msg = new byte[Ed448.PrehashSize];
+ if (Ed448.PrehashSize != prehash.DoFinal(msg, 0, Ed448.PrehashSize))
+ throw new InvalidOperationException("Prehash digest failed");
+
+ byte[] signature = new byte[Ed448PrivateKeyParameters.SignatureSize];
+ privateKey.Sign(Ed448.Algorithm.Ed448ph, publicKey, context, msg, 0, Ed448.PrehashSize, signature, 0);
+ return signature;
+ }
+
+ public virtual bool VerifySignature(byte[] signature)
+ {
+ if (forSigning || null == publicKey)
+ throw new InvalidOperationException("Ed448phSigner not initialised for verification");
+
+ byte[] pk = publicKey.GetEncoded();
+ return Ed448.VerifyPrehash(signature, 0, pk, 0, context, prehash);
+ }
+
+ public void Reset()
+ {
+ prehash.Reset();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed448phSigner.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed448phSigner.cs.meta
new file mode 100644
index 00000000..cd684f89
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Ed448phSigner.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: d482c3f30a338e84eac18dc552d6f14f
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/GOST3410DigestSigner.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/GOST3410DigestSigner.cs
new file mode 100644
index 00000000..c690e191
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/GOST3410DigestSigner.cs
@@ -0,0 +1,149 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
+{
+ public class Gost3410DigestSigner
+ : ISigner
+ {
+ private readonly IDigest digest;
+ private readonly IDsa dsaSigner;
+ private bool forSigning;
+
+ public Gost3410DigestSigner(
+ IDsa signer,
+ IDigest digest)
+ {
+ this.dsaSigner = signer;
+ this.digest = digest;
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return digest.AlgorithmName + "with" + dsaSigner.AlgorithmName; }
+ }
+
+ public virtual void Init(
+ bool forSigning,
+ ICipherParameters parameters)
+ {
+ this.forSigning = forSigning;
+
+ AsymmetricKeyParameter k;
+ if (parameters is ParametersWithRandom)
+ {
+ k = (AsymmetricKeyParameter)((ParametersWithRandom)parameters).Parameters;
+ }
+ else
+ {
+ k = (AsymmetricKeyParameter)parameters;
+ }
+
+ if (forSigning && !k.IsPrivate)
+ {
+ throw new InvalidKeyException("Signing Requires Private Key.");
+ }
+
+ if (!forSigning && k.IsPrivate)
+ {
+ throw new InvalidKeyException("Verification Requires Public Key.");
+ }
+
+ Reset();
+
+ dsaSigner.Init(forSigning, parameters);
+ }
+
+ /**
+ * update the internal digest with the byte b
+ */
+ public virtual void Update(
+ byte input)
+ {
+ digest.Update(input);
+ }
+
+ /**
+ * update the internal digest with the byte array in
+ */
+ public virtual void BlockUpdate(
+ byte[] input,
+ int inOff,
+ int length)
+ {
+ digest.BlockUpdate(input, inOff, length);
+ }
+
+ /**
+ * Generate a signature for the message we've been loaded with using
+ * the key we were initialised with.
+ */
+ public virtual byte[] GenerateSignature()
+ {
+ if (!forSigning)
+ throw new InvalidOperationException("GOST3410DigestSigner not initialised for signature generation.");
+
+ byte[] hash = new byte[digest.GetDigestSize()];
+ digest.DoFinal(hash, 0);
+
+ try
+ {
+ BigInteger[] sig = dsaSigner.GenerateSignature(hash);
+ byte[] sigBytes = new byte[64];
+
+ // TODO Add methods to allow writing BigInteger to existing byte array?
+ byte[] r = sig[0].ToByteArrayUnsigned();
+ byte[] s = sig[1].ToByteArrayUnsigned();
+ s.CopyTo(sigBytes, 32 - s.Length);
+ r.CopyTo(sigBytes, 64 - r.Length);
+ return sigBytes;
+ }
+ catch (Exception e)
+ {
+ throw new SignatureException(e.Message, e);
+ }
+ }
+
+ /// true if the internal state represents the signature described in the passed in array.
+ public virtual bool VerifySignature(
+ byte[] signature)
+ {
+ if (forSigning)
+ throw new InvalidOperationException("DSADigestSigner not initialised for verification");
+
+ byte[] hash = new byte[digest.GetDigestSize()];
+ digest.DoFinal(hash, 0);
+
+ BigInteger R, S;
+ try
+ {
+ R = new BigInteger(1, signature, 32, 32);
+ S = new BigInteger(1, signature, 0, 32);
+ }
+ catch (Exception e)
+ {
+ throw new SignatureException("error decoding signature bytes.", e);
+ }
+
+ return dsaSigner.VerifySignature(hash, R, S);
+ }
+
+ /// Reset the internal state
+ public virtual void Reset()
+ {
+ digest.Reset();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/GOST3410DigestSigner.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/GOST3410DigestSigner.cs.meta
new file mode 100644
index 00000000..313b6beb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/GOST3410DigestSigner.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: e49e35369e72fe545b2a1fddbaa3603a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/GOST3410Signer.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/GOST3410Signer.cs
new file mode 100644
index 00000000..84f7a64a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/GOST3410Signer.cs
@@ -0,0 +1,141 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
+{
+ /**
+ * Gost R 34.10-94 Signature Algorithm
+ */
+ public class Gost3410Signer
+ : IDsaExt
+ {
+ private Gost3410KeyParameters key;
+ private SecureRandom random;
+
+ public virtual string AlgorithmName
+ {
+ get { return "GOST3410"; }
+ }
+
+ public virtual void Init(
+ bool forSigning,
+ ICipherParameters parameters)
+ {
+ if (forSigning)
+ {
+ if (parameters is ParametersWithRandom)
+ {
+ ParametersWithRandom rParam = (ParametersWithRandom)parameters;
+
+ this.random = rParam.Random;
+ parameters = rParam.Parameters;
+ }
+ else
+ {
+ this.random = new SecureRandom();
+ }
+
+ if (!(parameters is Gost3410PrivateKeyParameters))
+ throw new InvalidKeyException("GOST3410 private key required for signing");
+
+ this.key = (Gost3410PrivateKeyParameters) parameters;
+ }
+ else
+ {
+ if (!(parameters is Gost3410PublicKeyParameters))
+ throw new InvalidKeyException("GOST3410 public key required for signing");
+
+ this.key = (Gost3410PublicKeyParameters) parameters;
+ }
+ }
+
+ public virtual BigInteger Order
+ {
+ get { return key.Parameters.Q; }
+ }
+
+ /**
+ * generate a signature for the given message using the key we were
+ * initialised with. For conventional Gost3410 the message should be a Gost3411
+ * hash of the message of interest.
+ *
+ * @param message the message that will be verified later.
+ */
+ public virtual BigInteger[] GenerateSignature(
+ byte[] message)
+ {
+ byte[] mRev = new byte[message.Length]; // conversion is little-endian
+ for (int i = 0; i != mRev.Length; i++)
+ {
+ mRev[i] = message[mRev.Length - 1 - i];
+ }
+
+ BigInteger m = new BigInteger(1, mRev);
+ Gost3410Parameters parameters = key.Parameters;
+ BigInteger k;
+
+ do
+ {
+ k = new BigInteger(parameters.Q.BitLength, random);
+ }
+ while (k.CompareTo(parameters.Q) >= 0);
+
+ BigInteger r = parameters.A.ModPow(k, parameters.P).Mod(parameters.Q);
+
+ BigInteger s = k.Multiply(m).
+ Add(((Gost3410PrivateKeyParameters)key).X.Multiply(r)).
+ Mod(parameters.Q);
+
+ return new BigInteger[]{ r, s };
+ }
+
+ /**
+ * return true if the value r and s represent a Gost3410 signature for
+ * the passed in message for standard Gost3410 the message should be a
+ * Gost3411 hash of the real message to be verified.
+ */
+ public virtual bool VerifySignature(
+ byte[] message,
+ BigInteger r,
+ BigInteger s)
+ {
+ byte[] mRev = new byte[message.Length]; // conversion is little-endian
+ for (int i = 0; i != mRev.Length; i++)
+ {
+ mRev[i] = message[mRev.Length - 1 - i];
+ }
+
+ BigInteger m = new BigInteger(1, mRev);
+ Gost3410Parameters parameters = key.Parameters;
+
+ if (r.SignValue < 0 || parameters.Q.CompareTo(r) <= 0)
+ {
+ return false;
+ }
+
+ if (s.SignValue < 0 || parameters.Q.CompareTo(s) <= 0)
+ {
+ return false;
+ }
+
+ BigInteger v = m.ModPow(parameters.Q.Subtract(BigInteger.Two), parameters.Q);
+
+ BigInteger z1 = s.Multiply(v).Mod(parameters.Q);
+ BigInteger z2 = (parameters.Q.Subtract(r)).Multiply(v).Mod(parameters.Q);
+
+ z1 = parameters.A.ModPow(z1, parameters.P);
+ z2 = ((Gost3410PublicKeyParameters)key).Y.ModPow(z2, parameters.P);
+
+ BigInteger u = z1.Multiply(z2).Mod(parameters.P).Mod(parameters.Q);
+
+ return u.Equals(r);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/GOST3410Signer.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/GOST3410Signer.cs.meta
new file mode 100644
index 00000000..ec61a12e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/GOST3410Signer.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 675f660b7066e3842bfd94bc6c5ea723
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/GenericSigner.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/GenericSigner.cs
new file mode 100644
index 00000000..abf14d92
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/GenericSigner.cs
@@ -0,0 +1,134 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
+{
+ public class GenericSigner
+ : ISigner
+ {
+ private readonly IAsymmetricBlockCipher engine;
+ private readonly IDigest digest;
+ private bool forSigning;
+
+ public GenericSigner(
+ IAsymmetricBlockCipher engine,
+ IDigest digest)
+ {
+ this.engine = engine;
+ this.digest = digest;
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "Generic(" + engine.AlgorithmName + "/" + digest.AlgorithmName + ")"; }
+ }
+
+ /**
+ * initialise the signer for signing or verification.
+ *
+ * @param forSigning
+ * true if for signing, false otherwise
+ * @param parameters
+ * necessary parameters.
+ */
+ public virtual void Init(bool forSigning, ICipherParameters parameters)
+ {
+ this.forSigning = forSigning;
+
+ AsymmetricKeyParameter k;
+ if (parameters is ParametersWithRandom)
+ {
+ k = (AsymmetricKeyParameter)((ParametersWithRandom)parameters).Parameters;
+ }
+ else
+ {
+ k = (AsymmetricKeyParameter)parameters;
+ }
+
+ if (forSigning && !k.IsPrivate)
+ throw new InvalidKeyException("Signing requires private key.");
+
+ if (!forSigning && k.IsPrivate)
+ throw new InvalidKeyException("Verification requires public key.");
+
+ Reset();
+
+ engine.Init(forSigning, parameters);
+ }
+
+ /**
+ * update the internal digest with the byte b
+ */
+ public virtual void Update(byte input)
+ {
+ digest.Update(input);
+ }
+
+ /**
+ * update the internal digest with the byte array in
+ */
+ public virtual void BlockUpdate(byte[] input, int inOff, int length)
+ {
+ digest.BlockUpdate(input, inOff, length);
+ }
+
+ /**
+ * Generate a signature for the message we've been loaded with using the key
+ * we were initialised with.
+ */
+ public virtual byte[] GenerateSignature()
+ {
+ if (!forSigning)
+ throw new InvalidOperationException("GenericSigner not initialised for signature generation.");
+
+ byte[] hash = new byte[digest.GetDigestSize()];
+ digest.DoFinal(hash, 0);
+
+ return engine.ProcessBlock(hash, 0, hash.Length);
+ }
+
+ /**
+ * return true if the internal state represents the signature described in
+ * the passed in array.
+ */
+ public virtual bool VerifySignature(byte[] signature)
+ {
+ if (forSigning)
+ throw new InvalidOperationException("GenericSigner not initialised for verification");
+
+ byte[] hash = new byte[digest.GetDigestSize()];
+ digest.DoFinal(hash, 0);
+
+ try
+ {
+ byte[] sig = engine.ProcessBlock(signature, 0, signature.Length);
+
+ // Extend with leading zeroes to match the digest size, if necessary.
+ if (sig.Length < hash.Length)
+ {
+ byte[] tmp = new byte[hash.Length];
+ Array.Copy(sig, 0, tmp, tmp.Length - sig.Length, sig.Length);
+ sig = tmp;
+ }
+
+ return Arrays.ConstantTimeAreEqual(sig, hash);
+ }
+ catch (Exception)
+ {
+ return false;
+ }
+ }
+
+ public virtual void Reset()
+ {
+ digest.Reset();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/GenericSigner.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/GenericSigner.cs.meta
new file mode 100644
index 00000000..554fceec
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/GenericSigner.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c33281fcbe5fc2448a481ded39da05c4
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/HMacDsaKCalculator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/HMacDsaKCalculator.cs
new file mode 100644
index 00000000..a8cb7ca6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/HMacDsaKCalculator.cs
@@ -0,0 +1,155 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
+{
+ /**
+ * A deterministic K calculator based on the algorithm in section 3.2 of RFC 6979.
+ */
+ public class HMacDsaKCalculator
+ : IDsaKCalculator
+ {
+ private readonly HMac hMac;
+ private readonly byte[] K;
+ private readonly byte[] V;
+
+ private BigInteger n;
+
+ /**
+ * Base constructor.
+ *
+ * @param digest digest to build the HMAC on.
+ */
+ public HMacDsaKCalculator(IDigest digest)
+ {
+ this.hMac = new HMac(digest);
+ this.V = new byte[hMac.GetMacSize()];
+ this.K = new byte[hMac.GetMacSize()];
+ }
+
+ public virtual bool IsDeterministic
+ {
+ get { return true; }
+ }
+
+ public virtual void Init(BigInteger n, SecureRandom random)
+ {
+ throw new InvalidOperationException("Operation not supported");
+ }
+
+ public void Init(BigInteger n, BigInteger d, byte[] message)
+ {
+ this.n = n;
+
+ Arrays.Fill(V, (byte)0x01);
+ Arrays.Fill(K, (byte)0);
+
+ int size = BigIntegers.GetUnsignedByteLength(n);
+ byte[] x = new byte[size];
+ byte[] dVal = BigIntegers.AsUnsignedByteArray(d);
+
+ Array.Copy(dVal, 0, x, x.Length - dVal.Length, dVal.Length);
+
+ byte[] m = new byte[size];
+
+ BigInteger mInt = BitsToInt(message);
+
+ if (mInt.CompareTo(n) >= 0)
+ {
+ mInt = mInt.Subtract(n);
+ }
+
+ byte[] mVal = BigIntegers.AsUnsignedByteArray(mInt);
+
+ Array.Copy(mVal, 0, m, m.Length - mVal.Length, mVal.Length);
+
+ hMac.Init(new KeyParameter(K));
+
+ hMac.BlockUpdate(V, 0, V.Length);
+ hMac.Update((byte)0x00);
+ hMac.BlockUpdate(x, 0, x.Length);
+ hMac.BlockUpdate(m, 0, m.Length);
+
+ hMac.DoFinal(K, 0);
+
+ hMac.Init(new KeyParameter(K));
+
+ hMac.BlockUpdate(V, 0, V.Length);
+
+ hMac.DoFinal(V, 0);
+
+ hMac.BlockUpdate(V, 0, V.Length);
+ hMac.Update((byte)0x01);
+ hMac.BlockUpdate(x, 0, x.Length);
+ hMac.BlockUpdate(m, 0, m.Length);
+
+ hMac.DoFinal(K, 0);
+
+ hMac.Init(new KeyParameter(K));
+
+ hMac.BlockUpdate(V, 0, V.Length);
+
+ hMac.DoFinal(V, 0);
+ }
+
+ public virtual BigInteger NextK()
+ {
+ byte[] t = new byte[BigIntegers.GetUnsignedByteLength(n)];
+
+ for (;;)
+ {
+ int tOff = 0;
+
+ while (tOff < t.Length)
+ {
+ hMac.BlockUpdate(V, 0, V.Length);
+
+ hMac.DoFinal(V, 0);
+
+ int len = System.Math.Min(t.Length - tOff, V.Length);
+ Array.Copy(V, 0, t, tOff, len);
+ tOff += len;
+ }
+
+ BigInteger k = BitsToInt(t);
+
+ if (k.SignValue > 0 && k.CompareTo(n) < 0)
+ {
+ return k;
+ }
+
+ hMac.BlockUpdate(V, 0, V.Length);
+ hMac.Update((byte)0x00);
+
+ hMac.DoFinal(K, 0);
+
+ hMac.Init(new KeyParameter(K));
+
+ hMac.BlockUpdate(V, 0, V.Length);
+
+ hMac.DoFinal(V, 0);
+ }
+ }
+
+ private BigInteger BitsToInt(byte[] t)
+ {
+ BigInteger v = new BigInteger(1, t);
+
+ if (t.Length * 8 > n.BitLength)
+ {
+ v = v.ShiftRight(t.Length * 8 - n.BitLength);
+ }
+
+ return v;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/HMacDsaKCalculator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/HMacDsaKCalculator.cs.meta
new file mode 100644
index 00000000..a805ca9d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/HMacDsaKCalculator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 78e1027b4769aa54ba1097aeccbdf881
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/IDsaEncoding.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/IDsaEncoding.cs
new file mode 100644
index 00000000..c921dcb3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/IDsaEncoding.cs
@@ -0,0 +1,29 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
+{
+ ///
+ /// An interface for different encoding formats for DSA signatures.
+ ///
+ public interface IDsaEncoding
+ {
+ /// Decode the (r, s) pair of a DSA signature.
+ /// The order of the group that r, s belong to.
+ /// An encoding of the (r, s) pair of a DSA signature.
+ /// The (r, s) of a DSA signature, stored in an array of exactly two elements, r followed by s.
+ BigInteger[] Decode(BigInteger n, byte[] encoding);
+
+ /// Encode the (r, s) pair of a DSA signature.
+ /// The order of the group that r, s belong to.
+ /// The r value of a DSA signature.
+ /// The s value of a DSA signature.
+ /// An encoding of the DSA signature given by the provided (r, s) pair.
+ byte[] Encode(BigInteger n, BigInteger r, BigInteger s);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/IDsaEncoding.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/IDsaEncoding.cs.meta
new file mode 100644
index 00000000..f11da500
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/IDsaEncoding.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: b15d467750338ac4a8b50bf23145b743
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/IDsaKCalculator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/IDsaKCalculator.cs
new file mode 100644
index 00000000..08a40c45
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/IDsaKCalculator.cs
@@ -0,0 +1,48 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
+{
+ /**
+ * Interface define calculators of K values for DSA/ECDSA.
+ */
+ public interface IDsaKCalculator
+ {
+ /**
+ * Return true if this calculator is deterministic, false otherwise.
+ *
+ * @return true if deterministic, otherwise false.
+ */
+ bool IsDeterministic { get; }
+
+ /**
+ * Non-deterministic initialiser.
+ *
+ * @param n the order of the DSA group.
+ * @param random a source of randomness.
+ */
+ void Init(BigInteger n, SecureRandom random);
+
+ /**
+ * Deterministic initialiser.
+ *
+ * @param n the order of the DSA group.
+ * @param d the DSA private value.
+ * @param message the message being signed.
+ */
+ void Init(BigInteger n, BigInteger d, byte[] message);
+
+ /**
+ * Return the next valid value of K.
+ *
+ * @return a K value.
+ */
+ BigInteger NextK();
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/IDsaKCalculator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/IDsaKCalculator.cs.meta
new file mode 100644
index 00000000..c6a65e1e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/IDsaKCalculator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: b6b2ca8e130099946a1565068a5b5929
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Iso9796d2PssSigner.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Iso9796d2PssSigner.cs
new file mode 100644
index 00000000..72469898
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Iso9796d2PssSigner.cs
@@ -0,0 +1,623 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
+{
+ /// ISO9796-2 - mechanism using a hash function with recovery (scheme 2 and 3).
+ ///
+ /// Note: the usual length for the salt is the length of the hash
+ /// function used in bytes.
+ ///
+ public class Iso9796d2PssSigner
+ : ISignerWithRecovery
+ {
+ ///
+ /// Return a reference to the recoveredMessage message.
+ ///
+ /// The full/partial recoveredMessage message.
+ ///
+ public byte[] GetRecoveredMessage()
+ {
+ return recoveredMessage;
+ }
+
+ [Obsolete("Use 'IsoTrailers' instead")]
+ public const int TrailerImplicit = 0xBC;
+ [Obsolete("Use 'IsoTrailers' instead")]
+ public const int TrailerRipeMD160 = 0x31CC;
+ [Obsolete("Use 'IsoTrailers' instead")]
+ public const int TrailerRipeMD128 = 0x32CC;
+ [Obsolete("Use 'IsoTrailers' instead")]
+ public const int TrailerSha1 = 0x33CC;
+ [Obsolete("Use 'IsoTrailers' instead")]
+ public const int TrailerSha256 = 0x34CC;
+ [Obsolete("Use 'IsoTrailers' instead")]
+ public const int TrailerSha512 = 0x35CC;
+ [Obsolete("Use 'IsoTrailers' instead")]
+ public const int TrailerSha384 = 0x36CC;
+ [Obsolete("Use 'IsoTrailers' instead")]
+ public const int TrailerWhirlpool = 0x37CC;
+
+ private IDigest digest;
+ private IAsymmetricBlockCipher cipher;
+
+ private SecureRandom random;
+ private byte[] standardSalt;
+
+ private int hLen;
+ private int trailer;
+ private int keyBits;
+ private byte[] block;
+ private byte[] mBuf;
+ private int messageLength;
+ private readonly int saltLength;
+ private bool fullMessage;
+ private byte[] recoveredMessage;
+
+ private byte[] preSig;
+ private byte[] preBlock;
+ private int preMStart;
+ private int preTLength;
+
+ ///
+ /// Generate a signer with either implicit or explicit trailers for ISO9796-2, scheme 2 or 3.
+ ///
+ /// base cipher to use for signature creation/verification
+ /// digest to use.
+ /// length of salt in bytes.
+ /// whether or not the trailer is implicit or gives the hash.
+ public Iso9796d2PssSigner(
+ IAsymmetricBlockCipher cipher,
+ IDigest digest,
+ int saltLength,
+ bool isImplicit)
+ {
+ this.cipher = cipher;
+ this.digest = digest;
+ this.hLen = digest.GetDigestSize();
+ this.saltLength = saltLength;
+
+ if (isImplicit)
+ {
+ trailer = IsoTrailers.TRAILER_IMPLICIT;
+ }
+ else if (IsoTrailers.NoTrailerAvailable(digest))
+ {
+ throw new ArgumentException("no valid trailer", "digest");
+ }
+ else
+ {
+ trailer = IsoTrailers.GetTrailer(digest);
+ }
+ }
+
+ /// Constructor for a signer with an explicit digest trailer.
+ ///
+ ///
+ /// cipher to use.
+ ///
+ /// digest to sign with.
+ ///
+ /// length of salt in bytes.
+ ///
+ public Iso9796d2PssSigner(
+ IAsymmetricBlockCipher cipher,
+ IDigest digest,
+ int saltLength)
+ : this(cipher, digest, saltLength, false)
+ {
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return digest.AlgorithmName + "with" + "ISO9796-2S2"; }
+ }
+
+ /// Initialise the signer.
+ /// true if for signing, false if for verification.
+ /// parameters for signature generation/verification. If the
+ /// parameters are for generation they should be a ParametersWithRandom,
+ /// a ParametersWithSalt, or just an RsaKeyParameters object. If RsaKeyParameters
+ /// are passed in a SecureRandom will be created.
+ ///
+ /// if wrong parameter type or a fixed
+ /// salt is passed in which is the wrong length.
+ ///
+ public virtual void Init(
+ bool forSigning,
+ ICipherParameters parameters)
+ {
+ RsaKeyParameters kParam;
+ if (parameters is ParametersWithRandom)
+ {
+ ParametersWithRandom p = (ParametersWithRandom) parameters;
+
+ kParam = (RsaKeyParameters) p.Parameters;
+
+ if (forSigning)
+ {
+ random = p.Random;
+ }
+ }
+ else if (parameters is ParametersWithSalt)
+ {
+ if (!forSigning)
+ throw new ArgumentException("ParametersWithSalt only valid for signing", "parameters");
+
+ ParametersWithSalt p = (ParametersWithSalt) parameters;
+
+ kParam = (RsaKeyParameters) p.Parameters;
+ standardSalt = p.GetSalt();
+
+ if (standardSalt.Length != saltLength)
+ throw new ArgumentException("Fixed salt is of wrong length");
+ }
+ else
+ {
+ kParam = (RsaKeyParameters) parameters;
+
+ if (forSigning)
+ {
+ random = new SecureRandom();
+ }
+ }
+
+ cipher.Init(forSigning, kParam);
+
+ keyBits = kParam.Modulus.BitLength;
+
+ block = new byte[(keyBits + 7) / 8];
+
+ if (trailer == IsoTrailers.TRAILER_IMPLICIT)
+ {
+ mBuf = new byte[block.Length - digest.GetDigestSize() - saltLength - 1 - 1];
+ }
+ else
+ {
+ mBuf = new byte[block.Length - digest.GetDigestSize() - saltLength - 1 - 2];
+ }
+
+ Reset();
+ }
+
+ /// compare two byte arrays - constant time.
+ private bool IsSameAs(byte[] a, byte[] b)
+ {
+ if (messageLength != b.Length)
+ {
+ return false;
+ }
+
+ bool isOkay = true;
+
+ for (int i = 0; i != b.Length; i++)
+ {
+ if (a[i] != b[i])
+ {
+ isOkay = false;
+ }
+ }
+
+ return isOkay;
+ }
+
+ /// clear possible sensitive data
+ private void ClearBlock(
+ byte[] block)
+ {
+ Array.Clear(block, 0, block.Length);
+ }
+
+ public virtual void UpdateWithRecoveredMessage(
+ byte[] signature)
+ {
+ byte[] block = cipher.ProcessBlock(signature, 0, signature.Length);
+
+ //
+ // adjust block size for leading zeroes if necessary
+ //
+ if (block.Length < (keyBits + 7) / 8)
+ {
+ byte[] tmp = new byte[(keyBits + 7) / 8];
+
+ Array.Copy(block, 0, tmp, tmp.Length - block.Length, block.Length);
+ ClearBlock(block);
+ block = tmp;
+ }
+
+ int tLength;
+
+ if (((block[block.Length - 1] & 0xFF) ^ 0xBC) == 0)
+ {
+ tLength = 1;
+ }
+ else
+ {
+ int sigTrail = ((block[block.Length - 2] & 0xFF) << 8) | (block[block.Length - 1] & 0xFF);
+
+ if (IsoTrailers.NoTrailerAvailable(digest))
+ throw new ArgumentException("unrecognised hash in signature");
+
+ if (sigTrail != IsoTrailers.GetTrailer(digest))
+ throw new InvalidOperationException("signer initialised with wrong digest for trailer " + sigTrail);
+
+ tLength = 2;
+ }
+
+ //
+ // calculate H(m2)
+ //
+ byte[] m2Hash = new byte[hLen];
+ digest.DoFinal(m2Hash, 0);
+
+ //
+ // remove the mask
+ //
+ byte[] dbMask = MaskGeneratorFunction1(block, block.Length - hLen - tLength, hLen, block.Length - hLen - tLength);
+ for (int i = 0; i != dbMask.Length; i++)
+ {
+ block[i] ^= dbMask[i];
+ }
+
+ block[0] &= 0x7f;
+
+ //
+ // find out how much padding we've got
+ //
+ int mStart = 0;
+
+ while (mStart < block.Length)
+ {
+ if (block[mStart++] == 0x01)
+ break;
+ }
+
+ if (mStart >= block.Length)
+ {
+ ClearBlock(block);
+ }
+
+ fullMessage = (mStart > 1);
+
+ recoveredMessage = new byte[dbMask.Length - mStart - saltLength];
+
+ Array.Copy(block, mStart, recoveredMessage, 0, recoveredMessage.Length);
+ recoveredMessage.CopyTo(mBuf, 0);
+
+ preSig = signature;
+ preBlock = block;
+ preMStart = mStart;
+ preTLength = tLength;
+ }
+
+ /// update the internal digest with the byte b
+ public virtual void Update(
+ byte input)
+ {
+ if (preSig == null && messageLength < mBuf.Length)
+ {
+ mBuf[messageLength++] = input;
+ }
+ else
+ {
+ digest.Update(input);
+ }
+ }
+
+ /// update the internal digest with the byte array in
+ public virtual void BlockUpdate(
+ byte[] input,
+ int inOff,
+ int length)
+ {
+ if (preSig == null)
+ {
+ while (length > 0 && messageLength < mBuf.Length)
+ {
+ this.Update(input[inOff]);
+ inOff++;
+ length--;
+ }
+ }
+
+ if (length > 0)
+ {
+ digest.BlockUpdate(input, inOff, length);
+ }
+ }
+
+ /// reset the internal state
+ public virtual void Reset()
+ {
+ digest.Reset();
+ messageLength = 0;
+ if (mBuf != null)
+ {
+ ClearBlock(mBuf);
+ }
+ if (recoveredMessage != null)
+ {
+ ClearBlock(recoveredMessage);
+ recoveredMessage = null;
+ }
+ fullMessage = false;
+ if (preSig != null)
+ {
+ preSig = null;
+ ClearBlock(preBlock);
+ preBlock = null;
+ }
+ }
+
+ /// Generate a signature for the loaded message using the key we were
+ /// initialised with.
+ ///
+ public virtual byte[] GenerateSignature()
+ {
+ int digSize = digest.GetDigestSize();
+ byte[] m2Hash = new byte[digSize];
+ digest.DoFinal(m2Hash, 0);
+
+ byte[] C = new byte[8];
+ LtoOSP(messageLength * 8, C);
+
+ digest.BlockUpdate(C, 0, C.Length);
+ digest.BlockUpdate(mBuf, 0, messageLength);
+ digest.BlockUpdate(m2Hash, 0, m2Hash.Length);
+
+ byte[] salt;
+ if (standardSalt != null)
+ {
+ salt = standardSalt;
+ }
+ else
+ {
+ salt = new byte[saltLength];
+ random.NextBytes(salt);
+ }
+
+ digest.BlockUpdate(salt, 0, salt.Length);
+
+ byte[] hash = new byte[digest.GetDigestSize()];
+ digest.DoFinal(hash, 0);
+
+ int tLength = 2;
+ if (trailer == IsoTrailers.TRAILER_IMPLICIT)
+ {
+ tLength = 1;
+ }
+
+ int off = block.Length - messageLength - salt.Length - hLen - tLength - 1;
+
+ block[off] = (byte) (0x01);
+
+ Array.Copy(mBuf, 0, block, off + 1, messageLength);
+ Array.Copy(salt, 0, block, off + 1 + messageLength, salt.Length);
+
+ byte[] dbMask = MaskGeneratorFunction1(hash, 0, hash.Length, block.Length - hLen - tLength);
+ for (int i = 0; i != dbMask.Length; i++)
+ {
+ block[i] ^= dbMask[i];
+ }
+
+ Array.Copy(hash, 0, block, block.Length - hLen - tLength, hLen);
+
+ if (trailer == IsoTrailers.TRAILER_IMPLICIT)
+ {
+ block[block.Length - 1] = (byte)IsoTrailers.TRAILER_IMPLICIT;
+ }
+ else
+ {
+ block[block.Length - 2] = (byte) ((uint)trailer >> 8);
+ block[block.Length - 1] = (byte) trailer;
+ }
+
+ block[0] &= (byte) (0x7f);
+
+ byte[] b = cipher.ProcessBlock(block, 0, block.Length);
+
+ ClearBlock(mBuf);
+ ClearBlock(block);
+ messageLength = 0;
+
+ return b;
+ }
+
+ /// return true if the signature represents a ISO9796-2 signature
+ /// for the passed in message.
+ ///
+ public virtual bool VerifySignature(
+ byte[] signature)
+ {
+ //
+ // calculate H(m2)
+ //
+ byte[] m2Hash = new byte[hLen];
+ digest.DoFinal(m2Hash, 0);
+
+ byte[] block;
+ int tLength;
+ int mStart = 0;
+
+ if (preSig == null)
+ {
+ try
+ {
+ UpdateWithRecoveredMessage(signature);
+ }
+ catch (Exception)
+ {
+ return false;
+ }
+ }
+ else
+ {
+ if (!Arrays.AreEqual(preSig, signature))
+ {
+ throw new InvalidOperationException("UpdateWithRecoveredMessage called on different signature");
+ }
+ }
+
+ block = preBlock;
+ mStart = preMStart;
+ tLength = preTLength;
+
+ preSig = null;
+ preBlock = null;
+
+ //
+ // check the hashes
+ //
+ byte[] C = new byte[8];
+ LtoOSP(recoveredMessage.Length * 8, C);
+
+ digest.BlockUpdate(C, 0, C.Length);
+
+ if (recoveredMessage.Length != 0)
+ {
+ digest.BlockUpdate(recoveredMessage, 0, recoveredMessage.Length);
+ }
+
+ digest.BlockUpdate(m2Hash, 0, m2Hash.Length);
+
+ // Update for the salt
+ if (standardSalt != null)
+ {
+ digest.BlockUpdate(standardSalt, 0, standardSalt.Length);
+ }
+ else
+ {
+ digest.BlockUpdate(block, mStart + recoveredMessage.Length, saltLength);
+ }
+
+ byte[] hash = new byte[digest.GetDigestSize()];
+ digest.DoFinal(hash, 0);
+
+ int off = block.Length - tLength - hash.Length;
+
+ bool isOkay = true;
+
+ for (int i = 0; i != hash.Length; i++)
+ {
+ if (hash[i] != block[off + i])
+ {
+ isOkay = false;
+ }
+ }
+
+ ClearBlock(block);
+ ClearBlock(hash);
+
+ if (!isOkay)
+ {
+ fullMessage = false;
+ messageLength = 0;
+ ClearBlock(recoveredMessage);
+ return false;
+ }
+
+ //
+ // if they've input a message check what we've recovered against
+ // what was input.
+ //
+ if (messageLength != 0)
+ {
+ if (!IsSameAs(mBuf, recoveredMessage))
+ {
+ messageLength = 0;
+ ClearBlock(mBuf);
+ return false;
+ }
+ }
+
+ messageLength = 0;
+
+ ClearBlock(mBuf);
+ return true;
+ }
+
+ ///
+ /// Return true if the full message was recoveredMessage.
+ ///
+ /// true on full message recovery, false otherwise, or if not sure.
+ ///
+ public virtual bool HasFullMessage()
+ {
+ return fullMessage;
+ }
+
+ /// int to octet string.
+ /// int to octet string.
+ private void ItoOSP(
+ int i,
+ byte[] sp)
+ {
+ sp[0] = (byte)((uint)i >> 24);
+ sp[1] = (byte)((uint)i >> 16);
+ sp[2] = (byte)((uint)i >> 8);
+ sp[3] = (byte)((uint)i >> 0);
+ }
+
+ /// long to octet string.
+ private void LtoOSP(long l, byte[] sp)
+ {
+ sp[0] = (byte)((ulong)l >> 56);
+ sp[1] = (byte)((ulong)l >> 48);
+ sp[2] = (byte)((ulong)l >> 40);
+ sp[3] = (byte)((ulong)l >> 32);
+ sp[4] = (byte)((ulong)l >> 24);
+ sp[5] = (byte)((ulong)l >> 16);
+ sp[6] = (byte)((ulong)l >> 8);
+ sp[7] = (byte)((ulong)l >> 0);
+ }
+
+ /// mask generator function, as described in Pkcs1v2.
+ private byte[] MaskGeneratorFunction1(
+ byte[] Z,
+ int zOff,
+ int zLen,
+ int length)
+ {
+ byte[] mask = new byte[length];
+ byte[] hashBuf = new byte[hLen];
+ byte[] C = new byte[4];
+ int counter = 0;
+
+ digest.Reset();
+
+ do
+ {
+ ItoOSP(counter, C);
+
+ digest.BlockUpdate(Z, zOff, zLen);
+ digest.BlockUpdate(C, 0, C.Length);
+ digest.DoFinal(hashBuf, 0);
+
+ Array.Copy(hashBuf, 0, mask, counter * hLen, hLen);
+ }
+ while (++counter < (length / hLen));
+
+ if ((counter * hLen) < length)
+ {
+ ItoOSP(counter, C);
+
+ digest.BlockUpdate(Z, zOff, zLen);
+ digest.BlockUpdate(C, 0, C.Length);
+ digest.DoFinal(hashBuf, 0);
+
+ Array.Copy(hashBuf, 0, mask, counter * hLen, mask.Length - (counter * hLen));
+ }
+
+ return mask;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Iso9796d2PssSigner.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Iso9796d2PssSigner.cs.meta
new file mode 100644
index 00000000..c323cdb0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Iso9796d2PssSigner.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: d99002462363d2048b142db69714f6ee
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Iso9796d2Signer.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Iso9796d2Signer.cs
new file mode 100644
index 00000000..db5ed7b0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Iso9796d2Signer.cs
@@ -0,0 +1,560 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
+{
+ /// ISO9796-2 - mechanism using a hash function with recovery (scheme 1)
+ public class Iso9796d2Signer : ISignerWithRecovery
+ {
+ ///
+ /// Return a reference to the recoveredMessage message.
+ ///
+ /// The full/partial recoveredMessage message.
+ ///
+ public byte[] GetRecoveredMessage()
+ {
+ return recoveredMessage;
+ }
+
+ [Obsolete("Use 'IsoTrailers' instead")]
+ public const int TrailerImplicit = 0xBC;
+ [Obsolete("Use 'IsoTrailers' instead")]
+ public const int TrailerRipeMD160 = 0x31CC;
+ [Obsolete("Use 'IsoTrailers' instead")]
+ public const int TrailerRipeMD128 = 0x32CC;
+ [Obsolete("Use 'IsoTrailers' instead")]
+ public const int TrailerSha1 = 0x33CC;
+ [Obsolete("Use 'IsoTrailers' instead")]
+ public const int TrailerSha256 = 0x34CC;
+ [Obsolete("Use 'IsoTrailers' instead")]
+ public const int TrailerSha512 = 0x35CC;
+ [Obsolete("Use 'IsoTrailers' instead")]
+ public const int TrailerSha384 = 0x36CC;
+ [Obsolete("Use 'IsoTrailers' instead")]
+ public const int TrailerWhirlpool = 0x37CC;
+
+ private IDigest digest;
+ private IAsymmetricBlockCipher cipher;
+
+ private int trailer;
+ private int keyBits;
+ private byte[] block;
+ private byte[] mBuf;
+ private int messageLength;
+ private bool fullMessage;
+ private byte[] recoveredMessage;
+
+ private byte[] preSig;
+ private byte[] preBlock;
+
+ ///
+ /// Generate a signer with either implicit or explicit trailers for ISO9796-2.
+ ///
+ /// base cipher to use for signature creation/verification
+ /// digest to use.
+ /// whether or not the trailer is implicit or gives the hash.
+ public Iso9796d2Signer(
+ IAsymmetricBlockCipher cipher,
+ IDigest digest,
+ bool isImplicit)
+ {
+ this.cipher = cipher;
+ this.digest = digest;
+
+ if (isImplicit)
+ {
+ trailer = IsoTrailers.TRAILER_IMPLICIT;
+ }
+ else if (IsoTrailers.NoTrailerAvailable(digest))
+ {
+ throw new ArgumentException("no valid trailer", "digest");
+ }
+ else
+ {
+ trailer = IsoTrailers.GetTrailer(digest);
+ }
+ }
+
+ /// Constructor for a signer with an explicit digest trailer.
+ ///
+ ///
+ /// cipher to use.
+ ///
+ /// digest to sign with.
+ ///
+ public Iso9796d2Signer(IAsymmetricBlockCipher cipher, IDigest digest)
+ : this(cipher, digest, false)
+ {
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return digest.AlgorithmName + "with" + "ISO9796-2S1"; }
+ }
+
+ public virtual void Init(bool forSigning, ICipherParameters parameters)
+ {
+ RsaKeyParameters kParam = (RsaKeyParameters) parameters;
+
+ cipher.Init(forSigning, kParam);
+
+ keyBits = kParam.Modulus.BitLength;
+
+ block = new byte[(keyBits + 7) / 8];
+ if (trailer == IsoTrailers.TRAILER_IMPLICIT)
+ {
+ mBuf = new byte[block.Length - digest.GetDigestSize() - 2];
+ }
+ else
+ {
+ mBuf = new byte[block.Length - digest.GetDigestSize() - 3];
+ }
+
+ Reset();
+ }
+
+ /// compare two byte arrays - constant time.
+ private bool IsSameAs(byte[] a, byte[] b)
+ {
+ int checkLen;
+ if (messageLength > mBuf.Length)
+ {
+ if (mBuf.Length > b.Length)
+ {
+ return false;
+ }
+
+ checkLen = mBuf.Length;
+ }
+ else
+ {
+ if (messageLength != b.Length)
+ {
+ return false;
+ }
+
+ checkLen = b.Length;
+ }
+
+ bool isOkay = true;
+
+ for (int i = 0; i != checkLen; i++)
+ {
+ if (a[i] != b[i])
+ {
+ isOkay = false;
+ }
+ }
+
+ return isOkay;
+ }
+
+ /// clear possible sensitive data
+ private void ClearBlock(
+ byte[] block)
+ {
+ Array.Clear(block, 0, block.Length);
+ }
+
+ public virtual void UpdateWithRecoveredMessage(
+ byte[] signature)
+ {
+ byte[] block = cipher.ProcessBlock(signature, 0, signature.Length);
+
+ if (((block[0] & 0xC0) ^ 0x40) != 0)
+ throw new InvalidCipherTextException("malformed signature");
+
+ if (((block[block.Length - 1] & 0xF) ^ 0xC) != 0)
+ throw new InvalidCipherTextException("malformed signature");
+
+ int delta = 0;
+
+ if (((block[block.Length - 1] & 0xFF) ^ 0xBC) == 0)
+ {
+ delta = 1;
+ }
+ else
+ {
+ int sigTrail = ((block[block.Length - 2] & 0xFF) << 8) | (block[block.Length - 1] & 0xFF);
+
+ if (IsoTrailers.NoTrailerAvailable(digest))
+ throw new ArgumentException("unrecognised hash in signature");
+
+ if (sigTrail != IsoTrailers.GetTrailer(digest))
+ throw new InvalidOperationException("signer initialised with wrong digest for trailer " + sigTrail);
+
+ delta = 2;
+ }
+
+ //
+ // find out how much padding we've got
+ //
+ int mStart = 0;
+
+ for (mStart = 0; mStart != block.Length; mStart++)
+ {
+ if (((block[mStart] & 0x0f) ^ 0x0a) == 0)
+ break;
+ }
+
+ mStart++;
+
+ int off = block.Length - delta - digest.GetDigestSize();
+
+ //
+ // there must be at least one byte of message string
+ //
+ if ((off - mStart) <= 0)
+ throw new InvalidCipherTextException("malformed block");
+
+ //
+ // if we contain the whole message as well, check the hash of that.
+ //
+ if ((block[0] & 0x20) == 0)
+ {
+ fullMessage = true;
+
+ recoveredMessage = new byte[off - mStart];
+ Array.Copy(block, mStart, recoveredMessage, 0, recoveredMessage.Length);
+ }
+ else
+ {
+ fullMessage = false;
+
+ recoveredMessage = new byte[off - mStart];
+ Array.Copy(block, mStart, recoveredMessage, 0, recoveredMessage.Length);
+ }
+
+ preSig = signature;
+ preBlock = block;
+
+ digest.BlockUpdate(recoveredMessage, 0, recoveredMessage.Length);
+ messageLength = recoveredMessage.Length;
+ recoveredMessage.CopyTo(mBuf, 0);
+ }
+
+ /// update the internal digest with the byte b
+ public virtual void Update(
+ byte input)
+ {
+ digest.Update(input);
+
+ if (messageLength < mBuf.Length)
+ {
+ mBuf[messageLength] = input;
+ }
+
+ messageLength++;
+ }
+
+ /// update the internal digest with the byte array in
+ public virtual void BlockUpdate(
+ byte[] input,
+ int inOff,
+ int length)
+ {
+ while (length > 0 && messageLength < mBuf.Length)
+ {
+ //for (int i = 0; i < length && (i + messageLength) < mBuf.Length; i++)
+ //{
+ // mBuf[messageLength + i] = input[inOff + i];
+ //}
+ this.Update(input[inOff]);
+ inOff++;
+ length--;
+ }
+
+ digest.BlockUpdate(input, inOff, length);
+ messageLength += length;
+ }
+
+ /// reset the internal state
+ public virtual void Reset()
+ {
+ digest.Reset();
+ messageLength = 0;
+ ClearBlock(mBuf);
+
+ if (recoveredMessage != null)
+ {
+ ClearBlock(recoveredMessage);
+ }
+
+ recoveredMessage = null;
+ fullMessage = false;
+
+ if (preSig != null)
+ {
+ preSig = null;
+ ClearBlock(preBlock);
+ preBlock = null;
+ }
+ }
+
+ /// Generate a signature for the loaded message using the key we were
+ /// initialised with.
+ ///
+ public virtual byte[] GenerateSignature()
+ {
+ int digSize = digest.GetDigestSize();
+
+ int t = 0;
+ int delta = 0;
+
+ if (trailer == IsoTrailers.TRAILER_IMPLICIT)
+ {
+ t = 8;
+ delta = block.Length - digSize - 1;
+ digest.DoFinal(block, delta);
+ block[block.Length - 1] = (byte)IsoTrailers.TRAILER_IMPLICIT;
+ }
+ else
+ {
+ t = 16;
+ delta = block.Length - digSize - 2;
+ digest.DoFinal(block, delta);
+ block[block.Length - 2] = (byte) ((uint)trailer >> 8);
+ block[block.Length - 1] = (byte) trailer;
+ }
+
+ byte header = 0;
+ int x = (digSize + messageLength) * 8 + t + 4 - keyBits;
+
+ if (x > 0)
+ {
+ int mR = messageLength - ((x + 7) / 8);
+ header = (byte) (0x60);
+
+ delta -= mR;
+
+ Array.Copy(mBuf, 0, block, delta, mR);
+ }
+ else
+ {
+ header = (byte) (0x40);
+ delta -= messageLength;
+
+ Array.Copy(mBuf, 0, block, delta, messageLength);
+ }
+
+ if ((delta - 1) > 0)
+ {
+ for (int i = delta - 1; i != 0; i--)
+ {
+ block[i] = (byte) 0xbb;
+ }
+ block[delta - 1] ^= (byte) 0x01;
+ block[0] = (byte) 0x0b;
+ block[0] |= header;
+ }
+ else
+ {
+ block[0] = (byte) 0x0a;
+ block[0] |= header;
+ }
+
+ byte[] b = cipher.ProcessBlock(block, 0, block.Length);
+
+ messageLength = 0;
+
+ ClearBlock(mBuf);
+ ClearBlock(block);
+
+ return b;
+ }
+
+ /// return true if the signature represents a ISO9796-2 signature
+ /// for the passed in message.
+ ///
+ public virtual bool VerifySignature(byte[] signature)
+ {
+ byte[] block;
+
+ if (preSig == null)
+ {
+ try
+ {
+ block = cipher.ProcessBlock(signature, 0, signature.Length);
+ }
+ catch (Exception)
+ {
+ return false;
+ }
+ }
+ else
+ {
+ if (!Arrays.AreEqual(preSig, signature))
+ throw new InvalidOperationException("updateWithRecoveredMessage called on different signature");
+
+ block = preBlock;
+
+ preSig = null;
+ preBlock = null;
+ }
+
+ if (((block[0] & 0xC0) ^ 0x40) != 0)
+ return ReturnFalse(block);
+
+ if (((block[block.Length - 1] & 0xF) ^ 0xC) != 0)
+ return ReturnFalse(block);
+
+ int delta = 0;
+
+ if (((block[block.Length - 1] & 0xFF) ^ 0xBC) == 0)
+ {
+ delta = 1;
+ }
+ else
+ {
+ int sigTrail = ((block[block.Length - 2] & 0xFF) << 8) | (block[block.Length - 1] & 0xFF);
+
+ if (IsoTrailers.NoTrailerAvailable(digest))
+ throw new ArgumentException("unrecognised hash in signature");
+
+ if (sigTrail != IsoTrailers.GetTrailer(digest))
+ throw new InvalidOperationException("signer initialised with wrong digest for trailer " + sigTrail);
+
+ delta = 2;
+ }
+
+ //
+ // find out how much padding we've got
+ //
+ int mStart = 0;
+ for (; mStart != block.Length; mStart++)
+ {
+ if (((block[mStart] & 0x0f) ^ 0x0a) == 0)
+ {
+ break;
+ }
+ }
+
+ mStart++;
+
+ //
+ // check the hashes
+ //
+ byte[] hash = new byte[digest.GetDigestSize()];
+
+ int off = block.Length - delta - hash.Length;
+
+ //
+ // there must be at least one byte of message string
+ //
+ if ((off - mStart) <= 0)
+ {
+ return ReturnFalse(block);
+ }
+
+ //
+ // if we contain the whole message as well, check the hash of that.
+ //
+ if ((block[0] & 0x20) == 0)
+ {
+ fullMessage = true;
+
+ // check right number of bytes passed in.
+ if (messageLength > off - mStart)
+ {
+ return ReturnFalse(block);
+ }
+
+ digest.Reset();
+ digest.BlockUpdate(block, mStart, off - mStart);
+ digest.DoFinal(hash, 0);
+
+ bool isOkay = true;
+
+ for (int i = 0; i != hash.Length; i++)
+ {
+ block[off + i] ^= hash[i];
+ if (block[off + i] != 0)
+ {
+ isOkay = false;
+ }
+ }
+
+ if (!isOkay)
+ {
+ return ReturnFalse(block);
+ }
+
+ recoveredMessage = new byte[off - mStart];
+ Array.Copy(block, mStart, recoveredMessage, 0, recoveredMessage.Length);
+ }
+ else
+ {
+ fullMessage = false;
+
+ digest.DoFinal(hash, 0);
+
+ bool isOkay = true;
+
+ for (int i = 0; i != hash.Length; i++)
+ {
+ block[off + i] ^= hash[i];
+ if (block[off + i] != 0)
+ {
+ isOkay = false;
+ }
+ }
+
+ if (!isOkay)
+ {
+ return ReturnFalse(block);
+ }
+
+ recoveredMessage = new byte[off - mStart];
+ Array.Copy(block, mStart, recoveredMessage, 0, recoveredMessage.Length);
+ }
+
+ //
+ // if they've input a message check what we've recovered against
+ // what was input.
+ //
+ if (messageLength != 0)
+ {
+ if (!IsSameAs(mBuf, recoveredMessage))
+ {
+ return ReturnFalse(block);
+ }
+ }
+
+ ClearBlock(mBuf);
+ ClearBlock(block);
+
+ messageLength = 0;
+
+ return true;
+ }
+
+ private bool ReturnFalse(byte[] block)
+ {
+ messageLength = 0;
+
+ ClearBlock(mBuf);
+ ClearBlock(block);
+
+ return false;
+ }
+
+ ///
+ /// Return true if the full message was recoveredMessage.
+ ///
+ /// true on full message recovery, false otherwise.
+ ///
+ public virtual bool HasFullMessage()
+ {
+ return fullMessage;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Iso9796d2Signer.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Iso9796d2Signer.cs.meta
new file mode 100644
index 00000000..bebac84e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/Iso9796d2Signer.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 87ac94cff478bb34ba55e541d2971b29
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/IsoTrailers.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/IsoTrailers.cs
new file mode 100644
index 00000000..b388c2a1
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/IsoTrailers.cs
@@ -0,0 +1,61 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
+{
+ public class IsoTrailers
+ {
+ public const int TRAILER_IMPLICIT = 0xBC;
+ public const int TRAILER_RIPEMD160 = 0x31CC;
+ public const int TRAILER_RIPEMD128 = 0x32CC;
+ public const int TRAILER_SHA1 = 0x33CC;
+ public const int TRAILER_SHA256 = 0x34CC;
+ public const int TRAILER_SHA512 = 0x35CC;
+ public const int TRAILER_SHA384 = 0x36CC;
+ public const int TRAILER_WHIRLPOOL = 0x37CC;
+ public const int TRAILER_SHA224 = 0x38CC;
+ public const int TRAILER_SHA512_224 = 0x39CC;
+ public const int TRAILER_SHA512_256 = 0x40CC;
+
+ private static IDictionary CreateTrailerMap()
+ {
+ IDictionary trailers = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+
+ trailers.Add("RIPEMD128", TRAILER_RIPEMD128);
+ trailers.Add("RIPEMD160", TRAILER_RIPEMD160);
+
+ trailers.Add("SHA-1", TRAILER_SHA1);
+ trailers.Add("SHA-224", TRAILER_SHA224);
+ trailers.Add("SHA-256", TRAILER_SHA256);
+ trailers.Add("SHA-384", TRAILER_SHA384);
+ trailers.Add("SHA-512", TRAILER_SHA512);
+ trailers.Add("SHA-512/224", TRAILER_SHA512_224);
+ trailers.Add("SHA-512/256", TRAILER_SHA512_256);
+
+ trailers.Add("Whirlpool", TRAILER_WHIRLPOOL);
+
+ return CollectionUtilities.ReadOnly(trailers);
+ }
+
+ // IDictionary is (string -> Int32)
+ private static readonly IDictionary trailerMap = CreateTrailerMap();
+
+ public static int GetTrailer(IDigest digest)
+ {
+ return (int)trailerMap[digest.AlgorithmName];
+ }
+
+ public static bool NoTrailerAvailable(IDigest digest)
+ {
+ return !trailerMap.Contains(digest.AlgorithmName);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/IsoTrailers.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/IsoTrailers.cs.meta
new file mode 100644
index 00000000..89eb253f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/IsoTrailers.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a5fd009acb42ef44a8b900072b16221b
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/PlainDsaEncoding.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/PlainDsaEncoding.cs
new file mode 100644
index 00000000..7264d050
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/PlainDsaEncoding.cs
@@ -0,0 +1,62 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
+{
+ public class PlainDsaEncoding
+ : IDsaEncoding
+ {
+ public static readonly PlainDsaEncoding Instance = new PlainDsaEncoding();
+
+ public virtual BigInteger[] Decode(BigInteger n, byte[] encoding)
+ {
+ int valueLength = BigIntegers.GetUnsignedByteLength(n);
+ if (encoding.Length != valueLength * 2)
+ throw new ArgumentException("Encoding has incorrect length", "encoding");
+
+ return new BigInteger[] {
+ DecodeValue(n, encoding, 0, valueLength),
+ DecodeValue(n, encoding, valueLength, valueLength),
+ };
+ }
+
+ public virtual byte[] Encode(BigInteger n, BigInteger r, BigInteger s)
+ {
+ int valueLength = BigIntegers.GetUnsignedByteLength(n);
+ byte[] result = new byte[valueLength * 2];
+ EncodeValue(n, r, result, 0, valueLength);
+ EncodeValue(n, s, result, valueLength, valueLength);
+ return result;
+ }
+
+ protected virtual BigInteger CheckValue(BigInteger n, BigInteger x)
+ {
+ if (x.SignValue < 0 || x.CompareTo(n) >= 0)
+ throw new ArgumentException("Value out of range", "x");
+
+ return x;
+ }
+
+ protected virtual BigInteger DecodeValue(BigInteger n, byte[] buf, int off, int len)
+ {
+ return CheckValue(n, new BigInteger(1, buf, off, len));
+ }
+
+ protected virtual void EncodeValue(BigInteger n, BigInteger x, byte[] buf, int off, int len)
+ {
+ byte[] bs = CheckValue(n, x).ToByteArrayUnsigned();
+ int bsOff = System.Math.Max(0, bs.Length - len);
+ int bsLen = bs.Length - bsOff;
+
+ int pos = len - bsLen;
+ Arrays.Fill(buf, off, off + pos, 0);
+ Array.Copy(bs, bsOff, buf, off + pos, bsLen);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/PlainDsaEncoding.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/PlainDsaEncoding.cs.meta
new file mode 100644
index 00000000..604749fc
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/PlainDsaEncoding.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: aec988137075c7942a73a6b10ffef83f
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/PssSigner.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/PssSigner.cs
new file mode 100644
index 00000000..aa3296ea
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/PssSigner.cs
@@ -0,0 +1,390 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
+{
+ /// RSA-PSS as described in Pkcs# 1 v 2.1.
+ ///
+ /// Note: the usual value for the salt length is the number of
+ /// bytes in the hash function.
+ ///
+ public class PssSigner
+ : ISigner
+ {
+ public const byte TrailerImplicit = (byte)0xBC;
+
+ private readonly IDigest contentDigest1, contentDigest2;
+ private readonly IDigest mgfDigest;
+ private readonly IAsymmetricBlockCipher cipher;
+
+ private SecureRandom random;
+
+ private int hLen;
+ private int mgfhLen;
+ private int sLen;
+ private bool sSet;
+ private int emBits;
+ private byte[] salt;
+ private byte[] mDash;
+ private byte[] block;
+ private byte trailer;
+
+ public static PssSigner CreateRawSigner(
+ IAsymmetricBlockCipher cipher,
+ IDigest digest)
+ {
+ return new PssSigner(cipher, new NullDigest(), digest, digest, digest.GetDigestSize(), null, TrailerImplicit);
+ }
+
+ public static PssSigner CreateRawSigner(
+ IAsymmetricBlockCipher cipher,
+ IDigest contentDigest,
+ IDigest mgfDigest,
+ int saltLen,
+ byte trailer)
+ {
+ return new PssSigner(cipher, new NullDigest(), contentDigest, mgfDigest, saltLen, null, trailer);
+ }
+
+ public PssSigner(
+ IAsymmetricBlockCipher cipher,
+ IDigest digest)
+ : this(cipher, digest, digest.GetDigestSize())
+ {
+ }
+
+ /// Basic constructor
+ /// the asymmetric cipher to use.
+ /// the digest to use.
+ /// the length of the salt to use (in bytes).
+ public PssSigner(
+ IAsymmetricBlockCipher cipher,
+ IDigest digest,
+ int saltLen)
+ : this(cipher, digest, saltLen, TrailerImplicit)
+ {
+ }
+
+ /// Basic constructor
+ /// the asymmetric cipher to use.
+ /// the digest to use.
+ /// the fixed salt to be used.
+ public PssSigner(
+ IAsymmetricBlockCipher cipher,
+ IDigest digest,
+ byte[] salt)
+ : this(cipher, digest, digest, digest, salt.Length, salt, TrailerImplicit)
+ {
+ }
+
+ public PssSigner(
+ IAsymmetricBlockCipher cipher,
+ IDigest contentDigest,
+ IDigest mgfDigest,
+ int saltLen)
+ : this(cipher, contentDigest, mgfDigest, saltLen, TrailerImplicit)
+ {
+ }
+
+ public PssSigner(
+ IAsymmetricBlockCipher cipher,
+ IDigest contentDigest,
+ IDigest mgfDigest,
+ byte[] salt)
+ : this(cipher, contentDigest, contentDigest, mgfDigest, salt.Length, salt, TrailerImplicit)
+ {
+ }
+
+ public PssSigner(
+ IAsymmetricBlockCipher cipher,
+ IDigest digest,
+ int saltLen,
+ byte trailer)
+ : this(cipher, digest, digest, saltLen, TrailerImplicit)
+ {
+ }
+
+ public PssSigner(
+ IAsymmetricBlockCipher cipher,
+ IDigest contentDigest,
+ IDigest mgfDigest,
+ int saltLen,
+ byte trailer)
+ : this(cipher, contentDigest, contentDigest, mgfDigest, saltLen, null, trailer)
+ {
+ }
+
+ private PssSigner(
+ IAsymmetricBlockCipher cipher,
+ IDigest contentDigest1,
+ IDigest contentDigest2,
+ IDigest mgfDigest,
+ int saltLen,
+ byte[] salt,
+ byte trailer)
+ {
+ this.cipher = cipher;
+ this.contentDigest1 = contentDigest1;
+ this.contentDigest2 = contentDigest2;
+ this.mgfDigest = mgfDigest;
+ this.hLen = contentDigest2.GetDigestSize();
+ this.mgfhLen = mgfDigest.GetDigestSize();
+ this.sLen = saltLen;
+ this.sSet = salt != null;
+ if (sSet)
+ {
+ this.salt = salt;
+ }
+ else
+ {
+ this.salt = new byte[saltLen];
+ }
+ this.mDash = new byte[8 + saltLen + hLen];
+ this.trailer = trailer;
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return mgfDigest.AlgorithmName + "withRSAandMGF1"; }
+ }
+
+ public virtual void Init(
+ bool forSigning,
+ ICipherParameters parameters)
+ {
+ if (parameters is ParametersWithRandom)
+ {
+ ParametersWithRandom p = (ParametersWithRandom) parameters;
+
+ parameters = p.Parameters;
+ random = p.Random;
+ }
+ else
+ {
+ if (forSigning)
+ {
+ random = new SecureRandom();
+ }
+ }
+
+ cipher.Init(forSigning, parameters);
+
+ RsaKeyParameters kParam;
+ if (parameters is RsaBlindingParameters)
+ {
+ kParam = ((RsaBlindingParameters) parameters).PublicKey;
+ }
+ else
+ {
+ kParam = (RsaKeyParameters) parameters;
+ }
+
+ emBits = kParam.Modulus.BitLength - 1;
+
+ if (emBits < (8 * hLen + 8 * sLen + 9))
+ throw new ArgumentException("key too small for specified hash and salt lengths");
+
+ block = new byte[(emBits + 7) / 8];
+ }
+
+ /// clear possible sensitive data
+ private void ClearBlock(
+ byte[] block)
+ {
+ Array.Clear(block, 0, block.Length);
+ }
+
+ /// update the internal digest with the byte b
+ public virtual void Update(
+ byte input)
+ {
+ contentDigest1.Update(input);
+ }
+
+ /// update the internal digest with the byte array in
+ public virtual void BlockUpdate(
+ byte[] input,
+ int inOff,
+ int length)
+ {
+ contentDigest1.BlockUpdate(input, inOff, length);
+ }
+
+ /// reset the internal state
+ public virtual void Reset()
+ {
+ contentDigest1.Reset();
+ }
+
+ /// Generate a signature for the message we've been loaded with using
+ /// the key we were initialised with.
+ ///
+ public virtual byte[] GenerateSignature()
+ {
+ contentDigest1.DoFinal(mDash, mDash.Length - hLen - sLen);
+
+ if (sLen != 0)
+ {
+ if (!sSet)
+ {
+ random.NextBytes(salt);
+ }
+ salt.CopyTo(mDash, mDash.Length - sLen);
+ }
+
+ byte[] h = new byte[hLen];
+
+ contentDigest2.BlockUpdate(mDash, 0, mDash.Length);
+
+ contentDigest2.DoFinal(h, 0);
+
+ block[block.Length - sLen - 1 - hLen - 1] = (byte) (0x01);
+ salt.CopyTo(block, block.Length - sLen - hLen - 1);
+
+ byte[] dbMask = MaskGeneratorFunction1(h, 0, h.Length, block.Length - hLen - 1);
+ for (int i = 0; i != dbMask.Length; i++)
+ {
+ block[i] ^= dbMask[i];
+ }
+
+ block[0] &= (byte) ((0xff >> ((block.Length * 8) - emBits)));
+
+ h.CopyTo(block, block.Length - hLen - 1);
+
+ block[block.Length - 1] = trailer;
+
+ byte[] b = cipher.ProcessBlock(block, 0, block.Length);
+
+ ClearBlock(block);
+
+ return b;
+ }
+
+ /// return true if the internal state represents the signature described
+ /// in the passed in array.
+ ///
+ public virtual bool VerifySignature(
+ byte[] signature)
+ {
+ contentDigest1.DoFinal(mDash, mDash.Length - hLen - sLen);
+
+ byte[] b = cipher.ProcessBlock(signature, 0, signature.Length);
+ b.CopyTo(block, block.Length - b.Length);
+
+ if (block[block.Length - 1] != trailer)
+ {
+ ClearBlock(block);
+ return false;
+ }
+
+ byte[] dbMask = MaskGeneratorFunction1(block, block.Length - hLen - 1, hLen, block.Length - hLen - 1);
+
+ for (int i = 0; i != dbMask.Length; i++)
+ {
+ block[i] ^= dbMask[i];
+ }
+
+ block[0] &= (byte) ((0xff >> ((block.Length * 8) - emBits)));
+
+ for (int i = 0; i != block.Length - hLen - sLen - 2; i++)
+ {
+ if (block[i] != 0)
+ {
+ ClearBlock(block);
+ return false;
+ }
+ }
+
+ if (block[block.Length - hLen - sLen - 2] != 0x01)
+ {
+ ClearBlock(block);
+ return false;
+ }
+
+ if (sSet)
+ {
+ Array.Copy(salt, 0, mDash, mDash.Length - sLen, sLen);
+ }
+ else
+ {
+ Array.Copy(block, block.Length - sLen - hLen - 1, mDash, mDash.Length - sLen, sLen);
+ }
+
+ contentDigest2.BlockUpdate(mDash, 0, mDash.Length);
+ contentDigest2.DoFinal(mDash, mDash.Length - hLen);
+
+ for (int i = block.Length - hLen - 1, j = mDash.Length - hLen; j != mDash.Length; i++, j++)
+ {
+ if ((block[i] ^ mDash[j]) != 0)
+ {
+ ClearBlock(mDash);
+ ClearBlock(block);
+ return false;
+ }
+ }
+
+ ClearBlock(mDash);
+ ClearBlock(block);
+
+ return true;
+ }
+
+ /// int to octet string.
+ private void ItoOSP(
+ int i,
+ byte[] sp)
+ {
+ sp[0] = (byte)((uint) i >> 24);
+ sp[1] = (byte)((uint) i >> 16);
+ sp[2] = (byte)((uint) i >> 8);
+ sp[3] = (byte)((uint) i >> 0);
+ }
+
+ /// mask generator function, as described in Pkcs1v2.
+ private byte[] MaskGeneratorFunction1(
+ byte[] Z,
+ int zOff,
+ int zLen,
+ int length)
+ {
+ byte[] mask = new byte[length];
+ byte[] hashBuf = new byte[mgfhLen];
+ byte[] C = new byte[4];
+ int counter = 0;
+
+ mgfDigest.Reset();
+
+ while (counter < (length / mgfhLen))
+ {
+ ItoOSP(counter, C);
+
+ mgfDigest.BlockUpdate(Z, zOff, zLen);
+ mgfDigest.BlockUpdate(C, 0, C.Length);
+ mgfDigest.DoFinal(hashBuf, 0);
+
+ hashBuf.CopyTo(mask, counter * mgfhLen);
+ ++counter;
+ }
+
+ if ((counter * mgfhLen) < length)
+ {
+ ItoOSP(counter, C);
+
+ mgfDigest.BlockUpdate(Z, zOff, zLen);
+ mgfDigest.BlockUpdate(C, 0, C.Length);
+ mgfDigest.DoFinal(hashBuf, 0);
+
+ Array.Copy(hashBuf, 0, mask, counter * mgfhLen, mask.Length - (counter * mgfhLen));
+ }
+
+ return mask;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/PssSigner.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/PssSigner.cs.meta
new file mode 100644
index 00000000..4ccfb407
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/PssSigner.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 29735d3087c8c97469fcd65a9be64767
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/RandomDsaKCalculator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/RandomDsaKCalculator.cs
new file mode 100644
index 00000000..2597b1b2
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/RandomDsaKCalculator.cs
@@ -0,0 +1,48 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
+{
+ public class RandomDsaKCalculator
+ : IDsaKCalculator
+ {
+ private BigInteger q;
+ private SecureRandom random;
+
+ public virtual bool IsDeterministic
+ {
+ get { return false; }
+ }
+
+ public virtual void Init(BigInteger n, SecureRandom random)
+ {
+ this.q = n;
+ this.random = random;
+ }
+
+ public virtual void Init(BigInteger n, BigInteger d, byte[] message)
+ {
+ throw new InvalidOperationException("Operation not supported");
+ }
+
+ public virtual BigInteger NextK()
+ {
+ int qBitLength = q.BitLength;
+
+ BigInteger k;
+ do
+ {
+ k = new BigInteger(qBitLength, random);
+ }
+ while (k.SignValue < 1 || k.CompareTo(q) >= 0);
+
+ return k;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/RandomDsaKCalculator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/RandomDsaKCalculator.cs.meta
new file mode 100644
index 00000000..3d80dd41
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/RandomDsaKCalculator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c1bb646c95a66c04787462b6a62bd3cc
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/RsaDigestSigner.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/RsaDigestSigner.cs
new file mode 100644
index 00000000..cb96abb9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/RsaDigestSigner.cs
@@ -0,0 +1,237 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.TeleTrust;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Encodings;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
+{
+ public class RsaDigestSigner
+ : ISigner
+ {
+ private readonly IAsymmetricBlockCipher rsaEngine;
+ private readonly AlgorithmIdentifier algId;
+ private readonly IDigest digest;
+ private bool forSigning;
+
+ private static readonly IDictionary oidMap = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+
+ ///
+ /// Load oid table.
+ ///
+ static RsaDigestSigner()
+ {
+ oidMap["RIPEMD128"] = TeleTrusTObjectIdentifiers.RipeMD128;
+ oidMap["RIPEMD160"] = TeleTrusTObjectIdentifiers.RipeMD160;
+ oidMap["RIPEMD256"] = TeleTrusTObjectIdentifiers.RipeMD256;
+
+ oidMap["SHA-1"] = X509ObjectIdentifiers.IdSha1;
+ oidMap["SHA-224"] = NistObjectIdentifiers.IdSha224;
+ oidMap["SHA-256"] = NistObjectIdentifiers.IdSha256;
+ oidMap["SHA-384"] = NistObjectIdentifiers.IdSha384;
+ oidMap["SHA-512"] = NistObjectIdentifiers.IdSha512;
+
+ oidMap["MD2"] = PkcsObjectIdentifiers.MD2;
+ oidMap["MD4"] = PkcsObjectIdentifiers.MD4;
+ oidMap["MD5"] = PkcsObjectIdentifiers.MD5;
+ }
+
+ public RsaDigestSigner(IDigest digest)
+ : this(digest, (DerObjectIdentifier)oidMap[digest.AlgorithmName])
+ {
+ }
+
+ public RsaDigestSigner(IDigest digest, DerObjectIdentifier digestOid)
+ : this(digest, new AlgorithmIdentifier(digestOid, DerNull.Instance))
+ {
+ }
+
+ public RsaDigestSigner(IDigest digest, AlgorithmIdentifier algId)
+ : this(new RsaCoreEngine(), digest, algId)
+ {
+ }
+
+ public RsaDigestSigner(IRsa rsa, IDigest digest, DerObjectIdentifier digestOid)
+ : this(rsa, digest, new AlgorithmIdentifier(digestOid, DerNull.Instance))
+ {
+ }
+
+ public RsaDigestSigner(IRsa rsa, IDigest digest, AlgorithmIdentifier algId)
+ : this(new RsaBlindedEngine(rsa), digest, algId)
+ {
+ }
+
+ public RsaDigestSigner(IAsymmetricBlockCipher rsaEngine, IDigest digest, AlgorithmIdentifier algId)
+ {
+ this.rsaEngine = new Pkcs1Encoding(rsaEngine);
+ this.digest = digest;
+ this.algId = algId;
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return digest.AlgorithmName + "withRSA"; }
+ }
+
+ /**
+ * Initialise the signer for signing or verification.
+ *
+ * @param forSigning true if for signing, false otherwise
+ * @param param necessary parameters.
+ */
+ public virtual void Init(
+ bool forSigning,
+ ICipherParameters parameters)
+ {
+ this.forSigning = forSigning;
+ AsymmetricKeyParameter k;
+
+ if (parameters is ParametersWithRandom)
+ {
+ k = (AsymmetricKeyParameter)((ParametersWithRandom)parameters).Parameters;
+ }
+ else
+ {
+ k = (AsymmetricKeyParameter)parameters;
+ }
+
+ if (forSigning && !k.IsPrivate)
+ throw new InvalidKeyException("Signing requires private key.");
+
+ if (!forSigning && k.IsPrivate)
+ throw new InvalidKeyException("Verification requires public key.");
+
+ Reset();
+
+ rsaEngine.Init(forSigning, parameters);
+ }
+
+ /**
+ * update the internal digest with the byte b
+ */
+ public virtual void Update(
+ byte input)
+ {
+ digest.Update(input);
+ }
+
+ /**
+ * update the internal digest with the byte array in
+ */
+ public virtual void BlockUpdate(
+ byte[] input,
+ int inOff,
+ int length)
+ {
+ digest.BlockUpdate(input, inOff, length);
+ }
+
+ /**
+ * Generate a signature for the message we've been loaded with using
+ * the key we were initialised with.
+ */
+ public virtual byte[] GenerateSignature()
+ {
+ if (!forSigning)
+ throw new InvalidOperationException("RsaDigestSigner not initialised for signature generation.");
+
+ byte[] hash = new byte[digest.GetDigestSize()];
+ digest.DoFinal(hash, 0);
+
+ byte[] data = DerEncode(hash);
+ return rsaEngine.ProcessBlock(data, 0, data.Length);
+ }
+
+ /**
+ * return true if the internal state represents the signature described
+ * in the passed in array.
+ */
+ public virtual bool VerifySignature(
+ byte[] signature)
+ {
+ if (forSigning)
+ throw new InvalidOperationException("RsaDigestSigner not initialised for verification");
+
+ byte[] hash = new byte[digest.GetDigestSize()];
+ digest.DoFinal(hash, 0);
+
+ byte[] sig;
+ byte[] expected;
+
+ try
+ {
+ sig = rsaEngine.ProcessBlock(signature, 0, signature.Length);
+ expected = DerEncode(hash);
+ }
+ catch (Exception)
+ {
+ return false;
+ }
+
+ if (sig.Length == expected.Length)
+ {
+ return Arrays.ConstantTimeAreEqual(sig, expected);
+ }
+ else if (sig.Length == expected.Length - 2) // NULL left out
+ {
+ int sigOffset = sig.Length - hash.Length - 2;
+ int expectedOffset = expected.Length - hash.Length - 2;
+
+ expected[1] -= 2; // adjust lengths
+ expected[3] -= 2;
+
+ int nonEqual = 0;
+
+ for (int i = 0; i < hash.Length; i++)
+ {
+ nonEqual |= (sig[sigOffset + i] ^ expected[expectedOffset + i]);
+ }
+
+ for (int i = 0; i < sigOffset; i++)
+ {
+ nonEqual |= (sig[i] ^ expected[i]); // check header less NULL
+ }
+
+ return nonEqual == 0;
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ public virtual void Reset()
+ {
+ digest.Reset();
+ }
+
+ private byte[] DerEncode(byte[] hash)
+ {
+ if (algId == null)
+ {
+ // For raw RSA, the DigestInfo must be prepared externally
+ return hash;
+ }
+
+ DigestInfo dInfo = new DigestInfo(algId, hash);
+
+ return dInfo.GetDerEncoded();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/RsaDigestSigner.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/RsaDigestSigner.cs.meta
new file mode 100644
index 00000000..21e2861b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/RsaDigestSigner.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0a1d2191580cc304e9dd7fb6a78629ad
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/SM2Signer.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/SM2Signer.cs
new file mode 100644
index 00000000..07b2ec0e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/SM2Signer.cs
@@ -0,0 +1,246 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Multiplier;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
+{
+ /// The SM2 Digital Signature algorithm.
+ public class SM2Signer
+ : ISigner
+ {
+ private readonly IDsaKCalculator kCalculator = new RandomDsaKCalculator();
+ private readonly SM3Digest digest = new SM3Digest();
+ private readonly IDsaEncoding encoding;
+
+ private ECDomainParameters ecParams;
+ private ECPoint pubPoint;
+ private ECKeyParameters ecKey;
+ private byte[] z;
+
+ public SM2Signer()
+ {
+ this.encoding = StandardDsaEncoding.Instance;
+ }
+
+ public SM2Signer(IDsaEncoding encoding)
+ {
+ this.encoding = encoding;
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return "SM2Sign"; }
+ }
+
+ public virtual void Init(bool forSigning, ICipherParameters parameters)
+ {
+ ICipherParameters baseParam;
+ byte[] userID;
+
+ if (parameters is ParametersWithID)
+ {
+ baseParam = ((ParametersWithID)parameters).Parameters;
+ userID = ((ParametersWithID)parameters).GetID();
+ }
+ else
+ {
+ baseParam = parameters;
+ userID = Hex.Decode("31323334353637383132333435363738"); // the default value (ASCII "1234567812345678")
+ }
+
+ if (forSigning)
+ {
+ if (baseParam is ParametersWithRandom)
+ {
+ ParametersWithRandom rParam = (ParametersWithRandom)baseParam;
+
+ ecKey = (ECKeyParameters)rParam.Parameters;
+ ecParams = ecKey.Parameters;
+ kCalculator.Init(ecParams.N, rParam.Random);
+ }
+ else
+ {
+ ecKey = (ECKeyParameters)baseParam;
+ ecParams = ecKey.Parameters;
+ kCalculator.Init(ecParams.N, new SecureRandom());
+ }
+ pubPoint = CreateBasePointMultiplier().Multiply(ecParams.G, ((ECPrivateKeyParameters)ecKey).D).Normalize();
+ }
+ else
+ {
+ ecKey = (ECKeyParameters)baseParam;
+ ecParams = ecKey.Parameters;
+ pubPoint = ((ECPublicKeyParameters)ecKey).Q;
+ }
+
+ digest.Reset();
+ z = GetZ(userID);
+
+ digest.BlockUpdate(z, 0, z.Length);
+ }
+
+ public virtual void Update(byte b)
+ {
+ digest.Update(b);
+ }
+
+ public virtual void BlockUpdate(byte[] buf, int off, int len)
+ {
+ digest.BlockUpdate(buf, off, len);
+ }
+
+ public virtual bool VerifySignature(byte[] signature)
+ {
+ try
+ {
+ BigInteger[] rs = encoding.Decode(ecParams.N, signature);
+
+ return VerifySignature(rs[0], rs[1]);
+ }
+ catch (Exception)
+ {
+ }
+
+ return false;
+ }
+
+ public virtual void Reset()
+ {
+ if (z != null)
+ {
+ digest.Reset();
+ digest.BlockUpdate(z, 0, z.Length);
+ }
+ }
+
+ public virtual byte[] GenerateSignature()
+ {
+ byte[] eHash = DigestUtilities.DoFinal(digest);
+
+ BigInteger n = ecParams.N;
+ BigInteger e = CalculateE(eHash);
+ BigInteger d = ((ECPrivateKeyParameters)ecKey).D;
+
+ BigInteger r, s;
+
+ ECMultiplier basePointMultiplier = CreateBasePointMultiplier();
+
+ // 5.2.1 Draft RFC: SM2 Public Key Algorithms
+ do // generate s
+ {
+ BigInteger k;
+ do // generate r
+ {
+ // A3
+ k = kCalculator.NextK();
+
+ // A4
+ ECPoint p = basePointMultiplier.Multiply(ecParams.G, k).Normalize();
+
+ // A5
+ r = e.Add(p.AffineXCoord.ToBigInteger()).Mod(n);
+ }
+ while (r.SignValue == 0 || r.Add(k).Equals(n));
+
+ // A6
+ BigInteger dPlus1ModN = d.Add(BigInteger.One).ModInverse(n);
+
+ s = k.Subtract(r.Multiply(d)).Mod(n);
+ s = dPlus1ModN.Multiply(s).Mod(n);
+ }
+ while (s.SignValue == 0);
+
+ // A7
+ try
+ {
+ return encoding.Encode(ecParams.N, r, s);
+ }
+ catch (Exception ex)
+ {
+ throw new CryptoException("unable to encode signature: " + ex.Message, ex);
+ }
+ }
+
+ private bool VerifySignature(BigInteger r, BigInteger s)
+ {
+ BigInteger n = ecParams.N;
+
+ // 5.3.1 Draft RFC: SM2 Public Key Algorithms
+ // B1
+ if (r.CompareTo(BigInteger.One) < 0 || r.CompareTo(n) >= 0)
+ return false;
+
+ // B2
+ if (s.CompareTo(BigInteger.One) < 0 || s.CompareTo(n) >= 0)
+ return false;
+
+ // B3
+ byte[] eHash = DigestUtilities.DoFinal(digest);
+
+ // B4
+ BigInteger e = CalculateE(eHash);
+
+ // B5
+ BigInteger t = r.Add(s).Mod(n);
+ if (t.SignValue == 0)
+ return false;
+
+ // B6
+ ECPoint q = ((ECPublicKeyParameters)ecKey).Q;
+ ECPoint x1y1 = ECAlgorithms.SumOfTwoMultiplies(ecParams.G, s, q, t).Normalize();
+ if (x1y1.IsInfinity)
+ return false;
+
+ // B7
+ return r.Equals(e.Add(x1y1.AffineXCoord.ToBigInteger()).Mod(n));
+ }
+
+ private byte[] GetZ(byte[] userID)
+ {
+ AddUserID(digest, userID);
+
+ AddFieldElement(digest, ecParams.Curve.A);
+ AddFieldElement(digest, ecParams.Curve.B);
+ AddFieldElement(digest, ecParams.G.AffineXCoord);
+ AddFieldElement(digest, ecParams.G.AffineYCoord);
+ AddFieldElement(digest, pubPoint.AffineXCoord);
+ AddFieldElement(digest, pubPoint.AffineYCoord);
+
+ return DigestUtilities.DoFinal(digest);
+ }
+
+ private void AddUserID(IDigest digest, byte[] userID)
+ {
+ int len = userID.Length * 8;
+ digest.Update((byte)(len >> 8));
+ digest.Update((byte)len);
+ digest.BlockUpdate(userID, 0, userID.Length);
+ }
+
+ private void AddFieldElement(IDigest digest, ECFieldElement v)
+ {
+ byte[] p = v.GetEncoded();
+ digest.BlockUpdate(p, 0, p.Length);
+ }
+
+ protected virtual BigInteger CalculateE(byte[] message)
+ {
+ return new BigInteger(1, message);
+ }
+
+ protected virtual ECMultiplier CreateBasePointMultiplier()
+ {
+ return new FixedPointCombMultiplier();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/SM2Signer.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/SM2Signer.cs.meta
new file mode 100644
index 00000000..9faddedd
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/SM2Signer.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 68f56593743e64f4faf9b45065c5894a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/StandardDsaEncoding.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/StandardDsaEncoding.cs
new file mode 100644
index 00000000..ba76d033
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/StandardDsaEncoding.cs
@@ -0,0 +1,60 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
+{
+ public class StandardDsaEncoding
+ : IDsaEncoding
+ {
+ public static readonly StandardDsaEncoding Instance = new StandardDsaEncoding();
+
+ public virtual BigInteger[] Decode(BigInteger n, byte[] encoding)
+ {
+ Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(encoding);
+ if (seq.Count == 2)
+ {
+ BigInteger r = DecodeValue(n, seq, 0);
+ BigInteger s = DecodeValue(n, seq, 1);
+
+ byte[] expectedEncoding = Encode(n, r, s);
+ if (Arrays.AreEqual(expectedEncoding, encoding))
+ return new BigInteger[]{ r, s };
+ }
+
+ throw new ArgumentException("Malformed signature", "encoding");
+ }
+
+ public virtual byte[] Encode(BigInteger n, BigInteger r, BigInteger s)
+ {
+ return new DerSequence(
+ EncodeValue(n, r),
+ EncodeValue(n, s)
+ ).GetEncoded(Asn1Encodable.Der);
+ }
+
+ protected virtual BigInteger CheckValue(BigInteger n, BigInteger x)
+ {
+ if (x.SignValue < 0 || (null != n && x.CompareTo(n) >= 0))
+ throw new ArgumentException("Value out of range", "x");
+
+ return x;
+ }
+
+ protected virtual BigInteger DecodeValue(BigInteger n, Asn1Sequence s, int pos)
+ {
+ return CheckValue(n, ((DerInteger)s[pos]).Value);
+ }
+
+ protected virtual DerInteger EncodeValue(BigInteger n, BigInteger x)
+ {
+ return new DerInteger(CheckValue(n, x));
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/StandardDsaEncoding.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/StandardDsaEncoding.cs.meta
new file mode 100644
index 00000000..38fa2759
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/StandardDsaEncoding.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a964647027be2f14db0b63d2fb74479a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/X931Signer.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/X931Signer.cs
new file mode 100644
index 00000000..86ea3e37
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/X931Signer.cs
@@ -0,0 +1,230 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers
+{
+ /**
+ * X9.31-1998 - signing using a hash.
+ *
+ * The message digest hash, H, is encapsulated to form a byte string as follows
+ *
+ *
+ * EB = 06 || PS || 0xBA || H || TRAILER
+ *
+ * where PS is a string of bytes all of value 0xBB of length such that |EB|=|n|, and TRAILER is the ISO/IEC 10118 part number†for the digest. The byte string, EB, is converted to an integer value, the message representative, f.
+ */
+ public class X931Signer
+ : ISigner
+ {
+ [Obsolete("Use 'IsoTrailers' instead")]
+ public const int TRAILER_IMPLICIT = 0xBC;
+ [Obsolete("Use 'IsoTrailers' instead")]
+ public const int TRAILER_RIPEMD160 = 0x31CC;
+ [Obsolete("Use 'IsoTrailers' instead")]
+ public const int TRAILER_RIPEMD128 = 0x32CC;
+ [Obsolete("Use 'IsoTrailers' instead")]
+ public const int TRAILER_SHA1 = 0x33CC;
+ [Obsolete("Use 'IsoTrailers' instead")]
+ public const int TRAILER_SHA256 = 0x34CC;
+ [Obsolete("Use 'IsoTrailers' instead")]
+ public const int TRAILER_SHA512 = 0x35CC;
+ [Obsolete("Use 'IsoTrailers' instead")]
+ public const int TRAILER_SHA384 = 0x36CC;
+ [Obsolete("Use 'IsoTrailers' instead")]
+ public const int TRAILER_WHIRLPOOL = 0x37CC;
+ [Obsolete("Use 'IsoTrailers' instead")]
+ public const int TRAILER_SHA224 = 0x38CC;
+
+ private IDigest digest;
+ private IAsymmetricBlockCipher cipher;
+ private RsaKeyParameters kParam;
+
+ private int trailer;
+ private int keyBits;
+ private byte[] block;
+
+ /**
+ * Generate a signer with either implicit or explicit trailers for X9.31.
+ *
+ * @param cipher base cipher to use for signature creation/verification
+ * @param digest digest to use.
+ * @param implicit whether or not the trailer is implicit or gives the hash.
+ */
+ public X931Signer(IAsymmetricBlockCipher cipher, IDigest digest, bool isImplicit)
+ {
+ this.cipher = cipher;
+ this.digest = digest;
+
+ if (isImplicit)
+ {
+ trailer = IsoTrailers.TRAILER_IMPLICIT;
+ }
+ else if (IsoTrailers.NoTrailerAvailable(digest))
+ {
+ throw new ArgumentException("no valid trailer", "digest");
+ }
+ else
+ {
+ trailer = IsoTrailers.GetTrailer(digest);
+ }
+ }
+
+ public virtual string AlgorithmName
+ {
+ get { return digest.AlgorithmName + "with" + cipher.AlgorithmName + "/X9.31"; }
+ }
+
+ /**
+ * Constructor for a signer with an explicit digest trailer.
+ *
+ * @param cipher cipher to use.
+ * @param digest digest to sign with.
+ */
+ public X931Signer(IAsymmetricBlockCipher cipher, IDigest digest)
+ : this(cipher, digest, false)
+ {
+ }
+
+ public virtual void Init(bool forSigning, ICipherParameters parameters)
+ {
+ kParam = (RsaKeyParameters)parameters;
+
+ cipher.Init(forSigning, kParam);
+
+ keyBits = kParam.Modulus.BitLength;
+
+ block = new byte[(keyBits + 7) / 8];
+
+ Reset();
+ }
+
+ /// clear possible sensitive data
+ private void ClearBlock(byte[] block)
+ {
+ Array.Clear(block, 0, block.Length);
+ }
+
+ /**
+ * update the internal digest with the byte b
+ */
+ public virtual void Update(byte b)
+ {
+ digest.Update(b);
+ }
+
+ /**
+ * update the internal digest with the byte array in
+ */
+ public virtual void BlockUpdate(byte[] input, int off, int len)
+ {
+ digest.BlockUpdate(input, off, len);
+ }
+
+ /**
+ * reset the internal state
+ */
+ public virtual void Reset()
+ {
+ digest.Reset();
+ }
+
+ /**
+ * generate a signature for the loaded message using the key we were
+ * initialised with.
+ */
+ public virtual byte[] GenerateSignature()
+ {
+ CreateSignatureBlock();
+
+ BigInteger t = new BigInteger(1, cipher.ProcessBlock(block, 0, block.Length));
+ ClearBlock(block);
+
+ t = t.Min(kParam.Modulus.Subtract(t));
+
+ int size = BigIntegers.GetUnsignedByteLength(kParam.Modulus);
+ return BigIntegers.AsUnsignedByteArray(size, t);
+ }
+
+ private void CreateSignatureBlock()
+ {
+ int digSize = digest.GetDigestSize();
+
+ int delta;
+ if (trailer == IsoTrailers.TRAILER_IMPLICIT)
+ {
+ delta = block.Length - digSize - 1;
+ digest.DoFinal(block, delta);
+ block[block.Length - 1] = (byte)IsoTrailers.TRAILER_IMPLICIT;
+ }
+ else
+ {
+ delta = block.Length - digSize - 2;
+ digest.DoFinal(block, delta);
+ block[block.Length - 2] = (byte)(trailer >> 8);
+ block[block.Length - 1] = (byte)trailer;
+ }
+
+ block[0] = 0x6b;
+ for (int i = delta - 2; i != 0; i--)
+ {
+ block[i] = (byte)0xbb;
+ }
+ block[delta - 1] = (byte)0xba;
+ }
+
+ /**
+ * return true if the signature represents a ISO9796-2 signature
+ * for the passed in message.
+ */
+ public virtual bool VerifySignature(byte[] signature)
+ {
+ try
+ {
+ block = cipher.ProcessBlock(signature, 0, signature.Length);
+ }
+ catch (Exception)
+ {
+ return false;
+ }
+
+ BigInteger t = new BigInteger(1, block);
+ BigInteger f;
+
+ if ((t.IntValue & 15) == 12)
+ {
+ f = t;
+ }
+ else
+ {
+ t = kParam.Modulus.Subtract(t);
+ if ((t.IntValue & 15) == 12)
+ {
+ f = t;
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ CreateSignatureBlock();
+
+ byte[] fBlock = BigIntegers.AsUnsignedByteArray(block.Length, f);
+
+ bool rv = Arrays.ConstantTimeAreEqual(block, fBlock);
+
+ ClearBlock(block);
+ ClearBlock(fBlock);
+
+ return rv;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/X931Signer.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/X931Signer.cs.meta
new file mode 100644
index 00000000..9b00b1f5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/signers/X931Signer.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a4d003e3a33c78049a002e2b2f4da98d
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls.meta
new file mode 100644
index 00000000..05810b86
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 377c62a7a08191a46babb9e0f98c238c
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsAgreementCredentials.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsAgreementCredentials.cs
new file mode 100644
index 00000000..147aadff
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsAgreementCredentials.cs
@@ -0,0 +1,16 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Tls
+{
+ public abstract class AbstractTlsAgreementCredentials
+ : AbstractTlsCredentials, TlsAgreementCredentials
+ {
+ ///
+ public abstract byte[] GenerateAgreement(AsymmetricKeyParameter peerPublicKey);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsAgreementCredentials.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsAgreementCredentials.cs.meta
new file mode 100644
index 00000000..b0e62f87
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsAgreementCredentials.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 883690e221f19a6418e8bc624f2e9a08
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsCipherFactory.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsCipherFactory.cs
new file mode 100644
index 00000000..67dc9876
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsCipherFactory.cs
@@ -0,0 +1,19 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Tls
+{
+ public class AbstractTlsCipherFactory
+ : TlsCipherFactory
+ {
+ ///
+ public virtual TlsCipher CreateCipher(TlsContext context, int encryptionAlgorithm, int macAlgorithm)
+ {
+ throw new TlsFatalAlert(AlertDescription.internal_error);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsCipherFactory.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsCipherFactory.cs.meta
new file mode 100644
index 00000000..ebd4b5de
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsCipherFactory.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: f22405f313bf66a449f14a07c843bc2f
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsClient.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsClient.cs
new file mode 100644
index 00000000..cadc0466
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsClient.cs
@@ -0,0 +1,282 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Tls
+{
+ public abstract class AbstractTlsClient
+ : AbstractTlsPeer, TlsClient
+ {
+ protected TlsCipherFactory mCipherFactory;
+
+ protected TlsClientContext mContext;
+
+ protected IList mSupportedSignatureAlgorithms;
+ protected int[] mNamedCurves;
+ protected byte[] mClientECPointFormats, mServerECPointFormats;
+
+ protected int mSelectedCipherSuite;
+ protected short mSelectedCompressionMethod;
+
+ public System.Collections.Generic.List HostNames { get; set; }
+
+ public AbstractTlsClient()
+ : this(new DefaultTlsCipherFactory())
+ {
+ }
+
+ public AbstractTlsClient(TlsCipherFactory cipherFactory)
+ {
+ this.mCipherFactory = cipherFactory;
+ }
+
+ protected virtual bool AllowUnexpectedServerExtension(int extensionType, byte[] extensionData)
+ {
+ switch (extensionType)
+ {
+ case ExtensionType.elliptic_curves:
+ /*
+ * Exception added based on field reports that some servers do send this, although the
+ * Supported Elliptic Curves Extension is clearly intended to be client-only. If
+ * present, we still require that it is a valid EllipticCurveList.
+ */
+ TlsEccUtilities.ReadSupportedEllipticCurvesExtension(extensionData);
+ return true;
+
+ case ExtensionType.ec_point_formats:
+ /*
+ * Exception added based on field reports that some servers send this even when they
+ * didn't negotiate an ECC cipher suite. If present, we still require that it is a valid
+ * ECPointFormatList.
+ */
+ TlsEccUtilities.ReadSupportedPointFormatsExtension(extensionData);
+ return true;
+
+ default:
+ return false;
+ }
+ }
+
+ protected virtual void CheckForUnexpectedServerExtension(IDictionary serverExtensions, int extensionType)
+ {
+ byte[] extensionData = TlsUtilities.GetExtensionData(serverExtensions, extensionType);
+ if (extensionData != null && !AllowUnexpectedServerExtension(extensionType, extensionData))
+ {
+ throw new TlsFatalAlert(AlertDescription.illegal_parameter);
+ }
+ }
+
+ public virtual void Init(TlsClientContext context)
+ {
+ this.mContext = context;
+ }
+
+ public virtual TlsSession GetSessionToResume()
+ {
+ return null;
+ }
+
+ public virtual ProtocolVersion ClientHelloRecordLayerVersion
+ {
+ get
+ {
+ // "{03,00}"
+ //return ProtocolVersion.SSLv3;
+
+ // "the lowest version number supported by the client"
+ //return MinimumVersion;
+
+ // "the value of ClientHello.client_version"
+ return ClientVersion;
+ }
+ }
+
+ public virtual ProtocolVersion ClientVersion
+ {
+ get { return ProtocolVersion.TLSv12; }
+ }
+
+ public virtual bool IsFallback
+ {
+ /*
+ * RFC 7507 4. The TLS_FALLBACK_SCSV cipher suite value is meant for use by clients that
+ * repeat a connection attempt with a downgraded protocol (perform a "fallback retry") in
+ * order to work around interoperability problems with legacy servers.
+ */
+ get { return false; }
+ }
+
+ public virtual IDictionary GetClientExtensions()
+ {
+ IDictionary clientExtensions = null;
+
+ ProtocolVersion clientVersion = mContext.ClientVersion;
+
+ /*
+ * RFC 5246 7.4.1.4.1. Note: this extension is not meaningful for TLS versions prior to 1.2.
+ * Clients MUST NOT offer it if they are offering prior versions.
+ */
+ if (TlsUtilities.IsSignatureAlgorithmsExtensionAllowed(clientVersion))
+ {
+ // TODO Provide a way for the user to specify the acceptable hash/signature algorithms.
+
+ this.mSupportedSignatureAlgorithms = TlsUtilities.GetDefaultSupportedSignatureAlgorithms();
+
+ clientExtensions = TlsExtensionsUtilities.EnsureExtensionsInitialised(clientExtensions);
+
+ TlsUtilities.AddSignatureAlgorithmsExtension(clientExtensions, mSupportedSignatureAlgorithms);
+ }
+
+ if (TlsEccUtilities.ContainsEccCipherSuites(GetCipherSuites()))
+ {
+ /*
+ * RFC 4492 5.1. A client that proposes ECC cipher suites in its ClientHello message
+ * appends these extensions (along with any others), enumerating the curves it supports
+ * and the point formats it can parse. Clients SHOULD send both the Supported Elliptic
+ * Curves Extension and the Supported Point Formats Extension.
+ */
+ /*
+ * TODO Could just add all the curves since we support them all, but users may not want
+ * to use unnecessarily large fields. Need configuration options.
+ */
+ this.mNamedCurves = new int[]{ NamedCurve.secp256r1, NamedCurve.secp384r1 };
+ this.mClientECPointFormats = new byte[]{ ECPointFormat.uncompressed,
+ ECPointFormat.ansiX962_compressed_prime, ECPointFormat.ansiX962_compressed_char2, };
+
+ clientExtensions = TlsExtensionsUtilities.EnsureExtensionsInitialised(clientExtensions);
+
+ TlsEccUtilities.AddSupportedEllipticCurvesExtension(clientExtensions, mNamedCurves);
+ TlsEccUtilities.AddSupportedPointFormatsExtension(clientExtensions, mClientECPointFormats);
+ }
+
+ if (this.HostNames != null && this.HostNames.Count > 0)
+ {
+ var list = new System.Collections.Generic.List(this.HostNames.Count);
+
+ for (int i = 0; i < this.HostNames.Count; ++i)
+ list.Add(new ServerName(Tls.NameType.host_name, this.HostNames[i]));
+
+ TlsExtensionsUtilities.AddServerNameExtension(clientExtensions, new ServerNameList(list));
+ }
+
+ return clientExtensions;
+ }
+
+ public virtual ProtocolVersion MinimumVersion
+ {
+ get { return ProtocolVersion.TLSv10; }
+ }
+
+ public virtual void NotifyServerVersion(ProtocolVersion serverVersion)
+ {
+ if (!MinimumVersion.IsEqualOrEarlierVersionOf(serverVersion))
+ throw new TlsFatalAlert(AlertDescription.protocol_version);
+ }
+
+ public abstract int[] GetCipherSuites();
+
+ public virtual byte[] GetCompressionMethods()
+ {
+ return new byte[]{ CompressionMethod.cls_null };
+ }
+
+ public virtual void NotifySessionID(byte[] sessionID)
+ {
+ // Currently ignored
+ }
+
+ public virtual void NotifySelectedCipherSuite(int selectedCipherSuite)
+ {
+ this.mSelectedCipherSuite = selectedCipherSuite;
+ }
+
+ public virtual void NotifySelectedCompressionMethod(byte selectedCompressionMethod)
+ {
+ this.mSelectedCompressionMethod = selectedCompressionMethod;
+ }
+
+ public virtual void ProcessServerExtensions(IDictionary serverExtensions)
+ {
+ /*
+ * TlsProtocol implementation validates that any server extensions received correspond to
+ * client extensions sent. By default, we don't send any, and this method is not called.
+ */
+ if (serverExtensions != null)
+ {
+ /*
+ * RFC 5246 7.4.1.4.1. Servers MUST NOT send this extension.
+ */
+ CheckForUnexpectedServerExtension(serverExtensions, ExtensionType.signature_algorithms);
+
+ CheckForUnexpectedServerExtension(serverExtensions, ExtensionType.elliptic_curves);
+
+ if (TlsEccUtilities.IsEccCipherSuite(this.mSelectedCipherSuite))
+ {
+ this.mServerECPointFormats = TlsEccUtilities.GetSupportedPointFormatsExtension(serverExtensions);
+ }
+ else
+ {
+ CheckForUnexpectedServerExtension(serverExtensions, ExtensionType.ec_point_formats);
+ }
+
+ /*
+ * RFC 7685 3. The server MUST NOT echo the extension.
+ */
+ CheckForUnexpectedServerExtension(serverExtensions, ExtensionType.padding);
+ }
+ }
+
+ public virtual void ProcessServerSupplementalData(IList serverSupplementalData)
+ {
+ if (serverSupplementalData != null)
+ throw new TlsFatalAlert(AlertDescription.unexpected_message);
+ }
+
+ public abstract TlsKeyExchange GetKeyExchange();
+
+ public abstract TlsAuthentication GetAuthentication();
+
+ public virtual IList GetClientSupplementalData()
+ {
+ return null;
+ }
+
+ public override TlsCompression GetCompression()
+ {
+ switch (mSelectedCompressionMethod)
+ {
+ case CompressionMethod.cls_null:
+ return new TlsNullCompression();
+
+ case CompressionMethod.DEFLATE:
+ return new TlsDeflateCompression();
+
+ default:
+ /*
+ * Note: internal error here; the TlsProtocol implementation verifies that the
+ * server-selected compression method was in the list of client-offered compression
+ * methods, so if we now can't produce an implementation, we shouldn't have offered it!
+ */
+ throw new TlsFatalAlert(AlertDescription.internal_error);
+ }
+ }
+
+ public override TlsCipher GetCipher()
+ {
+ int encryptionAlgorithm = TlsUtilities.GetEncryptionAlgorithm(mSelectedCipherSuite);
+ int macAlgorithm = TlsUtilities.GetMacAlgorithm(mSelectedCipherSuite);
+
+ return mCipherFactory.CreateCipher(mContext, encryptionAlgorithm, macAlgorithm);
+ }
+
+ public virtual void NotifyNewSessionTicket(NewSessionTicket newSessionTicket)
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsClient.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsClient.cs.meta
new file mode 100644
index 00000000..9a4d0185
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsClient.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c301d56f352233b47bd13d7a3142a95a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsContext.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsContext.cs
new file mode 100644
index 00000000..351a5d3a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsContext.cs
@@ -0,0 +1,158 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Threading;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Tls
+{
+ internal abstract class AbstractTlsContext
+ : TlsContext
+ {
+ private static long counter = Times.NanoTime();
+
+#if NETCF_1_0
+ private static object counterLock = new object();
+ private static long NextCounterValue()
+ {
+ lock (counterLock)
+ {
+ return ++counter;
+ }
+ }
+#else
+ private static long NextCounterValue()
+ {
+ return Interlocked.Increment(ref counter);
+ }
+#endif
+
+ private readonly IRandomGenerator mNonceRandom;
+ private readonly SecureRandom mSecureRandom;
+ private readonly SecurityParameters mSecurityParameters;
+
+ private ProtocolVersion mClientVersion = null;
+ private ProtocolVersion mServerVersion = null;
+ private TlsSession mSession = null;
+ private object mUserObject = null;
+
+ internal AbstractTlsContext(SecureRandom secureRandom, SecurityParameters securityParameters)
+ {
+ IDigest d = TlsUtilities.CreateHash(HashAlgorithm.sha256);
+ byte[] seed = new byte[d.GetDigestSize()];
+ secureRandom.NextBytes(seed);
+
+ this.mNonceRandom = new DigestRandomGenerator(d);
+ mNonceRandom.AddSeedMaterial(NextCounterValue());
+ mNonceRandom.AddSeedMaterial(Times.NanoTime());
+ mNonceRandom.AddSeedMaterial(seed);
+
+ this.mSecureRandom = secureRandom;
+ this.mSecurityParameters = securityParameters;
+ }
+
+ public virtual IRandomGenerator NonceRandomGenerator
+ {
+ get { return mNonceRandom; }
+ }
+
+ public virtual SecureRandom SecureRandom
+ {
+ get { return mSecureRandom; }
+ }
+
+ public virtual SecurityParameters SecurityParameters
+ {
+ get { return mSecurityParameters; }
+ }
+
+ public abstract bool IsServer { get; }
+
+ public virtual ProtocolVersion ClientVersion
+ {
+ get { return mClientVersion; }
+ }
+
+ internal virtual void SetClientVersion(ProtocolVersion clientVersion)
+ {
+ this.mClientVersion = clientVersion;
+ }
+
+ public virtual ProtocolVersion ServerVersion
+ {
+ get { return mServerVersion; }
+ }
+
+ internal virtual void SetServerVersion(ProtocolVersion serverVersion)
+ {
+ this.mServerVersion = serverVersion;
+ }
+
+ public virtual TlsSession ResumableSession
+ {
+ get { return mSession; }
+ }
+
+ internal virtual void SetResumableSession(TlsSession session)
+ {
+ this.mSession = session;
+ }
+
+ public virtual object UserObject
+ {
+ get { return mUserObject; }
+ set { this.mUserObject = value; }
+ }
+
+ public virtual byte[] ExportKeyingMaterial(string asciiLabel, byte[] context_value, int length)
+ {
+ if (context_value != null && !TlsUtilities.IsValidUint16(context_value.Length))
+ throw new ArgumentException("must have length less than 2^16 (or be null)", "context_value");
+
+ SecurityParameters sp = SecurityParameters;
+ if (!sp.IsExtendedMasterSecret)
+ {
+ /*
+ * RFC 7627 5.4. If a client or server chooses to continue with a full handshake without
+ * the extended master secret extension, [..] the client or server MUST NOT export any
+ * key material based on the new master secret for any subsequent application-level
+ * authentication. In particular, it MUST disable [RFC5705] [..].
+ */
+ throw new InvalidOperationException("cannot export keying material without extended_master_secret");
+ }
+
+ byte[] cr = sp.ClientRandom, sr = sp.ServerRandom;
+
+ int seedLength = cr.Length + sr.Length;
+ if (context_value != null)
+ {
+ seedLength += (2 + context_value.Length);
+ }
+
+ byte[] seed = new byte[seedLength];
+ int seedPos = 0;
+
+ Array.Copy(cr, 0, seed, seedPos, cr.Length);
+ seedPos += cr.Length;
+ Array.Copy(sr, 0, seed, seedPos, sr.Length);
+ seedPos += sr.Length;
+ if (context_value != null)
+ {
+ TlsUtilities.WriteUint16(context_value.Length, seed, seedPos);
+ seedPos += 2;
+ Array.Copy(context_value, 0, seed, seedPos, context_value.Length);
+ seedPos += context_value.Length;
+ }
+
+ if (seedPos != seedLength)
+ throw new InvalidOperationException("error in calculation of seed for export");
+
+ return TlsUtilities.PRF(this, sp.MasterSecret, asciiLabel, seed, length);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsContext.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsContext.cs.meta
new file mode 100644
index 00000000..e48cf096
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsContext.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ae1694ad34c5af748804e7e441781e6e
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsCredentials.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsCredentials.cs
new file mode 100644
index 00000000..05406ced
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsCredentials.cs
@@ -0,0 +1,14 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Tls
+{
+ public abstract class AbstractTlsCredentials
+ : TlsCredentials
+ {
+ public abstract Certificate Certificate { get; }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsCredentials.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsCredentials.cs.meta
new file mode 100644
index 00000000..b440ca3c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsCredentials.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 45b44747a83f28d4a8d737abb08516fb
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsEncryptionCredentials.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsEncryptionCredentials.cs
new file mode 100644
index 00000000..59f565e9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsEncryptionCredentials.cs
@@ -0,0 +1,16 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Tls
+{
+ public abstract class AbstractTlsEncryptionCredentials
+ : AbstractTlsCredentials, TlsEncryptionCredentials
+ {
+ ///
+ public abstract byte[] DecryptPreMasterSecret(byte[] encryptedPreMasterSecret);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsEncryptionCredentials.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsEncryptionCredentials.cs.meta
new file mode 100644
index 00000000..ee422dd4
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsEncryptionCredentials.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 55bf10e0f1cbfca47b598d52fb8cdd7a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsKeyExchange.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsKeyExchange.cs
new file mode 100644
index 00000000..a1f9b4fd
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsKeyExchange.cs
@@ -0,0 +1,181 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Tls
+{
+ public abstract class AbstractTlsKeyExchange
+ : TlsKeyExchange
+ {
+ protected readonly int mKeyExchange;
+ protected IList mSupportedSignatureAlgorithms;
+
+ protected TlsContext mContext;
+
+ protected AbstractTlsKeyExchange(int keyExchange, IList supportedSignatureAlgorithms)
+ {
+ this.mKeyExchange = keyExchange;
+ this.mSupportedSignatureAlgorithms = supportedSignatureAlgorithms;
+ }
+
+ protected virtual DigitallySigned ParseSignature(Stream input)
+ {
+ DigitallySigned signature = DigitallySigned.Parse(mContext, input);
+ SignatureAndHashAlgorithm signatureAlgorithm = signature.Algorithm;
+ if (signatureAlgorithm != null)
+ {
+ TlsUtilities.VerifySupportedSignatureAlgorithm(mSupportedSignatureAlgorithms, signatureAlgorithm);
+ }
+ return signature;
+ }
+
+ public virtual void Init(TlsContext context)
+ {
+ this.mContext = context;
+
+ ProtocolVersion clientVersion = context.ClientVersion;
+
+ if (TlsUtilities.IsSignatureAlgorithmsExtensionAllowed(clientVersion))
+ {
+ /*
+ * RFC 5246 7.4.1.4.1. If the client does not send the signature_algorithms extension,
+ * the server MUST do the following:
+ *
+ * - If the negotiated key exchange algorithm is one of (RSA, DHE_RSA, DH_RSA, RSA_PSK,
+ * ECDH_RSA, ECDHE_RSA), behave as if client had sent the value {sha1,rsa}.
+ *
+ * - If the negotiated key exchange algorithm is one of (DHE_DSS, DH_DSS), behave as if
+ * the client had sent the value {sha1,dsa}.
+ *
+ * - If the negotiated key exchange algorithm is one of (ECDH_ECDSA, ECDHE_ECDSA),
+ * behave as if the client had sent value {sha1,ecdsa}.
+ */
+ if (this.mSupportedSignatureAlgorithms == null)
+ {
+ switch (mKeyExchange)
+ {
+ case KeyExchangeAlgorithm.DH_DSS:
+ case KeyExchangeAlgorithm.DHE_DSS:
+ case KeyExchangeAlgorithm.SRP_DSS:
+ {
+ this.mSupportedSignatureAlgorithms = TlsUtilities.GetDefaultDssSignatureAlgorithms();
+ break;
+ }
+
+ case KeyExchangeAlgorithm.ECDH_ECDSA:
+ case KeyExchangeAlgorithm.ECDHE_ECDSA:
+ {
+ this.mSupportedSignatureAlgorithms = TlsUtilities.GetDefaultECDsaSignatureAlgorithms();
+ break;
+ }
+
+ case KeyExchangeAlgorithm.DH_RSA:
+ case KeyExchangeAlgorithm.DHE_RSA:
+ case KeyExchangeAlgorithm.ECDH_RSA:
+ case KeyExchangeAlgorithm.ECDHE_RSA:
+ case KeyExchangeAlgorithm.RSA:
+ case KeyExchangeAlgorithm.RSA_PSK:
+ case KeyExchangeAlgorithm.SRP_RSA:
+ {
+ this.mSupportedSignatureAlgorithms = TlsUtilities.GetDefaultRsaSignatureAlgorithms();
+ break;
+ }
+
+ case KeyExchangeAlgorithm.DHE_PSK:
+ case KeyExchangeAlgorithm.ECDHE_PSK:
+ case KeyExchangeAlgorithm.PSK:
+ case KeyExchangeAlgorithm.SRP:
+ break;
+
+ default:
+ throw new InvalidOperationException("unsupported key exchange algorithm");
+ }
+ }
+
+ }
+ else if (this.mSupportedSignatureAlgorithms != null)
+ {
+ throw new InvalidOperationException("supported_signature_algorithms not allowed for " + clientVersion);
+ }
+ }
+
+ public abstract void SkipServerCredentials();
+
+ public virtual void ProcessServerCertificate(Certificate serverCertificate)
+ {
+ if (mSupportedSignatureAlgorithms == null)
+ {
+ /*
+ * TODO RFC 2246 7.4.2. Unless otherwise specified, the signing algorithm for the
+ * certificate must be the same as the algorithm for the certificate key.
+ */
+ }
+ else
+ {
+ /*
+ * TODO RFC 5246 7.4.2. If the client provided a "signature_algorithms" extension, then
+ * all certificates provided by the server MUST be signed by a hash/signature algorithm
+ * pair that appears in that extension.
+ */
+ }
+ }
+
+ public virtual void ProcessServerCredentials(TlsCredentials serverCredentials)
+ {
+ ProcessServerCertificate(serverCredentials.Certificate);
+ }
+
+ public virtual bool RequiresServerKeyExchange
+ {
+ get { return false; }
+ }
+
+ public virtual byte[] GenerateServerKeyExchange()
+ {
+ if (RequiresServerKeyExchange)
+ throw new TlsFatalAlert(AlertDescription.internal_error);
+
+ return null;
+ }
+
+ public virtual void SkipServerKeyExchange()
+ {
+ if (RequiresServerKeyExchange)
+ throw new TlsFatalAlert(AlertDescription.unexpected_message);
+ }
+
+ public virtual void ProcessServerKeyExchange(Stream input)
+ {
+ if (!RequiresServerKeyExchange)
+ {
+ throw new TlsFatalAlert(AlertDescription.unexpected_message);
+ }
+ }
+
+ public abstract void ValidateCertificateRequest(CertificateRequest certificateRequest);
+
+ public virtual void SkipClientCredentials()
+ {
+ }
+
+ public abstract void ProcessClientCredentials(TlsCredentials clientCredentials);
+
+ public virtual void ProcessClientCertificate(Certificate clientCertificate)
+ {
+ }
+
+ public abstract void GenerateClientKeyExchange(Stream output);
+
+ public virtual void ProcessClientKeyExchange(Stream input)
+ {
+ // Key exchange implementation MUST support client key exchange
+ throw new TlsFatalAlert(AlertDescription.internal_error);
+ }
+
+ public abstract byte[] GeneratePremasterSecret();
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsKeyExchange.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsKeyExchange.cs.meta
new file mode 100644
index 00000000..107538c3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsKeyExchange.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: e3f8816144989924494adb4d63ab573e
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsPeer.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsPeer.cs
new file mode 100644
index 00000000..2ad34f8c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsPeer.cs
@@ -0,0 +1,57 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Tls
+{
+ public abstract class AbstractTlsPeer
+ : TlsPeer
+ {
+ public virtual bool RequiresExtendedMasterSecret()
+ {
+ return false;
+ }
+
+ public virtual bool ShouldUseGmtUnixTime()
+ {
+ /*
+ * draft-mathewson-no-gmtunixtime-00 2. For the reasons we discuss above, we recommend that
+ * TLS implementors MUST by default set the entire value the ClientHello.Random and
+ * ServerHello.Random fields, including gmt_unix_time, to a cryptographically random
+ * sequence.
+ */
+ return false;
+ }
+
+ public virtual void NotifySecureRenegotiation(bool secureRenegotiation)
+ {
+ if (!secureRenegotiation)
+ {
+ /*
+ * RFC 5746 3.4/3.6. In this case, some clients/servers may want to terminate the handshake instead
+ * of continuing; see Section 4.1/4.3 for discussion.
+ */
+ throw new TlsFatalAlert(AlertDescription.handshake_failure);
+ }
+ }
+
+ public abstract TlsCompression GetCompression();
+
+ public abstract TlsCipher GetCipher();
+
+ public virtual void NotifyAlertRaised(byte alertLevel, byte alertDescription, string message, Exception cause)
+ {
+ }
+
+ public virtual void NotifyAlertReceived(byte alertLevel, byte alertDescription)
+ {
+ }
+
+ public virtual void NotifyHandshakeComplete()
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsPeer.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsPeer.cs.meta
new file mode 100644
index 00000000..34241da9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsPeer.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 630d4642ce55ac74fb84bdf9d0244397
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsServer.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsServer.cs
new file mode 100644
index 00000000..79870179
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsServer.cs
@@ -0,0 +1,355 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Tls
+{
+ public abstract class AbstractTlsServer
+ : AbstractTlsPeer, TlsServer
+ {
+ protected TlsCipherFactory mCipherFactory;
+
+ protected TlsServerContext mContext;
+
+ protected ProtocolVersion mClientVersion;
+ protected int[] mOfferedCipherSuites;
+ protected byte[] mOfferedCompressionMethods;
+ protected IDictionary mClientExtensions;
+
+ protected bool mEncryptThenMacOffered;
+ protected short mMaxFragmentLengthOffered;
+ protected bool mTruncatedHMacOffered;
+ protected IList mSupportedSignatureAlgorithms;
+ protected bool mEccCipherSuitesOffered;
+ protected int[] mNamedCurves;
+ protected byte[] mClientECPointFormats, mServerECPointFormats;
+
+ protected ProtocolVersion mServerVersion;
+ protected int mSelectedCipherSuite;
+ protected byte mSelectedCompressionMethod;
+ protected IDictionary mServerExtensions;
+
+ public AbstractTlsServer()
+ : this(new DefaultTlsCipherFactory())
+ {
+ }
+
+ public AbstractTlsServer(TlsCipherFactory cipherFactory)
+ {
+ this.mCipherFactory = cipherFactory;
+ }
+
+ protected virtual bool AllowEncryptThenMac
+ {
+ get { return true; }
+ }
+
+ protected virtual bool AllowTruncatedHMac
+ {
+ get { return false; }
+ }
+
+ protected virtual IDictionary CheckServerExtensions()
+ {
+ return this.mServerExtensions = TlsExtensionsUtilities.EnsureExtensionsInitialised(this.mServerExtensions);
+ }
+
+ protected abstract int[] GetCipherSuites();
+
+ protected byte[] GetCompressionMethods()
+ {
+ return new byte[] { CompressionMethod.cls_null };
+ }
+
+ protected virtual ProtocolVersion MaximumVersion
+ {
+ get { return ProtocolVersion.TLSv11; }
+ }
+
+ protected virtual ProtocolVersion MinimumVersion
+ {
+ get { return ProtocolVersion.TLSv10; }
+ }
+
+ protected virtual bool SupportsClientEccCapabilities(int[] namedCurves, byte[] ecPointFormats)
+ {
+ // NOTE: BC supports all the current set of point formats so we don't check them here
+
+ if (namedCurves == null)
+ {
+ /*
+ * RFC 4492 4. A client that proposes ECC cipher suites may choose not to include these
+ * extensions. In this case, the server is free to choose any one of the elliptic curves
+ * or point formats [...].
+ */
+ return TlsEccUtilities.HasAnySupportedNamedCurves();
+ }
+
+ for (int i = 0; i < namedCurves.Length; ++i)
+ {
+ int namedCurve = namedCurves[i];
+ if (NamedCurve.IsValid(namedCurve)
+ && (!NamedCurve.RefersToASpecificNamedCurve(namedCurve) || TlsEccUtilities.IsSupportedNamedCurve(namedCurve)))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ public virtual void Init(TlsServerContext context)
+ {
+ this.mContext = context;
+ }
+
+ public virtual void NotifyClientVersion(ProtocolVersion clientVersion)
+ {
+ this.mClientVersion = clientVersion;
+ }
+
+ public virtual void NotifyFallback(bool isFallback)
+ {
+ /*
+ * RFC 7507 3. If TLS_FALLBACK_SCSV appears in ClientHello.cipher_suites and the highest
+ * protocol version supported by the server is higher than the version indicated in
+ * ClientHello.client_version, the server MUST respond with a fatal inappropriate_fallback
+ * alert [..].
+ */
+ if (isFallback && MaximumVersion.IsLaterVersionOf(mClientVersion))
+ throw new TlsFatalAlert(AlertDescription.inappropriate_fallback);
+ }
+
+ public virtual void NotifyOfferedCipherSuites(int[] offeredCipherSuites)
+ {
+ this.mOfferedCipherSuites = offeredCipherSuites;
+ this.mEccCipherSuitesOffered = TlsEccUtilities.ContainsEccCipherSuites(this.mOfferedCipherSuites);
+ }
+
+ public virtual void NotifyOfferedCompressionMethods(byte[] offeredCompressionMethods)
+ {
+ this.mOfferedCompressionMethods = offeredCompressionMethods;
+ }
+
+ public virtual void ProcessClientExtensions(IDictionary clientExtensions)
+ {
+ this.mClientExtensions = clientExtensions;
+
+ if (clientExtensions != null)
+ {
+ this.mEncryptThenMacOffered = TlsExtensionsUtilities.HasEncryptThenMacExtension(clientExtensions);
+
+ this.mMaxFragmentLengthOffered = TlsExtensionsUtilities.GetMaxFragmentLengthExtension(clientExtensions);
+ if (mMaxFragmentLengthOffered >= 0 && !MaxFragmentLength.IsValid((byte)mMaxFragmentLengthOffered))
+ throw new TlsFatalAlert(AlertDescription.illegal_parameter);
+
+ this.mTruncatedHMacOffered = TlsExtensionsUtilities.HasTruncatedHMacExtension(clientExtensions);
+
+ this.mSupportedSignatureAlgorithms = TlsUtilities.GetSignatureAlgorithmsExtension(clientExtensions);
+ if (this.mSupportedSignatureAlgorithms != null)
+ {
+ /*
+ * RFC 5246 7.4.1.4.1. Note: this extension is not meaningful for TLS versions prior
+ * to 1.2. Clients MUST NOT offer it if they are offering prior versions.
+ */
+ if (!TlsUtilities.IsSignatureAlgorithmsExtensionAllowed(mClientVersion))
+ throw new TlsFatalAlert(AlertDescription.illegal_parameter);
+ }
+
+ this.mNamedCurves = TlsEccUtilities.GetSupportedEllipticCurvesExtension(clientExtensions);
+ this.mClientECPointFormats = TlsEccUtilities.GetSupportedPointFormatsExtension(clientExtensions);
+ }
+
+ /*
+ * RFC 4429 4. The client MUST NOT include these extensions in the ClientHello message if it
+ * does not propose any ECC cipher suites.
+ *
+ * NOTE: This was overly strict as there may be ECC cipher suites that we don't recognize.
+ * Also, draft-ietf-tls-negotiated-ff-dhe will be overloading the 'elliptic_curves'
+ * extension to explicitly allow FFDHE (i.e. non-ECC) groups.
+ */
+ //if (!this.mEccCipherSuitesOffered && (this.mNamedCurves != null || this.mClientECPointFormats != null))
+ // throw new TlsFatalAlert(AlertDescription.illegal_parameter);
+ }
+
+ public virtual ProtocolVersion GetServerVersion()
+ {
+ if (MinimumVersion.IsEqualOrEarlierVersionOf(mClientVersion))
+ {
+ ProtocolVersion maximumVersion = MaximumVersion;
+ if (mClientVersion.IsEqualOrEarlierVersionOf(maximumVersion))
+ {
+ return mServerVersion = mClientVersion;
+ }
+ if (mClientVersion.IsLaterVersionOf(maximumVersion))
+ {
+ return mServerVersion = maximumVersion;
+ }
+ }
+ throw new TlsFatalAlert(AlertDescription.protocol_version);
+ }
+
+ public virtual int GetSelectedCipherSuite()
+ {
+ /*
+ * RFC 5246 7.4.3. In order to negotiate correctly, the server MUST check any candidate
+ * cipher suites against the "signature_algorithms" extension before selecting them. This is
+ * somewhat inelegant but is a compromise designed to minimize changes to the original
+ * cipher suite design.
+ */
+ IList sigAlgs = TlsUtilities.GetUsableSignatureAlgorithms(this.mSupportedSignatureAlgorithms);
+
+ /*
+ * RFC 4429 5.1. A server that receives a ClientHello containing one or both of these
+ * extensions MUST use the client's enumerated capabilities to guide its selection of an
+ * appropriate cipher suite. One of the proposed ECC cipher suites must be negotiated only
+ * if the server can successfully complete the handshake while using the curves and point
+ * formats supported by the client [...].
+ */
+ bool eccCipherSuitesEnabled = SupportsClientEccCapabilities(this.mNamedCurves, this.mClientECPointFormats);
+
+ int[] cipherSuites = GetCipherSuites();
+ for (int i = 0; i < cipherSuites.Length; ++i)
+ {
+ int cipherSuite = cipherSuites[i];
+
+ if (Arrays.Contains(this.mOfferedCipherSuites, cipherSuite)
+ && (eccCipherSuitesEnabled || !TlsEccUtilities.IsEccCipherSuite(cipherSuite))
+ && TlsUtilities.IsValidCipherSuiteForVersion(cipherSuite, mServerVersion)
+ && TlsUtilities.IsValidCipherSuiteForSignatureAlgorithms(cipherSuite, sigAlgs))
+ {
+ return this.mSelectedCipherSuite = cipherSuite;
+ }
+ }
+ throw new TlsFatalAlert(AlertDescription.handshake_failure);
+ }
+
+ public virtual byte GetSelectedCompressionMethod()
+ {
+ byte[] compressionMethods = GetCompressionMethods();
+ for (int i = 0; i < compressionMethods.Length; ++i)
+ {
+ if (Arrays.Contains(mOfferedCompressionMethods, compressionMethods[i]))
+ {
+ return this.mSelectedCompressionMethod = compressionMethods[i];
+ }
+ }
+ throw new TlsFatalAlert(AlertDescription.handshake_failure);
+ }
+
+ // IDictionary is (Int32 -> byte[])
+ public virtual IDictionary GetServerExtensions()
+ {
+ if (this.mEncryptThenMacOffered && AllowEncryptThenMac)
+ {
+ /*
+ * RFC 7366 3. If a server receives an encrypt-then-MAC request extension from a client
+ * and then selects a stream or Authenticated Encryption with Associated Data (AEAD)
+ * ciphersuite, it MUST NOT send an encrypt-then-MAC response extension back to the
+ * client.
+ */
+ if (TlsUtilities.IsBlockCipherSuite(this.mSelectedCipherSuite))
+ {
+ TlsExtensionsUtilities.AddEncryptThenMacExtension(CheckServerExtensions());
+ }
+ }
+
+ if (this.mMaxFragmentLengthOffered >= 0
+ && TlsUtilities.IsValidUint8(mMaxFragmentLengthOffered)
+ && MaxFragmentLength.IsValid((byte)mMaxFragmentLengthOffered))
+ {
+ TlsExtensionsUtilities.AddMaxFragmentLengthExtension(CheckServerExtensions(), (byte)mMaxFragmentLengthOffered);
+ }
+
+ if (this.mTruncatedHMacOffered && AllowTruncatedHMac)
+ {
+ TlsExtensionsUtilities.AddTruncatedHMacExtension(CheckServerExtensions());
+ }
+
+ if (this.mClientECPointFormats != null && TlsEccUtilities.IsEccCipherSuite(this.mSelectedCipherSuite))
+ {
+ /*
+ * RFC 4492 5.2. A server that selects an ECC cipher suite in response to a ClientHello
+ * message including a Supported Point Formats Extension appends this extension (along
+ * with others) to its ServerHello message, enumerating the point formats it can parse.
+ */
+ this.mServerECPointFormats = new byte[]{ ECPointFormat.uncompressed,
+ ECPointFormat.ansiX962_compressed_prime, ECPointFormat.ansiX962_compressed_char2, };
+
+ TlsEccUtilities.AddSupportedPointFormatsExtension(CheckServerExtensions(), mServerECPointFormats);
+ }
+
+ return mServerExtensions;
+ }
+
+ public virtual IList GetServerSupplementalData()
+ {
+ return null;
+ }
+
+ public abstract TlsCredentials GetCredentials();
+
+ public virtual CertificateStatus GetCertificateStatus()
+ {
+ return null;
+ }
+
+ public abstract TlsKeyExchange GetKeyExchange();
+
+ public virtual CertificateRequest GetCertificateRequest()
+ {
+ return null;
+ }
+
+ public virtual void ProcessClientSupplementalData(IList clientSupplementalData)
+ {
+ if (clientSupplementalData != null)
+ throw new TlsFatalAlert(AlertDescription.unexpected_message);
+ }
+
+ public virtual void NotifyClientCertificate(Certificate clientCertificate)
+ {
+ throw new TlsFatalAlert(AlertDescription.internal_error);
+ }
+
+ public override TlsCompression GetCompression()
+ {
+ switch (mSelectedCompressionMethod)
+ {
+ case CompressionMethod.cls_null:
+ return new TlsNullCompression();
+
+ default:
+ /*
+ * Note: internal error here; we selected the compression method, so if we now can't
+ * produce an implementation, we shouldn't have chosen it!
+ */
+ throw new TlsFatalAlert(AlertDescription.internal_error);
+ }
+ }
+
+ public override TlsCipher GetCipher()
+ {
+ int encryptionAlgorithm = TlsUtilities.GetEncryptionAlgorithm(mSelectedCipherSuite);
+ int macAlgorithm = TlsUtilities.GetMacAlgorithm(mSelectedCipherSuite);
+
+ return mCipherFactory.CreateCipher(mContext, encryptionAlgorithm, macAlgorithm);
+ }
+
+ public virtual NewSessionTicket GetNewSessionTicket()
+ {
+ /*
+ * RFC 5077 3.3. If the server determines that it does not want to include a ticket after it
+ * has included the SessionTicket extension in the ServerHello, then it sends a zero-length
+ * ticket in the NewSessionTicket handshake message.
+ */
+ return new NewSessionTicket(0L, TlsUtilities.EmptyBytes);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsServer.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsServer.cs.meta
new file mode 100644
index 00000000..1964f9d7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsServer.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: faff47b25a0d7154f8ff18e0ab6843ed
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsSigner.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsSigner.cs
new file mode 100644
index 00000000..1f50eb49
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsSigner.cs
@@ -0,0 +1,54 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Tls
+{
+ public abstract class AbstractTlsSigner
+ : TlsSigner
+ {
+ protected TlsContext mContext;
+
+ public virtual void Init(TlsContext context)
+ {
+ this.mContext = context;
+ }
+
+ public virtual byte[] GenerateRawSignature(AsymmetricKeyParameter privateKey, byte[] md5AndSha1)
+ {
+ return GenerateRawSignature(null, privateKey, md5AndSha1);
+ }
+
+ public abstract byte[] GenerateRawSignature(SignatureAndHashAlgorithm algorithm,
+ AsymmetricKeyParameter privateKey, byte[] hash);
+
+ public virtual bool VerifyRawSignature(byte[] sigBytes, AsymmetricKeyParameter publicKey, byte[] md5AndSha1)
+ {
+ return VerifyRawSignature(null, sigBytes, publicKey, md5AndSha1);
+ }
+
+ public abstract bool VerifyRawSignature(SignatureAndHashAlgorithm algorithm, byte[] sigBytes,
+ AsymmetricKeyParameter publicKey, byte[] hash);
+
+ public virtual ISigner CreateSigner(AsymmetricKeyParameter privateKey)
+ {
+ return CreateSigner(null, privateKey);
+ }
+
+ public abstract ISigner CreateSigner(SignatureAndHashAlgorithm algorithm, AsymmetricKeyParameter privateKey);
+
+ public virtual ISigner CreateVerifyer(AsymmetricKeyParameter publicKey)
+ {
+ return CreateVerifyer(null, publicKey);
+ }
+
+ public abstract ISigner CreateVerifyer(SignatureAndHashAlgorithm algorithm, AsymmetricKeyParameter publicKey);
+
+ public abstract bool IsValidPublicKey(AsymmetricKeyParameter publicKey);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsSigner.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsSigner.cs.meta
new file mode 100644
index 00000000..de665c91
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsSigner.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0d7986fd51deb2444927d8eb012464dd
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsSignerCredentials.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsSignerCredentials.cs
new file mode 100644
index 00000000..c7869662
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsSignerCredentials.cs
@@ -0,0 +1,24 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Tls
+{
+ public abstract class AbstractTlsSignerCredentials
+ : AbstractTlsCredentials, TlsSignerCredentials
+ {
+ ///
+ public abstract byte[] GenerateCertificateSignature(byte[] hash);
+
+ public virtual SignatureAndHashAlgorithm SignatureAndHashAlgorithm
+ {
+ get
+ {
+ throw new InvalidOperationException("TlsSignerCredentials implementation does not support (D)TLS 1.2+");
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsSignerCredentials.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsSignerCredentials.cs.meta
new file mode 100644
index 00000000..8851f3fc
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AbstractTlsSignerCredentials.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 6c1498aa1db4f844e9473a971d4efbd2
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AlertDescription.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AlertDescription.cs
new file mode 100644
index 00000000..6135d2e6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AlertDescription.cs
@@ -0,0 +1,308 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Tls
+{
+ ///
+ /// RFC 5246 7.2
+ ///
+ public abstract class AlertDescription
+ {
+ /**
+ * This message notifies the recipient that the sender will not send any more messages on this
+ * connection. Note that as of TLS 1.1, failure to properly close a connection no longer
+ * requires that a session not be resumed. This is a change from TLS 1.0 ("The session becomes
+ * unresumable if any connection is terminated without proper close_notify messages with level
+ * equal to warning.") to conform with widespread implementation practice.
+ */
+ public const byte close_notify = 0;
+
+ /**
+ * An inappropriate message was received. This alert is always fatal and should never be
+ * observed in communication between proper implementations.
+ */
+ public const byte unexpected_message = 10;
+
+ /**
+ * This alert is returned if a record is received with an incorrect MAC. This alert also MUST be
+ * returned if an alert is sent because a TLSCiphertext decrypted in an invalid way: either it
+ * wasn't an even multiple of the block length, or its padding values, when checked, weren't
+ * correct. This message is always fatal and should never be observed in communication between
+ * proper implementations (except when messages were corrupted in the network).
+ */
+ public const byte bad_record_mac = 20;
+
+ /**
+ * This alert was used in some earlier versions of TLS, and may have permitted certain attacks
+ * against the CBC mode [CBCATT]. It MUST NOT be sent by compliant implementations.
+ */
+ public const byte decryption_failed = 21;
+
+ /**
+ * A TLSCiphertext record was received that had a length more than 2^14+2048 bytes, or a record
+ * decrypted to a TLSCompressed record with more than 2^14+1024 bytes. This message is always
+ * fatal and should never be observed in communication between proper implementations (except
+ * when messages were corrupted in the network).
+ */
+ public const byte record_overflow = 22;
+
+ /**
+ * The decompression function received improper input (e.g., data that would expand to excessive
+ * length). This message is always fatal and should never be observed in communication between
+ * proper implementations.
+ */
+ public const byte decompression_failure = 30;
+
+ /**
+ * Reception of a handshake_failure alert message indicates that the sender was unable to
+ * negotiate an acceptable set of security parameters given the options available. This is a
+ * fatal error.
+ */
+ public const byte handshake_failure = 40;
+
+ /**
+ * This alert was used in SSLv3 but not any version of TLS. It MUST NOT be sent by compliant
+ * implementations.
+ */
+ public const byte no_certificate = 41;
+
+ /**
+ * A certificate was corrupt, contained signatures that did not verify correctly, etc.
+ */
+ public const byte bad_certificate = 42;
+
+ /**
+ * A certificate was of an unsupported type.
+ */
+ public const byte unsupported_certificate = 43;
+
+ /**
+ * A certificate was revoked by its signer.
+ */
+ public const byte certificate_revoked = 44;
+
+ /**
+ * A certificate has expired or is not currently valid.
+ */
+ public const byte certificate_expired = 45;
+
+ /**
+ * Some other (unspecified) issue arose in processing the certificate, rendering it
+ * unacceptable.
+ */
+ public const byte certificate_unknown = 46;
+
+ /**
+ * A field in the handshake was out of range or inconsistent with other fields. This message is
+ * always fatal.
+ */
+ public const byte illegal_parameter = 47;
+
+ /**
+ * A valid certificate chain or partial chain was received, but the certificate was not accepted
+ * because the CA certificate could not be located or couldn't be matched with a known, trusted
+ * CA. This message is always fatal.
+ */
+ public const byte unknown_ca = 48;
+
+ /**
+ * A valid certificate was received, but when access control was applied, the sender decided not
+ * to proceed with negotiation. This message is always fatal.
+ */
+ public const byte access_denied = 49;
+
+ /**
+ * A message could not be decoded because some field was out of the specified range or the
+ * length of the message was incorrect. This message is always fatal and should never be
+ * observed in communication between proper implementations (except when messages were corrupted
+ * in the network).
+ */
+ public const byte decode_error = 50;
+
+ /**
+ * A handshake cryptographic operation failed, including being unable to correctly verify a
+ * signature or validate a Finished message. This message is always fatal.
+ */
+ public const byte decrypt_error = 51;
+
+ /**
+ * This alert was used in some earlier versions of TLS. It MUST NOT be sent by compliant
+ * implementations.
+ */
+ public const byte export_restriction = 60;
+
+ /**
+ * The protocol version the client has attempted to negotiate is recognized but not supported.
+ * (For example, old protocol versions might be avoided for security reasons.) This message is
+ * always fatal.
+ */
+ public const byte protocol_version = 70;
+
+ /**
+ * Returned instead of handshake_failure when a negotiation has failed specifically because the
+ * server requires ciphers more secure than those supported by the client. This message is
+ * always fatal.
+ */
+ public const byte insufficient_security = 71;
+
+ /**
+ * An internal error unrelated to the peer or the correctness of the protocol (such as a memory
+ * allocation failure) makes it impossible to continue. This message is always fatal.
+ */
+ public const byte internal_error = 80;
+
+ /**
+ * This handshake is being canceled for some reason unrelated to a protocol failure. If the user
+ * cancels an operation after the handshake is complete, just closing the connection by sending
+ * a close_notify is more appropriate. This alert should be followed by a close_notify. This
+ * message is generally a warning.
+ */
+ public const byte user_canceled = 90;
+
+ /**
+ * Sent by the client in response to a hello request or by the server in response to a client
+ * hello after initial handshaking. Either of these would normally lead to renegotiation; when
+ * that is not appropriate, the recipient should respond with this alert. At that point, the
+ * original requester can decide whether to proceed with the connection. One case where this
+ * would be appropriate is where a server has spawned a process to satisfy a request; the
+ * process might receive security parameters (key length, authentication, etc.) at startup, and
+ * it might be difficult to communicate changes to these parameters after that point. This
+ * message is always a warning.
+ */
+ public const byte no_renegotiation = 100;
+
+ /**
+ * Sent by clients that receive an extended server hello containing an extension that they did
+ * not put in the corresponding client hello. This message is always fatal.
+ */
+ public const byte unsupported_extension = 110;
+
+ /*
+ * RFC 3546
+ */
+
+ /**
+ * This alert is sent by servers who are unable to retrieve a certificate chain from the URL
+ * supplied by the client (see Section 3.3). This message MAY be fatal - for example if client
+ * authentication is required by the server for the handshake to continue and the server is
+ * unable to retrieve the certificate chain, it may send a fatal alert.
+ */
+ public const byte certificate_unobtainable = 111;
+
+ /**
+ * This alert is sent by servers that receive a server_name extension request, but do not
+ * recognize the server name. This message MAY be fatal.
+ */
+ public const byte unrecognized_name = 112;
+
+ /**
+ * This alert is sent by clients that receive an invalid certificate status response (see
+ * Section 3.6). This message is always fatal.
+ */
+ public const byte bad_certificate_status_response = 113;
+
+ /**
+ * This alert is sent by servers when a certificate hash does not match a client provided
+ * certificate_hash. This message is always fatal.
+ */
+ public const byte bad_certificate_hash_value = 114;
+
+ /*
+ * RFC 4279
+ */
+
+ /**
+ * If the server does not recognize the PSK identity, it MAY respond with an
+ * "unknown_psk_identity" alert message.
+ */
+ public const byte unknown_psk_identity = 115;
+
+ /*
+ * RFC 7507
+ */
+
+ /**
+ * If TLS_FALLBACK_SCSV appears in ClientHello.cipher_suites and the highest protocol version
+ * supported by the server is higher than the version indicated in ClientHello.client_version,
+ * the server MUST respond with a fatal inappropriate_fallback alert [..].
+ */
+ public const byte inappropriate_fallback = 86;
+
+ public static string GetName(byte alertDescription)
+ {
+ switch (alertDescription)
+ {
+ case close_notify:
+ return "close_notify";
+ case unexpected_message:
+ return "unexpected_message";
+ case bad_record_mac:
+ return "bad_record_mac";
+ case decryption_failed:
+ return "decryption_failed";
+ case record_overflow:
+ return "record_overflow";
+ case decompression_failure:
+ return "decompression_failure";
+ case handshake_failure:
+ return "handshake_failure";
+ case no_certificate:
+ return "no_certificate";
+ case bad_certificate:
+ return "bad_certificate";
+ case unsupported_certificate:
+ return "unsupported_certificate";
+ case certificate_revoked:
+ return "certificate_revoked";
+ case certificate_expired:
+ return "certificate_expired";
+ case certificate_unknown:
+ return "certificate_unknown";
+ case illegal_parameter:
+ return "illegal_parameter";
+ case unknown_ca:
+ return "unknown_ca";
+ case access_denied:
+ return "access_denied";
+ case decode_error:
+ return "decode_error";
+ case decrypt_error:
+ return "decrypt_error";
+ case export_restriction:
+ return "export_restriction";
+ case protocol_version:
+ return "protocol_version";
+ case insufficient_security:
+ return "insufficient_security";
+ case internal_error:
+ return "internal_error";
+ case user_canceled:
+ return "user_canceled";
+ case no_renegotiation:
+ return "no_renegotiation";
+ case unsupported_extension:
+ return "unsupported_extension";
+ case certificate_unobtainable:
+ return "certificate_unobtainable";
+ case unrecognized_name:
+ return "unrecognized_name";
+ case bad_certificate_status_response:
+ return "bad_certificate_status_response";
+ case bad_certificate_hash_value:
+ return "bad_certificate_hash_value";
+ case unknown_psk_identity:
+ return "unknown_psk_identity";
+ case inappropriate_fallback:
+ return "inappropriate_fallback";
+ default:
+ return "UNKNOWN";
+ }
+ }
+
+ public static string GetText(byte alertDescription)
+ {
+ return GetName(alertDescription) + "(" + alertDescription + ")";
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AlertDescription.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AlertDescription.cs.meta
new file mode 100644
index 00000000..c52faa2d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AlertDescription.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0e83bdd3959fac74eb57e28a1ffd3fe0
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AlertLevel.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AlertLevel.cs
new file mode 100644
index 00000000..e19cf4e0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AlertLevel.cs
@@ -0,0 +1,33 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Tls
+{
+ ///
+ /// RFC 5246 7.2
+ ///
+ public abstract class AlertLevel
+ {
+ public const byte warning = 1;
+ public const byte fatal = 2;
+
+ public static string GetName(byte alertDescription)
+ {
+ switch (alertDescription)
+ {
+ case warning:
+ return "warning";
+ case fatal:
+ return "fatal";
+ default:
+ return "UNKNOWN";
+ }
+ }
+
+ public static string GetText(byte alertDescription)
+ {
+ return GetName(alertDescription) + "(" + alertDescription + ")";
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AlertLevel.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AlertLevel.cs.meta
new file mode 100644
index 00000000..4bba27ab
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AlertLevel.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: f5a7ce7fd31dd384680237a5e4538758
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AlwaysValidVerifyer.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AlwaysValidVerifyer.cs
new file mode 100644
index 00000000..0710fafa
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AlwaysValidVerifyer.cs
@@ -0,0 +1,25 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+
+namespace Org.BouncyCastle.Crypto.Tls
+{
+ ///
+ /// A certificate verifyer, that will always return true.
+ ///
+ /// DO NOT USE THIS FILE UNLESS YOU KNOW EXACTLY WHAT YOU ARE DOING.
+ ///
+ ///
+ public class AlwaysValidVerifyer : ICertificateVerifyer
+ {
+ /// Return true.
+ public bool IsValid(Uri targetUri, X509CertificateStructure[] certs)
+ {
+ return true;
+ }
+ }
+}
+
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AlwaysValidVerifyer.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AlwaysValidVerifyer.cs.meta
new file mode 100644
index 00000000..0d63c847
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/AlwaysValidVerifyer.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 50fdbee77ed43ea4598b7a52994f3323
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/BasicTlsPskIdentity.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/BasicTlsPskIdentity.cs
new file mode 100644
index 00000000..57dc3291
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/BasicTlsPskIdentity.cs
@@ -0,0 +1,47 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Tls
+{
+ public class BasicTlsPskIdentity
+ : TlsPskIdentity
+ {
+ protected byte[] mIdentity;
+ protected byte[] mPsk;
+
+ public BasicTlsPskIdentity(byte[] identity, byte[] psk)
+ {
+ this.mIdentity = Arrays.Clone(identity);
+ this.mPsk = Arrays.Clone(psk);
+ }
+
+ public BasicTlsPskIdentity(string identity, byte[] psk)
+ {
+ this.mIdentity = Strings.ToUtf8ByteArray(identity);
+ this.mPsk = Arrays.Clone(psk);
+ }
+
+ public virtual void SkipIdentityHint()
+ {
+ }
+
+ public virtual void NotifyIdentityHint(byte[] psk_identity_hint)
+ {
+ }
+
+ public virtual byte[] GetPskIdentity()
+ {
+ return mIdentity;
+ }
+
+ public virtual byte[] GetPsk()
+ {
+ return mPsk;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/BasicTlsPskIdentity.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/BasicTlsPskIdentity.cs.meta
new file mode 100644
index 00000000..207fa45d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/BasicTlsPskIdentity.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a7efbf194a43ae849b278789c2f9afcb
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/BulkCipherAlgorithm.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/BulkCipherAlgorithm.cs
new file mode 100644
index 00000000..6a877d87
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/BulkCipherAlgorithm.cs
@@ -0,0 +1,29 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Tls
+{
+ /// RFC 2246
+ ///
+ /// Note that the values here are implementation-specific and arbitrary. It is recommended not to
+ /// depend on the particular values (e.g. serialization).
+ ///
+ public abstract class BulkCipherAlgorithm
+ {
+ public const int cls_null = 0;
+ public const int rc4 = 1;
+ public const int rc2 = 2;
+ public const int des = 3;
+ public const int cls_3des = 4;
+ public const int des40 = 5;
+
+ /*
+ * RFC 4346
+ */
+ public const int aes = 6;
+ public const int idea = 7;
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/BulkCipherAlgorithm.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/BulkCipherAlgorithm.cs.meta
new file mode 100644
index 00000000..dee46efa
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/BulkCipherAlgorithm.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ed9ea69cd7f421b4a9c8a02dd294b729
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/ByteQueue.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/ByteQueue.cs
new file mode 100644
index 00000000..6d65a26c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/ByteQueue.cs
@@ -0,0 +1,215 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Tls
+{
+ ///
+ /// A queue for bytes.
+ ///
+ /// This file could be more optimized.
+ ///
+ ///
+ public class ByteQueue
+ {
+ /// The smallest number which can be written as 2^x which is bigger than i.
+ public static int NextTwoPow(
+ int i)
+ {
+ /*
+ * This code is based of a lot of code I found on the Internet
+ * which mostly referenced a book called "Hacking delight".
+ *
+ */
+ i |= (i >> 1);
+ i |= (i >> 2);
+ i |= (i >> 4);
+ i |= (i >> 8);
+ i |= (i >> 16);
+ return i + 1;
+ }
+
+ /**
+ * The initial size for our buffer.
+ */
+ private const int DefaultCapacity = 1024;
+
+ /**
+ * The buffer where we store our data.
+ */
+ private byte[] databuf;
+
+ /**
+ * How many bytes at the beginning of the buffer are skipped.
+ */
+ private int skipped = 0;
+
+ /**
+ * How many bytes in the buffer are valid data.
+ */
+ private int available = 0;
+
+ private bool readOnlyBuf = false;
+
+ public ByteQueue()
+ : this(DefaultCapacity)
+ {
+ }
+
+ public ByteQueue(int capacity)
+ {
+ this.databuf = capacity == 0 ? TlsUtilities.EmptyBytes : new byte[capacity];
+ }
+
+ public ByteQueue(byte[] buf, int off, int len)
+ {
+ this.databuf = buf;
+ this.skipped = off;
+ this.available = len;
+ this.readOnlyBuf = true;
+ }
+
+ /// Add some data to our buffer.
+ /// A byte-array to read data from.
+ /// How many bytes to skip at the beginning of the array.
+ /// How many bytes to read from the array.
+ public void AddData(
+ byte[] data,
+ int offset,
+ int len)
+ {
+ if (readOnlyBuf)
+ throw new InvalidOperationException("Cannot add data to read-only buffer");
+
+ if ((skipped + available + len) > databuf.Length)
+ {
+ int desiredSize = ByteQueue.NextTwoPow(available + len);
+ if (desiredSize > databuf.Length)
+ {
+ byte[] tmp = new byte[desiredSize];
+ Array.Copy(databuf, skipped, tmp, 0, available);
+ databuf = tmp;
+ }
+ else
+ {
+ Array.Copy(databuf, skipped, databuf, 0, available);
+ }
+ skipped = 0;
+ }
+
+ Array.Copy(data, offset, databuf, skipped + available, len);
+ available += len;
+ }
+
+ /// The number of bytes which are available in this buffer.
+ public int Available
+ {
+ get { return available; }
+ }
+
+ /// Copy some bytes from the beginning of the data to the provided Stream.
+ /// The Stream to copy the bytes to.
+ /// How many bytes to copy.
+ /// If insufficient data is available.
+ /// If there is a problem copying the data.
+ public void CopyTo(Stream output, int length)
+ {
+ if (length > available)
+ throw new InvalidOperationException("Cannot copy " + length + " bytes, only got " + available);
+
+ output.Write(databuf, skipped, length);
+ }
+
+ /// Read data from the buffer.
+ /// The buffer where the read data will be copied to.
+ /// How many bytes to skip at the beginning of buf.
+ /// How many bytes to read at all.
+ /// How many bytes from our data to skip.
+ public void Read(
+ byte[] buf,
+ int offset,
+ int len,
+ int skip)
+ {
+ if ((buf.Length - offset) < len)
+ {
+ throw new ArgumentException("Buffer size of " + buf.Length + " is too small for a read of " + len + " bytes");
+ }
+ if ((available - skip) < len)
+ {
+ throw new InvalidOperationException("Not enough data to read");
+ }
+ Array.Copy(databuf, skipped + skip, buf, offset, len);
+ }
+
+ /// Return a MemoryStream over some bytes at the beginning of the data.
+ /// How many bytes will be readable.
+ /// A MemoryStream over the data.
+ /// If insufficient data is available.
+ public MemoryStream ReadFrom(int length)
+ {
+ if (length > available)
+ throw new InvalidOperationException("Cannot read " + length + " bytes, only got " + available);
+
+ int position = skipped;
+
+ available -= length;
+ skipped += length;
+
+ return new MemoryStream(databuf, position, length, false);
+ }
+
+ /// Remove some bytes from our data from the beginning.
+ /// How many bytes to remove.
+ public void RemoveData(
+ int i)
+ {
+ if (i > available)
+ {
+ throw new InvalidOperationException("Cannot remove " + i + " bytes, only got " + available);
+ }
+
+ /*
+ * Skip the data.
+ */
+ available -= i;
+ skipped += i;
+ }
+
+ public void RemoveData(byte[] buf, int off, int len, int skip)
+ {
+ Read(buf, off, len, skip);
+ RemoveData(skip + len);
+ }
+
+ public byte[] RemoveData(int len, int skip)
+ {
+ byte[] buf = new byte[len];
+ RemoveData(buf, 0, len, skip);
+ return buf;
+ }
+
+ public void Shrink()
+ {
+ if (available == 0)
+ {
+ databuf = TlsUtilities.EmptyBytes;
+ skipped = 0;
+ }
+ else
+ {
+ int desiredSize = ByteQueue.NextTwoPow(available);
+ if (desiredSize < databuf.Length)
+ {
+ byte[] tmp = new byte[desiredSize];
+ Array.Copy(databuf, skipped, tmp, 0, available);
+ databuf = tmp;
+ skipped = 0;
+ }
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/ByteQueue.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/ByteQueue.cs.meta
new file mode 100644
index 00000000..49f59a31
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/ByteQueue.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: e0b6d03f89d72e64da9242c29d55083d
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/ByteQueueStream.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/ByteQueueStream.cs
new file mode 100644
index 00000000..f8c3417b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/ByteQueueStream.cs
@@ -0,0 +1,114 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Tls
+{
+ public class ByteQueueStream
+ : Stream
+ {
+ private readonly ByteQueue buffer;
+
+ public ByteQueueStream()
+ {
+ this.buffer = new ByteQueue();
+ }
+
+ public virtual int Available
+ {
+ get { return buffer.Available; }
+ }
+
+ public override bool CanRead
+ {
+ get { return true; }
+ }
+
+ public override bool CanSeek
+ {
+ get { return false; }
+ }
+
+ public override bool CanWrite
+ {
+ get { return true; }
+ }
+
+ public override void Flush()
+ {
+ }
+
+ public override long Length
+ {
+ get { throw new NotSupportedException(); }
+ }
+
+ public virtual int Peek(byte[] buf)
+ {
+ int bytesToRead = System.Math.Min(buffer.Available, buf.Length);
+ buffer.Read(buf, 0, bytesToRead, 0);
+ return bytesToRead;
+ }
+
+ public override long Position
+ {
+ get { throw new NotSupportedException(); }
+ set { throw new NotSupportedException(); }
+ }
+
+ public virtual int Read(byte[] buf)
+ {
+ return Read(buf, 0, buf.Length);
+ }
+
+ public override int Read(byte[] buf, int off, int len)
+ {
+ int bytesToRead = System.Math.Min(buffer.Available, len);
+ buffer.RemoveData(buf, off, bytesToRead, 0);
+ return bytesToRead;
+ }
+
+ public override int ReadByte()
+ {
+ if (buffer.Available == 0)
+ return -1;
+
+ return buffer.RemoveData(1, 0)[0] & 0xFF;
+ }
+
+ public override long Seek(long offset, SeekOrigin origin)
+ {
+ throw new NotSupportedException();
+ }
+
+ public override void SetLength(long value)
+ {
+ throw new NotSupportedException();
+ }
+
+ public virtual int Skip(int n)
+ {
+ int bytesToSkip = System.Math.Min(buffer.Available, n);
+ buffer.RemoveData(bytesToSkip);
+ return bytesToSkip;
+ }
+
+ public virtual void Write(byte[] buf)
+ {
+ buffer.AddData(buf, 0, buf.Length);
+ }
+
+ public override void Write(byte[] buf, int off, int len)
+ {
+ buffer.AddData(buf, off, len);
+ }
+
+ public override void WriteByte(byte b)
+ {
+ buffer.AddData(new byte[]{ b }, 0, 1);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/ByteQueueStream.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/ByteQueueStream.cs.meta
new file mode 100644
index 00000000..3ce48d79
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/ByteQueueStream.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: fec5e2d706f06ac4eacec774c074001a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/CertChainType.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/CertChainType.cs
new file mode 100644
index 00000000..cc109b66
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/CertChainType.cs
@@ -0,0 +1,22 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Tls
+{
+ /*
+ * RFC 3546 3.3.
+ */
+ public abstract class CertChainType
+ {
+ public const byte individual_certs = 0;
+ public const byte pkipath = 1;
+
+ public static bool IsValid(byte certChainType)
+ {
+ return certChainType >= individual_certs && certChainType <= pkipath;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/CertChainType.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/CertChainType.cs.meta
new file mode 100644
index 00000000..eea30181
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/CertChainType.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 8bc6b0ebc7686e944b7bb9ab70a50f50
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/Certificate.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/Certificate.cs
new file mode 100644
index 00000000..54201af1
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/crypto/tls/Certificate.cs
@@ -0,0 +1,140 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Tls
+{
+ /**
+ * Parsing and encoding of a Certificate struct from RFC 4346.
+ *
+ *
+ */
+ public class OcspReq
+ : X509ExtensionBase
+ {
+ private OcspRequest req;
+
+ public OcspReq(
+ OcspRequest req)
+ {
+ this.req = req;
+ }
+
+ public OcspReq(
+ byte[] req)
+ : this(new Asn1InputStream(req))
+ {
+ }
+
+ public OcspReq(
+ Stream inStr)
+ : this(new Asn1InputStream(inStr))
+ {
+ }
+
+ private OcspReq(
+ Asn1InputStream aIn)
+ {
+ try
+ {
+ this.req = OcspRequest.GetInstance(aIn.ReadObject());
+ }
+ catch (ArgumentException e)
+ {
+ throw new IOException("malformed request: " + e.Message);
+ }
+ catch (InvalidCastException e)
+ {
+ throw new IOException("malformed request: " + e.Message);
+ }
+ }
+
+ /**
+ * Return the DER encoding of the tbsRequest field.
+ * @return DER encoding of tbsRequest
+ * @throws OcspException in the event of an encoding error.
+ */
+ public byte[] GetTbsRequest()
+ {
+ try
+ {
+ return req.TbsRequest.GetEncoded();
+ }
+ catch (IOException e)
+ {
+ throw new OcspException("problem encoding tbsRequest", e);
+ }
+ }
+
+ public int Version
+ {
+ get { return req.TbsRequest.Version.Value.IntValue + 1; }
+ }
+
+ public GeneralName RequestorName
+ {
+ get { return GeneralName.GetInstance(req.TbsRequest.RequestorName); }
+ }
+
+ public Req[] GetRequestList()
+ {
+ Asn1Sequence seq = req.TbsRequest.RequestList;
+ Req[] requests = new Req[seq.Count];
+
+ for (int i = 0; i != requests.Length; i++)
+ {
+ requests[i] = new Req(Request.GetInstance(seq[i]));
+ }
+
+ return requests;
+ }
+
+ public X509Extensions RequestExtensions
+ {
+ get { return X509Extensions.GetInstance(req.TbsRequest.RequestExtensions); }
+ }
+
+ protected override X509Extensions GetX509Extensions()
+ {
+ return RequestExtensions;
+ }
+
+ /**
+ * return the object identifier representing the signature algorithm
+ */
+ public string SignatureAlgOid
+ {
+ get
+ {
+ if (!this.IsSigned)
+ return null;
+
+ return req.OptionalSignature.SignatureAlgorithm.Algorithm.Id;
+ }
+ }
+
+ public byte[] GetSignature()
+ {
+ if (!this.IsSigned)
+ return null;
+
+ return req.OptionalSignature.GetSignatureOctets();
+ }
+
+ private IList GetCertList()
+ {
+ // load the certificates if we have any
+
+ IList certs = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ Asn1Sequence s = req.OptionalSignature.Certs;
+
+ if (s != null)
+ {
+ foreach (Asn1Encodable ae in s)
+ {
+ try
+ {
+ certs.Add(new X509CertificateParser().ReadCertificate(ae.GetEncoded()));
+ }
+ catch (Exception e)
+ {
+ throw new OcspException("can't re-encode certificate!", e);
+ }
+ }
+ }
+
+ return certs;
+ }
+
+ public X509Certificate[] GetCerts()
+ {
+ if (!this.IsSigned)
+ return null;
+
+ IList certs = this.GetCertList();
+ X509Certificate[] result = new X509Certificate[certs.Count];
+ for (int i = 0; i < certs.Count; ++i)
+ {
+ result[i] = (X509Certificate)certs[i];
+ }
+ return result;
+ }
+
+ /**
+ * If the request is signed return a possibly empty CertStore containing the certificates in the
+ * request. If the request is not signed the method returns null.
+ *
+ * @return null if not signed, a CertStore otherwise
+ * @throws OcspException
+ */
+ public IX509Store GetCertificates(
+ string type)
+ {
+ if (!this.IsSigned)
+ return null;
+
+ try
+ {
+ return X509StoreFactory.Create(
+ "Certificate/" + type,
+ new X509CollectionStoreParameters(this.GetCertList()));
+ }
+ catch (Exception e)
+ {
+ throw new OcspException("can't setup the CertStore", e);
+ }
+ }
+
+ /**
+ * Return whether or not this request is signed.
+ *
+ * @return true if signed false otherwise.
+ */
+ public bool IsSigned
+ {
+ get { return req.OptionalSignature != null; }
+ }
+
+ /**
+ * Verify the signature against the TBSRequest object we contain.
+ */
+ public bool Verify(
+ AsymmetricKeyParameter publicKey)
+ {
+ if (!this.IsSigned)
+ throw new OcspException("attempt to Verify signature on unsigned object");
+
+ try
+ {
+ ISigner signature = SignerUtilities.GetSigner(this.SignatureAlgOid);
+
+ signature.Init(false, publicKey);
+
+ byte[] encoded = req.TbsRequest.GetEncoded();
+
+ signature.BlockUpdate(encoded, 0, encoded.Length);
+
+ return signature.VerifySignature(this.GetSignature());
+ }
+ catch (Exception e)
+ {
+ throw new OcspException("exception processing sig: " + e, e);
+ }
+ }
+
+ /**
+ * return the ASN.1 encoded representation of this object.
+ */
+ public byte[] GetEncoded()
+ {
+ return req.GetEncoded();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPReq.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPReq.cs.meta
new file mode 100644
index 00000000..4210b99a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPReq.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0f95b7ecb00c00241947e9d20299129b
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPReqGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPReqGenerator.cs
new file mode 100644
index 00000000..26cea1c6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPReqGenerator.cs
@@ -0,0 +1,247 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Ocsp;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Ocsp
+{
+ public class OcspReqGenerator
+ {
+ private IList list = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ private GeneralName requestorName = null;
+ private X509Extensions requestExtensions = null;
+
+ private class RequestObject
+ {
+ internal CertificateID certId;
+ internal X509Extensions extensions;
+
+ public RequestObject(
+ CertificateID certId,
+ X509Extensions extensions)
+ {
+ this.certId = certId;
+ this.extensions = extensions;
+ }
+
+ public Request ToRequest()
+ {
+ return new Request(certId.ToAsn1Object(), extensions);
+ }
+ }
+
+ /**
+ * Add a request for the given CertificateID.
+ *
+ * @param certId certificate ID of interest
+ */
+ public void AddRequest(
+ CertificateID certId)
+ {
+ list.Add(new RequestObject(certId, null));
+ }
+
+ /**
+ * Add a request with extensions
+ *
+ * @param certId certificate ID of interest
+ * @param singleRequestExtensions the extensions to attach to the request
+ */
+ public void AddRequest(
+ CertificateID certId,
+ X509Extensions singleRequestExtensions)
+ {
+ list.Add(new RequestObject(certId, singleRequestExtensions));
+ }
+
+ /**
+ * Set the requestor name to the passed in X509Principal
+ *
+ * @param requestorName a X509Principal representing the requestor name.
+ */
+ public void SetRequestorName(
+ X509Name requestorName)
+ {
+ try
+ {
+ this.requestorName = new GeneralName(GeneralName.DirectoryName, requestorName);
+ }
+ catch (Exception e)
+ {
+ throw new ArgumentException("cannot encode principal", e);
+ }
+ }
+
+ public void SetRequestorName(
+ GeneralName requestorName)
+ {
+ this.requestorName = requestorName;
+ }
+
+ public void SetRequestExtensions(
+ X509Extensions requestExtensions)
+ {
+ this.requestExtensions = requestExtensions;
+ }
+
+ private OcspReq GenerateRequest(
+ DerObjectIdentifier signingAlgorithm,
+ AsymmetricKeyParameter privateKey,
+ X509Certificate[] chain,
+ SecureRandom random)
+ {
+ Asn1EncodableVector requests = new Asn1EncodableVector();
+
+ foreach (RequestObject reqObj in list)
+ {
+ try
+ {
+ requests.Add(reqObj.ToRequest());
+ }
+ catch (Exception e)
+ {
+ throw new OcspException("exception creating Request", e);
+ }
+ }
+
+ TbsRequest tbsReq = new TbsRequest(requestorName, new DerSequence(requests), requestExtensions);
+
+ ISigner sig = null;
+ Signature signature = null;
+
+ if (signingAlgorithm != null)
+ {
+ if (requestorName == null)
+ {
+ throw new OcspException("requestorName must be specified if request is signed.");
+ }
+
+ try
+ {
+ sig = SignerUtilities.GetSigner(signingAlgorithm.Id);
+ if (random != null)
+ {
+ sig.Init(true, new ParametersWithRandom(privateKey, random));
+ }
+ else
+ {
+ sig.Init(true, privateKey);
+ }
+ }
+ catch (Exception e)
+ {
+ throw new OcspException("exception creating signature: " + e, e);
+ }
+
+ DerBitString bitSig = null;
+
+ try
+ {
+ byte[] encoded = tbsReq.GetEncoded();
+ sig.BlockUpdate(encoded, 0, encoded.Length);
+
+ bitSig = new DerBitString(sig.GenerateSignature());
+ }
+ catch (Exception e)
+ {
+ throw new OcspException("exception processing TBSRequest: " + e, e);
+ }
+
+ AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(signingAlgorithm, DerNull.Instance);
+
+ if (chain != null && chain.Length > 0)
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector();
+ try
+ {
+ for (int i = 0; i != chain.Length; i++)
+ {
+ v.Add(
+ X509CertificateStructure.GetInstance(
+ Asn1Object.FromByteArray(chain[i].GetEncoded())));
+ }
+ }
+ catch (IOException e)
+ {
+ throw new OcspException("error processing certs", e);
+ }
+ catch (CertificateEncodingException e)
+ {
+ throw new OcspException("error encoding certs", e);
+ }
+
+ signature = new Signature(sigAlgId, bitSig, new DerSequence(v));
+ }
+ else
+ {
+ signature = new Signature(sigAlgId, bitSig);
+ }
+ }
+
+ return new OcspReq(new OcspRequest(tbsReq, signature));
+ }
+
+ /**
+ * Generate an unsigned request
+ *
+ * @return the OcspReq
+ * @throws OcspException
+ */
+ public OcspReq Generate()
+ {
+ return GenerateRequest(null, null, null, null);
+ }
+
+ public OcspReq Generate(
+ string signingAlgorithm,
+ AsymmetricKeyParameter privateKey,
+ X509Certificate[] chain)
+ {
+ return Generate(signingAlgorithm, privateKey, chain, null);
+ }
+
+ public OcspReq Generate(
+ string signingAlgorithm,
+ AsymmetricKeyParameter privateKey,
+ X509Certificate[] chain,
+ SecureRandom random)
+ {
+ if (signingAlgorithm == null)
+ throw new ArgumentException("no signing algorithm specified");
+
+ try
+ {
+ DerObjectIdentifier oid = OcspUtilities.GetAlgorithmOid(signingAlgorithm);
+
+ return GenerateRequest(oid, privateKey, chain, random);
+ }
+ catch (ArgumentException)
+ {
+ throw new ArgumentException("unknown signing algorithm specified: " + signingAlgorithm);
+ }
+ }
+
+ /**
+ * Return an IEnumerable of the signature names supported by the generator.
+ *
+ * @return an IEnumerable containing recognised names.
+ */
+ public IEnumerable SignatureAlgNames
+ {
+ get { return OcspUtilities.AlgNames; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPReqGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPReqGenerator.cs.meta
new file mode 100644
index 00000000..baf3f18c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPReqGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 69f137c4a9de5b640b7e294ab4400582
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPResp.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPResp.cs
new file mode 100644
index 00000000..76dd262d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPResp.cs
@@ -0,0 +1,104 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Ocsp;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Ocsp
+{
+ public class OcspResp
+ {
+ private OcspResponse resp;
+
+ public OcspResp(
+ OcspResponse resp)
+ {
+ this.resp = resp;
+ }
+
+ public OcspResp(
+ byte[] resp)
+ : this(new Asn1InputStream(resp))
+ {
+ }
+
+ public OcspResp(
+ Stream inStr)
+ : this(new Asn1InputStream(inStr))
+ {
+ }
+
+ private OcspResp(
+ Asn1InputStream aIn)
+ {
+ try
+ {
+ this.resp = OcspResponse.GetInstance(aIn.ReadObject());
+ }
+ catch (Exception e)
+ {
+ throw new IOException("malformed response: " + e.Message, e);
+ }
+ }
+
+ public int Status
+ {
+ get { return this.resp.ResponseStatus.Value.IntValue; }
+ }
+
+ public object GetResponseObject()
+ {
+ ResponseBytes rb = this.resp.ResponseBytes;
+
+ if (rb == null)
+ return null;
+
+ if (rb.ResponseType.Equals(OcspObjectIdentifiers.PkixOcspBasic))
+ {
+ try
+ {
+ return new BasicOcspResp(
+ BasicOcspResponse.GetInstance(
+ Asn1Object.FromByteArray(rb.Response.GetOctets())));
+ }
+ catch (Exception e)
+ {
+ throw new OcspException("problem decoding object: " + e, e);
+ }
+ }
+
+ return rb.Response;
+ }
+
+ /**
+ * return the ASN.1 encoded representation of this object.
+ */
+ public byte[] GetEncoded()
+ {
+ return resp.GetEncoded();
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return true;
+
+ OcspResp other = obj as OcspResp;
+
+ if (other == null)
+ return false;
+
+ return resp.Equals(other.resp);
+ }
+
+ public override int GetHashCode()
+ {
+ return resp.GetHashCode();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPResp.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPResp.cs.meta
new file mode 100644
index 00000000..138e43dd
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPResp.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 19a37ebb18c778947808bd6a45e1a6ed
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPRespGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPRespGenerator.cs
new file mode 100644
index 00000000..5e5e2aa0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPRespGenerator.cs
@@ -0,0 +1,58 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Ocsp;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Ocsp
+{
+ /**
+ * base generator for an OCSP response - at the moment this only supports the
+ * generation of responses containing BasicOCSP responses.
+ */
+ public class OCSPRespGenerator
+ {
+ public const int Successful = 0; // Response has valid confirmations
+ public const int MalformedRequest = 1; // Illegal confirmation request
+ public const int InternalError = 2; // Internal error in issuer
+ public const int TryLater = 3; // Try again later
+ // (4) is not used
+ public const int SigRequired = 5; // Must sign the request
+ public const int Unauthorized = 6; // Request unauthorized
+
+ public OcspResp Generate(
+ int status,
+ object response)
+ {
+ if (response == null)
+ {
+ return new OcspResp(new OcspResponse(new OcspResponseStatus(status),null));
+ }
+ if (response is BasicOcspResp)
+ {
+ BasicOcspResp r = (BasicOcspResp)response;
+ Asn1OctetString octs;
+
+ try
+ {
+ octs = new DerOctetString(r.GetEncoded());
+ }
+ catch (Exception e)
+ {
+ throw new OcspException("can't encode object.", e);
+ }
+
+ ResponseBytes rb = new ResponseBytes(
+ OcspObjectIdentifiers.PkixOcspBasic, octs);
+
+ return new OcspResp(new OcspResponse(
+ new OcspResponseStatus(status), rb));
+ }
+
+ throw new OcspException("unknown response object");
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPRespGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPRespGenerator.cs.meta
new file mode 100644
index 00000000..2b463be8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPRespGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 304a4d91bffb95a489fc47ab2d2a3fb1
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPRespStatus.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPRespStatus.cs
new file mode 100644
index 00000000..c69dc60d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPRespStatus.cs
@@ -0,0 +1,26 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Ocsp
+{
+ [Obsolete("Use version with correct spelling 'OcspRespStatus'")]
+ public abstract class OcscpRespStatus : OcspRespStatus
+ {
+ }
+
+ public abstract class OcspRespStatus
+ {
+ /**
+ * note 4 is not used.
+ */
+ public const int Successful = 0; // --Response has valid confirmations
+ public const int MalformedRequest = 1; // --Illegal confirmation request
+ public const int InternalError = 2; // --Internal error in issuer
+ public const int TryLater = 3; // --Try again later
+ public const int SigRequired = 5; // --Must sign the request
+ public const int Unauthorized = 6; // --Request unauthorized
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPRespStatus.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPRespStatus.cs.meta
new file mode 100644
index 00000000..e5f33571
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPRespStatus.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 18a92b5f029fd6645be84f8f25950a0f
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPUtil.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPUtil.cs
new file mode 100644
index 00000000..381ea63e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPUtil.cs
@@ -0,0 +1,140 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Oiw;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.TeleTrust;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Ocsp
+{
+ class OcspUtilities
+ {
+ private static readonly IDictionary algorithms = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ private static readonly IDictionary oids = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ private static readonly ISet noParams = new HashSet();
+
+ static OcspUtilities()
+ {
+ algorithms.Add("MD2WITHRSAENCRYPTION", PkcsObjectIdentifiers.MD2WithRsaEncryption);
+ algorithms.Add("MD2WITHRSA", PkcsObjectIdentifiers.MD2WithRsaEncryption);
+ algorithms.Add("MD5WITHRSAENCRYPTION", PkcsObjectIdentifiers.MD5WithRsaEncryption);
+ algorithms.Add("MD5WITHRSA", PkcsObjectIdentifiers.MD5WithRsaEncryption);
+ algorithms.Add("SHA1WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha1WithRsaEncryption);
+ algorithms.Add("SHA1WITHRSA", PkcsObjectIdentifiers.Sha1WithRsaEncryption);
+ algorithms.Add("SHA224WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha224WithRsaEncryption);
+ algorithms.Add("SHA224WITHRSA", PkcsObjectIdentifiers.Sha224WithRsaEncryption);
+ algorithms.Add("SHA256WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha256WithRsaEncryption);
+ algorithms.Add("SHA256WITHRSA", PkcsObjectIdentifiers.Sha256WithRsaEncryption);
+ algorithms.Add("SHA384WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha384WithRsaEncryption);
+ algorithms.Add("SHA384WITHRSA", PkcsObjectIdentifiers.Sha384WithRsaEncryption);
+ algorithms.Add("SHA512WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512WithRsaEncryption);
+ algorithms.Add("SHA512WITHRSA", PkcsObjectIdentifiers.Sha512WithRsaEncryption);
+ algorithms.Add("RIPEMD160WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160);
+ algorithms.Add("RIPEMD160WITHRSA", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160);
+ algorithms.Add("RIPEMD128WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128);
+ algorithms.Add("RIPEMD128WITHRSA", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128);
+ algorithms.Add("RIPEMD256WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256);
+ algorithms.Add("RIPEMD256WITHRSA", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256);
+ algorithms.Add("SHA1WITHDSA", X9ObjectIdentifiers.IdDsaWithSha1);
+ algorithms.Add("DSAWITHSHA1", X9ObjectIdentifiers.IdDsaWithSha1);
+ algorithms.Add("SHA224WITHDSA", NistObjectIdentifiers.DsaWithSha224);
+ algorithms.Add("SHA256WITHDSA", NistObjectIdentifiers.DsaWithSha256);
+ algorithms.Add("SHA1WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha1);
+ algorithms.Add("ECDSAWITHSHA1", X9ObjectIdentifiers.ECDsaWithSha1);
+ algorithms.Add("SHA224WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha224);
+ algorithms.Add("SHA256WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha256);
+ algorithms.Add("SHA384WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha384);
+ algorithms.Add("SHA512WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha512);
+ algorithms.Add("GOST3411WITHGOST3410", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94);
+ algorithms.Add("GOST3411WITHGOST3410-94", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94);
+
+ oids.Add(PkcsObjectIdentifiers.MD2WithRsaEncryption, "MD2WITHRSA");
+ oids.Add(PkcsObjectIdentifiers.MD5WithRsaEncryption, "MD5WITHRSA");
+ oids.Add(PkcsObjectIdentifiers.Sha1WithRsaEncryption, "SHA1WITHRSA");
+ oids.Add(PkcsObjectIdentifiers.Sha224WithRsaEncryption, "SHA224WITHRSA");
+ oids.Add(PkcsObjectIdentifiers.Sha256WithRsaEncryption, "SHA256WITHRSA");
+ oids.Add(PkcsObjectIdentifiers.Sha384WithRsaEncryption, "SHA384WITHRSA");
+ oids.Add(PkcsObjectIdentifiers.Sha512WithRsaEncryption, "SHA512WITHRSA");
+ oids.Add(TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160, "RIPEMD160WITHRSA");
+ oids.Add(TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128, "RIPEMD128WITHRSA");
+ oids.Add(TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256, "RIPEMD256WITHRSA");
+ oids.Add(X9ObjectIdentifiers.IdDsaWithSha1, "SHA1WITHDSA");
+ oids.Add(NistObjectIdentifiers.DsaWithSha224, "SHA224WITHDSA");
+ oids.Add(NistObjectIdentifiers.DsaWithSha256, "SHA256WITHDSA");
+ oids.Add(X9ObjectIdentifiers.ECDsaWithSha1, "SHA1WITHECDSA");
+ oids.Add(X9ObjectIdentifiers.ECDsaWithSha224, "SHA224WITHECDSA");
+ oids.Add(X9ObjectIdentifiers.ECDsaWithSha256, "SHA256WITHECDSA");
+ oids.Add(X9ObjectIdentifiers.ECDsaWithSha384, "SHA384WITHECDSA");
+ oids.Add(X9ObjectIdentifiers.ECDsaWithSha512, "SHA512WITHECDSA");
+ oids.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94, "GOST3411WITHGOST3410");
+ oids.Add(OiwObjectIdentifiers.MD5WithRsa, "MD5WITHRSA");
+ oids.Add(OiwObjectIdentifiers.Sha1WithRsa, "SHA1WITHRSA");
+ oids.Add(OiwObjectIdentifiers.DsaWithSha1, "SHA1WITHDSA");
+
+ //
+ // According to RFC 3279, the ASN.1 encoding SHALL (id-dsa-with-sha1) or MUST (ecdsa-with-SHA*) omit the parameters field.
+ // The parameters field SHALL be NULL for RSA based signature algorithms.
+ //
+ noParams.Add(X9ObjectIdentifiers.ECDsaWithSha1);
+ noParams.Add(X9ObjectIdentifiers.ECDsaWithSha224);
+ noParams.Add(X9ObjectIdentifiers.ECDsaWithSha256);
+ noParams.Add(X9ObjectIdentifiers.ECDsaWithSha384);
+ noParams.Add(X9ObjectIdentifiers.ECDsaWithSha512);
+ noParams.Add(X9ObjectIdentifiers.IdDsaWithSha1);
+ noParams.Add(NistObjectIdentifiers.DsaWithSha224);
+ noParams.Add(NistObjectIdentifiers.DsaWithSha256);
+ }
+
+ internal static DerObjectIdentifier GetAlgorithmOid(
+ string algorithmName)
+ {
+ algorithmName = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithmName);
+
+ if (algorithms.Contains(algorithmName))
+ {
+ return (DerObjectIdentifier)algorithms[algorithmName];
+ }
+
+ return new DerObjectIdentifier(algorithmName);
+ }
+
+
+ internal static string GetAlgorithmName(
+ DerObjectIdentifier oid)
+ {
+ if (oids.Contains(oid))
+ {
+ return (string)oids[oid];
+ }
+
+ return oid.Id;
+ }
+
+ internal static AlgorithmIdentifier GetSigAlgID(
+ DerObjectIdentifier sigOid)
+ {
+ if (noParams.Contains(sigOid))
+ {
+ return new AlgorithmIdentifier(sigOid);
+ }
+
+ return new AlgorithmIdentifier(sigOid, DerNull.Instance);
+ }
+
+ internal static IEnumerable AlgNames
+ {
+ get { return new EnumerableProxy(algorithms.Keys); }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPUtil.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPUtil.cs.meta
new file mode 100644
index 00000000..ca9d1938
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/OCSPUtil.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: df2daa91f25e00345abf4eea8f4fcb89
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/Req.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/Req.cs
new file mode 100644
index 00000000..0879fc66
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/Req.cs
@@ -0,0 +1,42 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Ocsp;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Ocsp
+{
+ public class Req
+ : X509ExtensionBase
+ {
+ private Request req;
+
+ public Req(
+ Request req)
+ {
+ this.req = req;
+ }
+
+ public CertificateID GetCertID()
+ {
+ return new CertificateID(req.ReqCert);
+ }
+
+ public X509Extensions SingleRequestExtensions
+ {
+ get { return req.SingleRequestExtensions; }
+ }
+
+ protected override X509Extensions GetX509Extensions()
+ {
+ return SingleRequestExtensions;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/Req.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/Req.cs.meta
new file mode 100644
index 00000000..9e20ed44
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/Req.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0f5fbac749d65af408d1b69a21018425
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/RespData.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/RespData.cs
new file mode 100644
index 00000000..4e98bed0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/RespData.cs
@@ -0,0 +1,64 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Ocsp;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Ocsp
+{
+ public class RespData
+ : X509ExtensionBase
+ {
+ internal readonly ResponseData data;
+
+ public RespData(
+ ResponseData data)
+ {
+ this.data = data;
+ }
+
+ public int Version
+ {
+ get { return data.Version.Value.IntValue + 1; }
+ }
+
+ public RespID GetResponderId()
+ {
+ return new RespID(data.ResponderID);
+ }
+
+ public DateTime ProducedAt
+ {
+ get { return data.ProducedAt.ToDateTime(); }
+ }
+
+ public SingleResp[] GetResponses()
+ {
+ Asn1Sequence s = data.Responses;
+ SingleResp[] rs = new SingleResp[s.Count];
+
+ for (int i = 0; i != rs.Length; i++)
+ {
+ rs[i] = new SingleResp(SingleResponse.GetInstance(s[i]));
+ }
+
+ return rs;
+ }
+
+ public X509Extensions ResponseExtensions
+ {
+ get { return data.ResponseExtensions; }
+ }
+
+ protected override X509Extensions GetX509Extensions()
+ {
+ return ResponseExtensions;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/RespData.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/RespData.cs.meta
new file mode 100644
index 00000000..18455859
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/RespData.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 8ad49440b0bfa564096d37219b93ff9e
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/RespID.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/RespID.cs
new file mode 100644
index 00000000..8a33b812
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/RespID.cs
@@ -0,0 +1,76 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Ocsp;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Ocsp
+{
+ /**
+ * Carrier for a ResponderID.
+ */
+ public class RespID
+ {
+ internal readonly ResponderID id;
+
+ public RespID(
+ ResponderID id)
+ {
+ this.id = id;
+ }
+
+ public RespID(
+ X509Name name)
+ {
+ this.id = new ResponderID(name);
+ }
+
+ public RespID(
+ AsymmetricKeyParameter publicKey)
+ {
+ try
+ {
+ SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
+
+ byte[] keyHash = DigestUtilities.CalculateDigest("SHA1", info.PublicKeyData.GetBytes());
+
+ this.id = new ResponderID(new DerOctetString(keyHash));
+ }
+ catch (Exception e)
+ {
+ throw new OcspException("problem creating ID: " + e, e);
+ }
+ }
+
+ public ResponderID ToAsn1Object()
+ {
+ return id;
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return true;
+
+ RespID other = obj as RespID;
+
+ if (other == null)
+ return false;
+
+ return id.Equals(other.id);
+ }
+
+ public override int GetHashCode()
+ {
+ return id.GetHashCode();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/RespID.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/RespID.cs.meta
new file mode 100644
index 00000000..fb0943b2
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/RespID.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 13f651178027dd544b220f45d0a9235a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/RevokedStatus.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/RevokedStatus.cs
new file mode 100644
index 00000000..622f6b8d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/RevokedStatus.cs
@@ -0,0 +1,62 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Ocsp;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Ocsp
+{
+ /**
+ * wrapper for the RevokedInfo object
+ */
+ public class RevokedStatus
+ : CertificateStatus
+ {
+ internal readonly RevokedInfo info;
+
+ public RevokedStatus(
+ RevokedInfo info)
+ {
+ this.info = info;
+ }
+
+ public RevokedStatus(
+ DateTime revocationDate,
+ int reason)
+ {
+ this.info = new RevokedInfo(new DerGeneralizedTime(revocationDate), new CrlReason(reason));
+ }
+
+ public DateTime RevocationTime
+ {
+ get { return info.RevocationTime.ToDateTime(); }
+ }
+
+ public bool HasRevocationReason
+ {
+ get { return (info.RevocationReason != null); }
+ }
+
+ /**
+ * return the revocation reason. Note: this field is optional, test for it
+ * with hasRevocationReason() first.
+ * @exception InvalidOperationException if a reason is asked for and none is avaliable
+ */
+ public int RevocationReason
+ {
+ get
+ {
+ if (info.RevocationReason == null)
+ {
+ throw new InvalidOperationException("attempt to get a reason where none is available");
+ }
+
+ return info.RevocationReason.Value.IntValue;
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/RevokedStatus.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/RevokedStatus.cs.meta
new file mode 100644
index 00000000..d433c918
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/RevokedStatus.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 942d978af399500418044db4ab073932
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/SingleResp.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/SingleResp.cs
new file mode 100644
index 00000000..f52f226b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/SingleResp.cs
@@ -0,0 +1,85 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Ocsp;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Date;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Ocsp
+{
+ public class SingleResp
+ : X509ExtensionBase
+ {
+ internal readonly SingleResponse resp;
+
+ public SingleResp(
+ SingleResponse resp)
+ {
+ this.resp = resp;
+ }
+
+ public CertificateID GetCertID()
+ {
+ return new CertificateID(resp.CertId);
+ }
+
+ /**
+ * Return the status object for the response - null indicates good.
+ *
+ * @return the status object for the response, null if it is good.
+ */
+ public object GetCertStatus()
+ {
+ CertStatus s = resp.CertStatus;
+
+ if (s.TagNo == 0)
+ {
+ return null; // good
+ }
+
+ if (s.TagNo == 1)
+ {
+ return new RevokedStatus(RevokedInfo.GetInstance(s.Status));
+ }
+
+ return new UnknownStatus();
+ }
+
+ public DateTime ThisUpdate
+ {
+ get { return resp.ThisUpdate.ToDateTime(); }
+ }
+
+ /**
+ * return the NextUpdate value - note: this is an optional field so may
+ * be returned as null.
+ *
+ * @return nextUpdate, or null if not present.
+ */
+ public DateTimeObject NextUpdate
+ {
+ get
+ {
+ return resp.NextUpdate == null
+ ? null
+ : new DateTimeObject(resp.NextUpdate.ToDateTime());
+ }
+ }
+
+ public X509Extensions SingleExtensions
+ {
+ get { return resp.SingleExtensions; }
+ }
+
+ protected override X509Extensions GetX509Extensions()
+ {
+ return SingleExtensions;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/SingleResp.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/SingleResp.cs.meta
new file mode 100644
index 00000000..a97875b5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/SingleResp.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 91706998de8e56c4082a6a753a1aeeab
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/UnknownStatus.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/UnknownStatus.cs
new file mode 100644
index 00000000..e44c005e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/UnknownStatus.cs
@@ -0,0 +1,19 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Ocsp
+{
+ /**
+ * wrapper for the UnknownInfo object
+ */
+ public class UnknownStatus
+ : CertificateStatus
+ {
+ public UnknownStatus()
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/UnknownStatus.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/UnknownStatus.cs.meta
new file mode 100644
index 00000000..2aa8bc51
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/ocsp/UnknownStatus.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 3f278a1680d992a45a352e630ce3ad55
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl.meta
new file mode 100644
index 00000000..6c8c19cd
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl.meta
@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: d9b0429922c0a544c993b4880e0172a0
+folderAsset: yes
+timeCreated: 1547039641
+licenseType: Store
+DefaultImporter:
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/EncryptionException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/EncryptionException.cs
new file mode 100644
index 00000000..b1561256
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/EncryptionException.cs
@@ -0,0 +1,29 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security
+{
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class EncryptionException
+ : IOException
+ {
+ public EncryptionException(
+ string message)
+ : base(message)
+ {
+ }
+
+ public EncryptionException(
+ string message,
+ Exception exception)
+ : base(message, exception)
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/EncryptionException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/EncryptionException.cs.meta
new file mode 100644
index 00000000..07a737a6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/EncryptionException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 4a424bf92daf4a94da4bbe8b216162ed
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/IPasswordFinder.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/IPasswordFinder.cs
new file mode 100644
index 00000000..887edf43
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/IPasswordFinder.cs
@@ -0,0 +1,13 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.OpenSsl
+{
+ public interface IPasswordFinder
+ {
+ char[] GetPassword();
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/IPasswordFinder.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/IPasswordFinder.cs.meta
new file mode 100644
index 00000000..2e4d5323
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/IPasswordFinder.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: dd93d5ed8706db84582edeff6a96a3d6
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/MiscPemGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/MiscPemGenerator.cs
new file mode 100644
index 00000000..d04f2984
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/MiscPemGenerator.cs
@@ -0,0 +1,279 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO.Pem;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.OpenSsl
+{
+ /**
+ * PEM generator for the original set of PEM objects used in Open SSL.
+ */
+ public class MiscPemGenerator
+ : PemObjectGenerator
+ {
+ private object obj;
+ private string algorithm;
+ private char[] password;
+ private SecureRandom random;
+
+ public MiscPemGenerator(object obj)
+ {
+ this.obj = obj;
+ }
+
+ public MiscPemGenerator(
+ object obj,
+ string algorithm,
+ char[] password,
+ SecureRandom random)
+ {
+ this.obj = obj;
+ this.algorithm = algorithm;
+ this.password = password;
+ this.random = random;
+ }
+
+ private static PemObject CreatePemObject(object obj)
+ {
+ if (obj == null)
+ throw new ArgumentNullException("obj");
+
+ if (obj is AsymmetricCipherKeyPair)
+ {
+ return CreatePemObject(((AsymmetricCipherKeyPair)obj).Private);
+ }
+
+ string type;
+ byte[] encoding;
+
+ if (obj is PemObject)
+ return (PemObject)obj;
+
+ if (obj is PemObjectGenerator)
+ return ((PemObjectGenerator)obj).Generate();
+
+ if (obj is X509Certificate)
+ {
+ // TODO Should we prefer "X509 CERTIFICATE" here?
+ type = "CERTIFICATE";
+ try
+ {
+ encoding = ((X509Certificate)obj).GetEncoded();
+ }
+ catch (CertificateEncodingException e)
+ {
+ throw new IOException("Cannot Encode object: " + e.ToString());
+ }
+ }
+ else if (obj is X509Crl)
+ {
+ type = "X509 CRL";
+ try
+ {
+ encoding = ((X509Crl)obj).GetEncoded();
+ }
+ catch (CrlException e)
+ {
+ throw new IOException("Cannot Encode object: " + e.ToString());
+ }
+ }
+ else if (obj is AsymmetricKeyParameter)
+ {
+ AsymmetricKeyParameter akp = (AsymmetricKeyParameter) obj;
+ if (akp.IsPrivate)
+ {
+ string keyType;
+ encoding = EncodePrivateKey(akp, out keyType);
+
+ type = keyType + " PRIVATE KEY";
+ }
+ else
+ {
+ type = "PUBLIC KEY";
+
+ encoding = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(akp).GetDerEncoded();
+ }
+ }
+ else if (obj is IX509AttributeCertificate)
+ {
+ type = "ATTRIBUTE CERTIFICATE";
+ encoding = ((X509V2AttributeCertificate)obj).GetEncoded();
+ }
+ else if (obj is Pkcs10CertificationRequest)
+ {
+ type = "CERTIFICATE REQUEST";
+ encoding = ((Pkcs10CertificationRequest)obj).GetEncoded();
+ }
+ else if (obj is Asn1.Cms.ContentInfo)
+ {
+ type = "PKCS7";
+ encoding = ((Asn1.Cms.ContentInfo)obj).GetEncoded();
+ }
+ else
+ {
+ throw new PemGenerationException("Object type not supported: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj));
+ }
+
+ return new PemObject(type, encoding);
+ }
+
+// private string GetHexEncoded(byte[] bytes)
+// {
+// bytes = Hex.Encode(bytes);
+//
+// char[] chars = new char[bytes.Length];
+//
+// for (int i = 0; i != bytes.Length; i++)
+// {
+// chars[i] = (char)bytes[i];
+// }
+//
+// return new string(chars);
+// }
+
+ private static PemObject CreatePemObject(
+ object obj,
+ string algorithm,
+ char[] password,
+ SecureRandom random)
+ {
+ if (obj == null)
+ throw new ArgumentNullException("obj");
+ if (algorithm == null)
+ throw new ArgumentNullException("algorithm");
+ if (password == null)
+ throw new ArgumentNullException("password");
+ if (random == null)
+ throw new ArgumentNullException("random");
+
+ if (obj is AsymmetricCipherKeyPair)
+ {
+ return CreatePemObject(((AsymmetricCipherKeyPair)obj).Private, algorithm, password, random);
+ }
+
+ string type = null;
+ byte[] keyData = null;
+
+ if (obj is AsymmetricKeyParameter)
+ {
+ AsymmetricKeyParameter akp = (AsymmetricKeyParameter) obj;
+ if (akp.IsPrivate)
+ {
+ string keyType;
+ keyData = EncodePrivateKey(akp, out keyType);
+
+ type = keyType + " PRIVATE KEY";
+ }
+ }
+
+ if (type == null || keyData == null)
+ {
+ // TODO Support other types?
+ throw new PemGenerationException("Object type not supported: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj));
+ }
+
+
+ string dekAlgName = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm);
+
+ // Note: For backward compatibility
+ if (dekAlgName == "DESEDE")
+ {
+ dekAlgName = "DES-EDE3-CBC";
+ }
+
+ int ivLength = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(dekAlgName, "AES-") ? 16 : 8;
+
+ byte[] iv = new byte[ivLength];
+ random.NextBytes(iv);
+
+ byte[] encData = PemUtilities.Crypt(true, keyData, password, dekAlgName, iv);
+
+ IList headers = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(2);
+
+ headers.Add(new PemHeader("Proc-Type", "4,ENCRYPTED"));
+ headers.Add(new PemHeader("DEK-Info", dekAlgName + "," + Hex.ToHexString(iv)));
+
+ return new PemObject(type, headers, encData);
+ }
+
+ private static byte[] EncodePrivateKey(
+ AsymmetricKeyParameter akp,
+ out string keyType)
+ {
+ PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(akp);
+ AlgorithmIdentifier algID = info.PrivateKeyAlgorithm;
+ DerObjectIdentifier oid = algID.Algorithm;
+
+ if (oid.Equals(X9ObjectIdentifiers.IdDsa))
+ {
+ keyType = "DSA";
+
+ DsaParameter p = DsaParameter.GetInstance(algID.Parameters);
+
+ BigInteger x = ((DsaPrivateKeyParameters) akp).X;
+ BigInteger y = p.G.ModPow(x, p.P);
+
+ // TODO Create an ASN1 object somewhere for this?
+ return new DerSequence(
+ new DerInteger(0),
+ new DerInteger(p.P),
+ new DerInteger(p.Q),
+ new DerInteger(p.G),
+ new DerInteger(y),
+ new DerInteger(x)).GetEncoded();
+ }
+
+ if (oid.Equals(PkcsObjectIdentifiers.RsaEncryption))
+ {
+ keyType = "RSA";
+ }
+ else if (oid.Equals(CryptoProObjectIdentifiers.GostR3410x2001)
+ || oid.Equals(X9ObjectIdentifiers.IdECPublicKey))
+ {
+ keyType = "EC";
+ }
+ else
+ {
+ throw new ArgumentException("Cannot handle private key of type: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(akp), "akp");
+ }
+
+ return info.ParsePrivateKey().GetEncoded();
+ }
+
+ public PemObject Generate()
+ {
+ try
+ {
+ if (algorithm != null)
+ {
+ return CreatePemObject(obj, algorithm, password, random);
+ }
+
+ return CreatePemObject(obj);
+ }
+ catch (IOException e)
+ {
+ throw new PemGenerationException("encoding exception", e);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/MiscPemGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/MiscPemGenerator.cs.meta
new file mode 100644
index 00000000..2f44a9b7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/MiscPemGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c0d8a624220f0fc41b80f7f2549e984a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PEMException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PEMException.cs
new file mode 100644
index 00000000..fec661b6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PEMException.cs
@@ -0,0 +1,29 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.OpenSsl
+{
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class PemException
+ : IOException
+ {
+ public PemException(
+ string message)
+ : base(message)
+ {
+ }
+
+ public PemException(
+ string message,
+ Exception exception)
+ : base(message, exception)
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PEMException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PEMException.cs.meta
new file mode 100644
index 00000000..d2f949a9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PEMException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 02930c4db3958684397dcfe7708b464b
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PEMReader.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PEMReader.cs
new file mode 100644
index 00000000..0debee66
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PEMReader.cs
@@ -0,0 +1,405 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.Diagnostics;
+using System.IO;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Sec;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.TeleTrust;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.EC;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO.Pem;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.OpenSsl
+{
+ /**
+ * Class for reading OpenSSL PEM encoded streams containing
+ * X509 certificates, PKCS8 encoded keys and PKCS7 objects.
+ *
+ * In the case of PKCS7 objects the reader will return a CMS ContentInfo object. Keys and
+ * Certificates will be returned using the appropriate java.security type.
+ */
+ public class PemReader
+ : BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO.Pem.PemReader
+ {
+// private static readonly IDictionary parsers = new Hashtable();
+
+ static PemReader()
+ {
+// parsers.Add("CERTIFICATE REQUEST", new PKCS10CertificationRequestParser());
+// parsers.Add("NEW CERTIFICATE REQUEST", new PKCS10CertificationRequestParser());
+// parsers.Add("CERTIFICATE", new X509CertificateParser(provider));
+// parsers.Add("X509 CERTIFICATE", new X509CertificateParser(provider));
+// parsers.Add("X509 CRL", new X509CRLParser(provider));
+// parsers.Add("PKCS7", new PKCS7Parser());
+// parsers.Add("ATTRIBUTE CERTIFICATE", new X509AttributeCertificateParser());
+// parsers.Add("EC PARAMETERS", new ECNamedCurveSpecParser());
+// parsers.Add("PUBLIC KEY", new PublicKeyParser(provider));
+// parsers.Add("RSA PUBLIC KEY", new RSAPublicKeyParser(provider));
+// parsers.Add("RSA PRIVATE KEY", new RSAKeyPairParser(provider));
+// parsers.Add("DSA PRIVATE KEY", new DSAKeyPairParser(provider));
+// parsers.Add("EC PRIVATE KEY", new ECDSAKeyPairParser(provider));
+// parsers.Add("ENCRYPTED PRIVATE KEY", new EncryptedPrivateKeyParser(provider));
+// parsers.Add("PRIVATE KEY", new PrivateKeyParser(provider));
+ }
+
+ private readonly IPasswordFinder pFinder;
+
+ /**
+ * Create a new PemReader
+ *
+ * @param reader the Reader
+ */
+ public PemReader(
+ TextReader reader)
+ : this(reader, null)
+ {
+ }
+
+ /**
+ * Create a new PemReader with a password finder
+ *
+ * @param reader the Reader
+ * @param pFinder the password finder
+ */
+ public PemReader(
+ TextReader reader,
+ IPasswordFinder pFinder)
+ : base(reader)
+ {
+ this.pFinder = pFinder;
+ }
+
+ public object ReadObject()
+ {
+ PemObject obj = ReadPemObject();
+
+ if (obj == null)
+ return null;
+
+ // TODO Follow Java build and map to parser objects?
+// if (parsers.Contains(obj.Type))
+// return ((PemObjectParser)parsers[obj.Type]).ParseObject(obj);
+
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(obj.Type, "PRIVATE KEY"))
+ return ReadPrivateKey(obj);
+
+ switch (obj.Type)
+ {
+ case "PUBLIC KEY":
+ return ReadPublicKey(obj);
+ case "RSA PUBLIC KEY":
+ return ReadRsaPublicKey(obj);
+ case "CERTIFICATE REQUEST":
+ case "NEW CERTIFICATE REQUEST":
+ return ReadCertificateRequest(obj);
+ case "CERTIFICATE":
+ case "X509 CERTIFICATE":
+ return ReadCertificate(obj);
+ case "PKCS7":
+ case "CMS":
+ return ReadPkcs7(obj);
+ case "X509 CRL":
+ return ReadCrl(obj);
+ case "ATTRIBUTE CERTIFICATE":
+ return ReadAttributeCertificate(obj);
+ // TODO Add back in when tests done, and return type issue resolved
+ //case "EC PARAMETERS":
+ // return ReadECParameters(obj);
+ default:
+ throw new IOException("unrecognised object: " + obj.Type);
+ }
+ }
+
+ private AsymmetricKeyParameter ReadRsaPublicKey(PemObject pemObject)
+ {
+ RsaPublicKeyStructure rsaPubStructure = RsaPublicKeyStructure.GetInstance(
+ Asn1Object.FromByteArray(pemObject.Content));
+
+ return new RsaKeyParameters(
+ false, // not private
+ rsaPubStructure.Modulus,
+ rsaPubStructure.PublicExponent);
+ }
+
+ private AsymmetricKeyParameter ReadPublicKey(PemObject pemObject)
+ {
+ return PublicKeyFactory.CreateKey(pemObject.Content);
+ }
+
+ /**
+ * Reads in a X509Certificate.
+ *
+ * @return the X509Certificate
+ * @throws IOException if an I/O error occured
+ */
+ private X509Certificate ReadCertificate(PemObject pemObject)
+ {
+ try
+ {
+ return new X509CertificateParser().ReadCertificate(pemObject.Content);
+ }
+ catch (Exception e)
+ {
+ throw new PemException("problem parsing cert: " + e.ToString());
+ }
+ }
+
+ /**
+ * Reads in a X509CRL.
+ *
+ * @return the X509Certificate
+ * @throws IOException if an I/O error occured
+ */
+ private X509Crl ReadCrl(PemObject pemObject)
+ {
+ try
+ {
+ return new X509CrlParser().ReadCrl(pemObject.Content);
+ }
+ catch (Exception e)
+ {
+ throw new PemException("problem parsing cert: " + e.ToString());
+ }
+ }
+
+ /**
+ * Reads in a PKCS10 certification request.
+ *
+ * @return the certificate request.
+ * @throws IOException if an I/O error occured
+ */
+ private Pkcs10CertificationRequest ReadCertificateRequest(PemObject pemObject)
+ {
+ try
+ {
+ return new Pkcs10CertificationRequest(pemObject.Content);
+ }
+ catch (Exception e)
+ {
+ throw new PemException("problem parsing cert: " + e.ToString());
+ }
+ }
+
+ /**
+ * Reads in a X509 Attribute Certificate.
+ *
+ * @return the X509 Attribute Certificate
+ * @throws IOException if an I/O error occured
+ */
+ private IX509AttributeCertificate ReadAttributeCertificate(PemObject pemObject)
+ {
+ return new X509V2AttributeCertificate(pemObject.Content);
+ }
+
+ /**
+ * Reads in a PKCS7 object. This returns a ContentInfo object suitable for use with the CMS
+ * API.
+ *
+ * @return the X509Certificate
+ * @throws IOException if an I/O error occured
+ */
+ // TODO Consider returning Asn1.Pkcs.ContentInfo
+ private Asn1.Cms.ContentInfo ReadPkcs7(PemObject pemObject)
+ {
+ try
+ {
+ return Asn1.Cms.ContentInfo.GetInstance(
+ Asn1Object.FromByteArray(pemObject.Content));
+ }
+ catch (Exception e)
+ {
+ throw new PemException("problem parsing PKCS7 object: " + e.ToString());
+ }
+ }
+
+ /**
+ * Read a Key Pair
+ */
+ private object ReadPrivateKey(PemObject pemObject)
+ {
+ //
+ // extract the key
+ //
+ Debug.Assert(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(pemObject.Type, "PRIVATE KEY"));
+
+ string type = pemObject.Type.Substring(0, pemObject.Type.Length - "PRIVATE KEY".Length).Trim();
+ byte[] keyBytes = pemObject.Content;
+
+ IDictionary fields = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ foreach (PemHeader header in pemObject.Headers)
+ {
+ fields[header.Name] = header.Value;
+ }
+
+ string procType = (string) fields["Proc-Type"];
+
+ if (procType == "4,ENCRYPTED")
+ {
+ if (pFinder == null)
+ throw new PasswordException("No password finder specified, but a password is required");
+
+ char[] password = pFinder.GetPassword();
+
+ if (password == null)
+ throw new PasswordException("Password is null, but a password is required");
+
+ string dekInfo = (string) fields["DEK-Info"];
+ string[] tknz = dekInfo.Split(',');
+
+ string dekAlgName = tknz[0].Trim();
+ byte[] iv = Hex.Decode(tknz[1].Trim());
+
+ keyBytes = PemUtilities.Crypt(false, keyBytes, password, dekAlgName, iv);
+ }
+
+ try
+ {
+ AsymmetricKeyParameter pubSpec, privSpec;
+ Asn1Sequence seq = Asn1Sequence.GetInstance(keyBytes);
+
+ switch (type)
+ {
+ case "RSA":
+ {
+ if (seq.Count != 9)
+ throw new PemException("malformed sequence in RSA private key");
+
+ RsaPrivateKeyStructure rsa = RsaPrivateKeyStructure.GetInstance(seq);
+
+ pubSpec = new RsaKeyParameters(false, rsa.Modulus, rsa.PublicExponent);
+ privSpec = new RsaPrivateCrtKeyParameters(
+ rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent,
+ rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2,
+ rsa.Coefficient);
+
+ break;
+ }
+
+ case "DSA":
+ {
+ if (seq.Count != 6)
+ throw new PemException("malformed sequence in DSA private key");
+
+ // TODO Create an ASN1 object somewhere for this?
+ //DerInteger v = (DerInteger)seq[0];
+ DerInteger p = (DerInteger)seq[1];
+ DerInteger q = (DerInteger)seq[2];
+ DerInteger g = (DerInteger)seq[3];
+ DerInteger y = (DerInteger)seq[4];
+ DerInteger x = (DerInteger)seq[5];
+
+ DsaParameters parameters = new DsaParameters(p.Value, q.Value, g.Value);
+
+ privSpec = new DsaPrivateKeyParameters(x.Value, parameters);
+ pubSpec = new DsaPublicKeyParameters(y.Value, parameters);
+
+ break;
+ }
+
+ case "EC":
+ {
+ ECPrivateKeyStructure pKey = ECPrivateKeyStructure.GetInstance(seq);
+ AlgorithmIdentifier algId = new AlgorithmIdentifier(
+ X9ObjectIdentifiers.IdECPublicKey, pKey.GetParameters());
+
+ PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey.ToAsn1Object());
+
+ // TODO Are the keys returned here ECDSA, as Java version forces?
+ privSpec = PrivateKeyFactory.CreateKey(privInfo);
+
+ DerBitString pubKey = pKey.GetPublicKey();
+ if (pubKey != null)
+ {
+ SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo(algId, pubKey.GetBytes());
+
+ // TODO Are the keys returned here ECDSA, as Java version forces?
+ pubSpec = PublicKeyFactory.CreateKey(pubInfo);
+ }
+ else
+ {
+ pubSpec = ECKeyPairGenerator.GetCorrespondingPublicKey(
+ (ECPrivateKeyParameters)privSpec);
+ }
+
+ break;
+ }
+
+ case "ENCRYPTED":
+ {
+ char[] password = pFinder.GetPassword();
+
+ if (password == null)
+ throw new PasswordException("Password is null, but a password is required");
+
+ return PrivateKeyFactory.DecryptKey(password, EncryptedPrivateKeyInfo.GetInstance(seq));
+ }
+
+ case "":
+ {
+ return PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(seq));
+ }
+
+ default:
+ throw new ArgumentException("Unknown key type: " + type, "type");
+ }
+
+ return new AsymmetricCipherKeyPair(pubSpec, privSpec);
+ }
+ catch (IOException e)
+ {
+ throw e;
+ }
+ catch (Exception e)
+ {
+ throw new PemException(
+ "problem creating " + type + " private key: " + e.ToString());
+ }
+ }
+
+ // TODO Add an equivalent class for ECNamedCurveParameterSpec?
+ //private ECNamedCurveParameterSpec ReadECParameters(
+// private X9ECParameters ReadECParameters(PemObject pemObject)
+// {
+// DerObjectIdentifier oid = (DerObjectIdentifier)Asn1Object.FromByteArray(pemObject.Content);
+//
+// //return ECNamedCurveTable.getParameterSpec(oid.Id);
+// return GetCurveParameters(oid.Id);
+// }
+
+ //private static ECDomainParameters GetCurveParameters(
+ private static X9ECParameters GetCurveParameters(
+ string name)
+ {
+ // TODO ECGost3410NamedCurves support (returns ECDomainParameters though)
+
+ X9ECParameters ecP = CustomNamedCurves.GetByName(name);
+ if (ecP == null)
+ {
+ ecP = ECNamedCurveTable.GetByName(name);
+ }
+
+ if (ecP == null)
+ throw new Exception("unknown curve name: " + name);
+
+ //return new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed());
+ return ecP;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PEMReader.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PEMReader.cs.meta
new file mode 100644
index 00000000..a7724a9b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PEMReader.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ea2749aedc54590409ca3ca57e7e3a00
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PEMUtilities.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PEMUtilities.cs
new file mode 100644
index 00000000..9e1e4d2b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PEMUtilities.cs
@@ -0,0 +1,162 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.OpenSsl
+{
+ internal sealed class PemUtilities
+ {
+ private enum PemBaseAlg { AES_128, AES_192, AES_256, BF, DES, DES_EDE, DES_EDE3, RC2, RC2_40, RC2_64 };
+ private enum PemMode { CBC, CFB, ECB, OFB };
+
+ static PemUtilities()
+ {
+ // Signal to obfuscation tools not to change enum constants
+ ((PemBaseAlg)Enums.GetArbitraryValue(typeof(PemBaseAlg))).ToString();
+ ((PemMode)Enums.GetArbitraryValue(typeof(PemMode))).ToString();
+ }
+
+ private static void ParseDekAlgName(
+ string dekAlgName,
+ out PemBaseAlg baseAlg,
+ out PemMode mode)
+ {
+ try
+ {
+ mode = PemMode.ECB;
+
+ if (dekAlgName == "DES-EDE" || dekAlgName == "DES-EDE3")
+ {
+ baseAlg = (PemBaseAlg)Enums.GetEnumValue(typeof(PemBaseAlg), dekAlgName);
+ return;
+ }
+
+ int pos = dekAlgName.LastIndexOf('-');
+ if (pos >= 0)
+ {
+ baseAlg = (PemBaseAlg)Enums.GetEnumValue(typeof(PemBaseAlg), dekAlgName.Substring(0, pos));
+ mode = (PemMode)Enums.GetEnumValue(typeof(PemMode), dekAlgName.Substring(pos + 1));
+ return;
+ }
+ }
+ catch (ArgumentException)
+ {
+ }
+
+ throw new EncryptionException("Unknown DEK algorithm: " + dekAlgName);
+ }
+
+ internal static byte[] Crypt(
+ bool encrypt,
+ byte[] bytes,
+ char[] password,
+ string dekAlgName,
+ byte[] iv)
+ {
+ PemBaseAlg baseAlg;
+ PemMode mode;
+ ParseDekAlgName(dekAlgName, out baseAlg, out mode);
+
+ string padding;
+ switch (mode)
+ {
+ case PemMode.CBC:
+ case PemMode.ECB:
+ padding = "PKCS5Padding";
+ break;
+ case PemMode.CFB:
+ case PemMode.OFB:
+ padding = "NoPadding";
+ break;
+ default:
+ throw new EncryptionException("Unknown DEK algorithm: " + dekAlgName);
+ }
+
+ string algorithm;
+
+ byte[] salt = iv;
+ switch (baseAlg)
+ {
+ case PemBaseAlg.AES_128:
+ case PemBaseAlg.AES_192:
+ case PemBaseAlg.AES_256:
+ algorithm = "AES";
+ if (salt.Length > 8)
+ {
+ salt = new byte[8];
+ Array.Copy(iv, 0, salt, 0, salt.Length);
+ }
+ break;
+ case PemBaseAlg.BF:
+ algorithm = "BLOWFISH";
+ break;
+ case PemBaseAlg.DES:
+ algorithm = "DES";
+ break;
+ case PemBaseAlg.DES_EDE:
+ case PemBaseAlg.DES_EDE3:
+ algorithm = "DESede";
+ break;
+ case PemBaseAlg.RC2:
+ case PemBaseAlg.RC2_40:
+ case PemBaseAlg.RC2_64:
+ algorithm = "RC2";
+ break;
+ default:
+ throw new EncryptionException("Unknown DEK algorithm: " + dekAlgName);
+ }
+
+ string cipherName = algorithm + "/" + mode + "/" + padding;
+ IBufferedCipher cipher = CipherUtilities.GetCipher(cipherName);
+
+ ICipherParameters cParams = GetCipherParameters(password, baseAlg, salt);
+
+ if (mode != PemMode.ECB)
+ {
+ cParams = new ParametersWithIV(cParams, iv);
+ }
+
+ cipher.Init(encrypt, cParams);
+
+ return cipher.DoFinal(bytes);
+ }
+
+ private static ICipherParameters GetCipherParameters(
+ char[] password,
+ PemBaseAlg baseAlg,
+ byte[] salt)
+ {
+ string algorithm;
+ int keyBits;
+ switch (baseAlg)
+ {
+ case PemBaseAlg.AES_128: keyBits = 128; algorithm = "AES128"; break;
+ case PemBaseAlg.AES_192: keyBits = 192; algorithm = "AES192"; break;
+ case PemBaseAlg.AES_256: keyBits = 256; algorithm = "AES256"; break;
+ case PemBaseAlg.BF: keyBits = 128; algorithm = "BLOWFISH"; break;
+ case PemBaseAlg.DES: keyBits = 64; algorithm = "DES"; break;
+ case PemBaseAlg.DES_EDE: keyBits = 128; algorithm = "DESEDE"; break;
+ case PemBaseAlg.DES_EDE3: keyBits = 192; algorithm = "DESEDE3"; break;
+ case PemBaseAlg.RC2: keyBits = 128; algorithm = "RC2"; break;
+ case PemBaseAlg.RC2_40: keyBits = 40; algorithm = "RC2"; break;
+ case PemBaseAlg.RC2_64: keyBits = 64; algorithm = "RC2"; break;
+ default:
+ return null;
+ }
+
+ OpenSslPbeParametersGenerator pGen = new OpenSslPbeParametersGenerator();
+
+ pGen.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password), salt);
+
+ return pGen.GenerateDerivedParameters(algorithm, keyBits);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PEMUtilities.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PEMUtilities.cs.meta
new file mode 100644
index 00000000..03b1b1b2
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PEMUtilities.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: bb8051867251512499844467793cdf9f
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PEMWriter.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PEMWriter.cs
new file mode 100644
index 00000000..f0563e54
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PEMWriter.cs
@@ -0,0 +1,65 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Diagnostics;
+using System.Globalization;
+using System.IO;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO.Pem;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.OpenSsl
+{
+ /// General purpose writer for OpenSSL PEM objects.
+ public class PemWriter
+ : BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO.Pem.PemWriter
+ {
+ /// The TextWriter object to write the output to.
+ public PemWriter(
+ TextWriter writer)
+ : base(writer)
+ {
+ }
+
+ public void WriteObject(
+ object obj)
+ {
+ try
+ {
+ base.WriteObject(new MiscPemGenerator(obj));
+ }
+ catch (PemGenerationException e)
+ {
+ if (e.InnerException is IOException)
+ throw (IOException)e.InnerException;
+
+ throw e;
+ }
+ }
+
+ public void WriteObject(
+ object obj,
+ string algorithm,
+ char[] password,
+ SecureRandom random)
+ {
+ base.WriteObject(new MiscPemGenerator(obj, algorithm, password, random));
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PEMWriter.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PEMWriter.cs.meta
new file mode 100644
index 00000000..6e43b931
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PEMWriter.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 23f95c4b40043494bb615ca11764ba46
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PasswordException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PasswordException.cs
new file mode 100644
index 00000000..b1ee0283
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PasswordException.cs
@@ -0,0 +1,29 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security
+{
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class PasswordException
+ : IOException
+ {
+ public PasswordException(
+ string message)
+ : base(message)
+ {
+ }
+
+ public PasswordException(
+ string message,
+ Exception exception)
+ : base(message, exception)
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PasswordException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PasswordException.cs.meta
new file mode 100644
index 00000000..6835ce53
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/PasswordException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 1a0af6d81e309f746935cdd3c3287be7
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/Pkcs8Generator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/Pkcs8Generator.cs
new file mode 100644
index 00000000..0d67b853
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/Pkcs8Generator.cs
@@ -0,0 +1,115 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO.Pem;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.OpenSsl
+{
+ public class Pkcs8Generator
+ : PemObjectGenerator
+ {
+ // FIXME See PbeUtilities static constructor
+// public static readonly string Aes128Cbc = NistObjectIdentifiers.IdAes128Cbc.Id;
+// public static readonly string Aes192Cbc = NistObjectIdentifiers.IdAes192Cbc.Id;
+// public static readonly string Aes256Cbc = NistObjectIdentifiers.IdAes256Cbc.Id;
+//
+// public static readonly string Des3Cbc = PkcsObjectIdentifiers.DesEde3Cbc.Id;
+
+ public static readonly string PbeSha1_RC4_128 = PkcsObjectIdentifiers.PbeWithShaAnd128BitRC4.Id;
+ public static readonly string PbeSha1_RC4_40 = PkcsObjectIdentifiers.PbeWithShaAnd40BitRC4.Id;
+ public static readonly string PbeSha1_3DES = PkcsObjectIdentifiers.PbeWithShaAnd3KeyTripleDesCbc.Id;
+ public static readonly string PbeSha1_2DES = PkcsObjectIdentifiers.PbeWithShaAnd2KeyTripleDesCbc.Id;
+ public static readonly string PbeSha1_RC2_128 = PkcsObjectIdentifiers.PbeWithShaAnd128BitRC2Cbc.Id;
+ public static readonly string PbeSha1_RC2_40 = PkcsObjectIdentifiers.PbewithShaAnd40BitRC2Cbc.Id;
+
+ private char[] password;
+ private string algorithm;
+ private int iterationCount;
+ private AsymmetricKeyParameter privKey;
+ private SecureRandom random;
+
+ /**
+ * Constructor for an unencrypted private key PEM object.
+ *
+ * @param key private key to be encoded.
+ */
+ public Pkcs8Generator(AsymmetricKeyParameter privKey)
+ {
+ this.privKey = privKey;
+ }
+
+ /**
+ * Constructor for an encrypted private key PEM object.
+ *
+ * @param key private key to be encoded
+ * @param algorithm encryption algorithm to use
+ * @param provider provider to use
+ * @throws NoSuchAlgorithmException if algorithm/mode cannot be found
+ */
+ public Pkcs8Generator(AsymmetricKeyParameter privKey, string algorithm)
+ {
+ // TODO Check privKey.IsPrivate
+ this.privKey = privKey;
+ this.algorithm = algorithm;
+ this.iterationCount = 2048;
+ }
+
+ public SecureRandom SecureRandom
+ {
+ set { this.random = value; }
+ }
+
+ public char[] Password
+ {
+ set { this.password = value; }
+ }
+
+ public int IterationCount
+ {
+ set { this.iterationCount = value; }
+ }
+
+ public PemObject Generate()
+ {
+ if (algorithm == null)
+ {
+ PrivateKeyInfo pki = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privKey);
+
+ return new PemObject("PRIVATE KEY", pki.GetEncoded());
+ }
+
+ // TODO Theoretically, the amount of salt needed depends on the algorithm
+ byte[] salt = new byte[20];
+ if (random == null)
+ {
+ random = new SecureRandom();
+ }
+ random.NextBytes(salt);
+
+ try
+ {
+ EncryptedPrivateKeyInfo epki = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
+ algorithm, password, salt, iterationCount, privKey);
+
+ return new PemObject("ENCRYPTED PRIVATE KEY", epki.GetEncoded());
+ }
+ catch (Exception e)
+ {
+ throw new PemGenerationException("Couldn't encrypt private key", e);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/Pkcs8Generator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/Pkcs8Generator.cs.meta
new file mode 100644
index 00000000..01c253d3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/openssl/Pkcs8Generator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 8fd3426c3338f804185fac837f54726a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs.meta
new file mode 100644
index 00000000..e9cbd2a8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs.meta
@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: c5b7d40a38054774bb2cee59156dd3d3
+folderAsset: yes
+timeCreated: 1547039641
+licenseType: Store
+DefaultImporter:
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/AsymmetricKeyEntry.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/AsymmetricKeyEntry.cs
new file mode 100644
index 00000000..7dba455d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/AsymmetricKeyEntry.cs
@@ -0,0 +1,64 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs
+{
+ public class AsymmetricKeyEntry
+ : Pkcs12Entry
+ {
+ private readonly AsymmetricKeyParameter key;
+
+ public AsymmetricKeyEntry(
+ AsymmetricKeyParameter key)
+ : base(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable())
+ {
+ this.key = key;
+ }
+
+#if !(SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Obsolete]
+ public AsymmetricKeyEntry(
+ AsymmetricKeyParameter key,
+ Hashtable attributes)
+ : base(attributes)
+ {
+ this.key = key;
+ }
+#endif
+
+ public AsymmetricKeyEntry(
+ AsymmetricKeyParameter key,
+ IDictionary attributes)
+ : base(attributes)
+ {
+ this.key = key;
+ }
+
+ public AsymmetricKeyParameter Key
+ {
+ get { return this.key; }
+ }
+
+ public override bool Equals(object obj)
+ {
+ AsymmetricKeyEntry other = obj as AsymmetricKeyEntry;
+
+ if (other == null)
+ return false;
+
+ return key.Equals(other.key);
+ }
+
+ public override int GetHashCode()
+ {
+ return ~key.GetHashCode();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/AsymmetricKeyEntry.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/AsymmetricKeyEntry.cs.meta
new file mode 100644
index 00000000..8c2605ea
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/AsymmetricKeyEntry.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: e0fc1e2e40052dc44899abad8920a4e5
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/EncryptedPrivateKeyInfoFactory.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/EncryptedPrivateKeyInfoFactory.cs
new file mode 100644
index 00000000..7daafcb6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/EncryptedPrivateKeyInfoFactory.cs
@@ -0,0 +1,68 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs
+{
+ public sealed class EncryptedPrivateKeyInfoFactory
+ {
+ private EncryptedPrivateKeyInfoFactory()
+ {
+ }
+
+ public static EncryptedPrivateKeyInfo CreateEncryptedPrivateKeyInfo(
+ DerObjectIdentifier algorithm,
+ char[] passPhrase,
+ byte[] salt,
+ int iterationCount,
+ AsymmetricKeyParameter key)
+ {
+ return CreateEncryptedPrivateKeyInfo(
+ algorithm.Id, passPhrase, salt, iterationCount,
+ PrivateKeyInfoFactory.CreatePrivateKeyInfo(key));
+ }
+
+ public static EncryptedPrivateKeyInfo CreateEncryptedPrivateKeyInfo(
+ string algorithm,
+ char[] passPhrase,
+ byte[] salt,
+ int iterationCount,
+ AsymmetricKeyParameter key)
+ {
+ return CreateEncryptedPrivateKeyInfo(
+ algorithm, passPhrase, salt, iterationCount,
+ PrivateKeyInfoFactory.CreatePrivateKeyInfo(key));
+ }
+
+ public static EncryptedPrivateKeyInfo CreateEncryptedPrivateKeyInfo(
+ string algorithm,
+ char[] passPhrase,
+ byte[] salt,
+ int iterationCount,
+ PrivateKeyInfo keyInfo)
+ {
+ IBufferedCipher cipher = PbeUtilities.CreateEngine(algorithm) as IBufferedCipher;
+ if (cipher == null)
+ throw new Exception("Unknown encryption algorithm: " + algorithm);
+
+ Asn1Encodable pbeParameters = PbeUtilities.GenerateAlgorithmParameters(
+ algorithm, salt, iterationCount);
+ ICipherParameters cipherParameters = PbeUtilities.GenerateCipherParameters(
+ algorithm, passPhrase, pbeParameters);
+ cipher.Init(true, cipherParameters);
+ byte[] encoding = cipher.DoFinal(keyInfo.GetEncoded());
+
+ DerObjectIdentifier oid = PbeUtilities.GetObjectIdentifier(algorithm);
+ AlgorithmIdentifier algID = new AlgorithmIdentifier(oid, pbeParameters);
+ return new EncryptedPrivateKeyInfo(algID, encoding);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/EncryptedPrivateKeyInfoFactory.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/EncryptedPrivateKeyInfoFactory.cs.meta
new file mode 100644
index 00000000..fe457e8c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/EncryptedPrivateKeyInfoFactory.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0ff4b19a3a083b346a18148d9cd0ba8d
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/PKCS12StoreBuilder.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/PKCS12StoreBuilder.cs
new file mode 100644
index 00000000..ac53dcd9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/PKCS12StoreBuilder.cs
@@ -0,0 +1,45 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs
+{
+ public class Pkcs12StoreBuilder
+ {
+ private DerObjectIdentifier keyAlgorithm = PkcsObjectIdentifiers.PbeWithShaAnd3KeyTripleDesCbc;
+ private DerObjectIdentifier certAlgorithm = PkcsObjectIdentifiers.PbewithShaAnd40BitRC2Cbc;
+ private bool useDerEncoding = false;
+
+ public Pkcs12StoreBuilder()
+ {
+ }
+
+ public Pkcs12Store Build()
+ {
+ return new Pkcs12Store(keyAlgorithm, certAlgorithm, useDerEncoding);
+ }
+
+ public Pkcs12StoreBuilder SetCertAlgorithm(DerObjectIdentifier certAlgorithm)
+ {
+ this.certAlgorithm = certAlgorithm;
+ return this;
+ }
+
+ public Pkcs12StoreBuilder SetKeyAlgorithm(DerObjectIdentifier keyAlgorithm)
+ {
+ this.keyAlgorithm = keyAlgorithm;
+ return this;
+ }
+
+ public Pkcs12StoreBuilder SetUseDerEncoding(bool useDerEncoding)
+ {
+ this.useDerEncoding = useDerEncoding;
+ return this;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/PKCS12StoreBuilder.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/PKCS12StoreBuilder.cs.meta
new file mode 100644
index 00000000..d43a66c2
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/PKCS12StoreBuilder.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 43aa4e117903bc6489e2b003abb2af10
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs10CertificationRequest.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs10CertificationRequest.cs
new file mode 100644
index 00000000..fcb20bcd
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs10CertificationRequest.cs
@@ -0,0 +1,471 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Oiw;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.TeleTrust;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Operators;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs
+{
+ ///
+ /// A class for verifying and creating Pkcs10 Certification requests.
+ ///
+ ///
+ /// CertificationRequest ::= Sequence {
+ /// certificationRequestInfo CertificationRequestInfo,
+ /// signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }},
+ /// signature BIT STRING
+ /// }
+ ///
+ /// CertificationRequestInfo ::= Sequence {
+ /// version Integer { v1(0) } (v1,...),
+ /// subject Name,
+ /// subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }},
+ /// attributes [0] Attributes{{ CRIAttributes }}
+ /// }
+ ///
+ /// Attributes { ATTRIBUTE:IOSet } ::= Set OF Attr{{ IOSet }}
+ ///
+ /// Attr { ATTRIBUTE:IOSet } ::= Sequence {
+ /// type ATTRIBUTE.&id({IOSet}),
+ /// values Set SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{\@type})
+ /// }
+ ///
+ /// see
+ public class Pkcs10CertificationRequest
+ : CertificationRequest
+ {
+ protected static readonly IDictionary algorithms = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ protected static readonly IDictionary exParams = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ protected static readonly IDictionary keyAlgorithms = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ protected static readonly IDictionary oids = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ protected static readonly ISet noParams = new HashSet();
+
+ static Pkcs10CertificationRequest()
+ {
+ algorithms.Add("MD2WITHRSAENCRYPTION", PkcsObjectIdentifiers.MD2WithRsaEncryption);
+ algorithms.Add("MD2WITHRSA", PkcsObjectIdentifiers.MD2WithRsaEncryption);
+ algorithms.Add("MD5WITHRSAENCRYPTION", PkcsObjectIdentifiers.MD5WithRsaEncryption);
+ algorithms.Add("MD5WITHRSA", PkcsObjectIdentifiers.MD5WithRsaEncryption);
+ algorithms.Add("RSAWITHMD5", PkcsObjectIdentifiers.MD5WithRsaEncryption);
+ algorithms.Add("SHA1WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha1WithRsaEncryption);
+ algorithms.Add("SHA1WITHRSA", PkcsObjectIdentifiers.Sha1WithRsaEncryption);
+ algorithms.Add("SHA224WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha224WithRsaEncryption);
+ algorithms.Add("SHA224WITHRSA", PkcsObjectIdentifiers.Sha224WithRsaEncryption);
+ algorithms.Add("SHA256WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha256WithRsaEncryption);
+ algorithms.Add("SHA256WITHRSA", PkcsObjectIdentifiers.Sha256WithRsaEncryption);
+ algorithms.Add("SHA384WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha384WithRsaEncryption);
+ algorithms.Add("SHA384WITHRSA", PkcsObjectIdentifiers.Sha384WithRsaEncryption);
+ algorithms.Add("SHA512WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512WithRsaEncryption);
+ algorithms.Add("SHA512WITHRSA", PkcsObjectIdentifiers.Sha512WithRsaEncryption);
+ algorithms.Add("SHA1WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss);
+ algorithms.Add("SHA224WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss);
+ algorithms.Add("SHA256WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss);
+ algorithms.Add("SHA384WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss);
+ algorithms.Add("SHA512WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss);
+ algorithms.Add("RSAWITHSHA1", PkcsObjectIdentifiers.Sha1WithRsaEncryption);
+ algorithms.Add("RIPEMD128WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128);
+ algorithms.Add("RIPEMD128WITHRSA", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128);
+ algorithms.Add("RIPEMD160WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160);
+ algorithms.Add("RIPEMD160WITHRSA", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160);
+ algorithms.Add("RIPEMD256WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256);
+ algorithms.Add("RIPEMD256WITHRSA", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256);
+ algorithms.Add("SHA1WITHDSA", X9ObjectIdentifiers.IdDsaWithSha1);
+ algorithms.Add("DSAWITHSHA1", X9ObjectIdentifiers.IdDsaWithSha1);
+ algorithms.Add("SHA224WITHDSA", NistObjectIdentifiers.DsaWithSha224);
+ algorithms.Add("SHA256WITHDSA", NistObjectIdentifiers.DsaWithSha256);
+ algorithms.Add("SHA384WITHDSA", NistObjectIdentifiers.DsaWithSha384);
+ algorithms.Add("SHA512WITHDSA", NistObjectIdentifiers.DsaWithSha512);
+ algorithms.Add("SHA1WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha1);
+ algorithms.Add("SHA224WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha224);
+ algorithms.Add("SHA256WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha256);
+ algorithms.Add("SHA384WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha384);
+ algorithms.Add("SHA512WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha512);
+ algorithms.Add("ECDSAWITHSHA1", X9ObjectIdentifiers.ECDsaWithSha1);
+ algorithms.Add("GOST3411WITHGOST3410", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94);
+ algorithms.Add("GOST3410WITHGOST3411", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94);
+ algorithms.Add("GOST3411WITHECGOST3410", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001);
+ algorithms.Add("GOST3411WITHECGOST3410-2001", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001);
+ algorithms.Add("GOST3411WITHGOST3410-2001", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001);
+
+ //
+ // reverse mappings
+ //
+ oids.Add(PkcsObjectIdentifiers.Sha1WithRsaEncryption, "SHA1WITHRSA");
+ oids.Add(PkcsObjectIdentifiers.Sha224WithRsaEncryption, "SHA224WITHRSA");
+ oids.Add(PkcsObjectIdentifiers.Sha256WithRsaEncryption, "SHA256WITHRSA");
+ oids.Add(PkcsObjectIdentifiers.Sha384WithRsaEncryption, "SHA384WITHRSA");
+ oids.Add(PkcsObjectIdentifiers.Sha512WithRsaEncryption, "SHA512WITHRSA");
+ oids.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94, "GOST3411WITHGOST3410");
+ oids.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001, "GOST3411WITHECGOST3410");
+
+ oids.Add(PkcsObjectIdentifiers.MD5WithRsaEncryption, "MD5WITHRSA");
+ oids.Add(PkcsObjectIdentifiers.MD2WithRsaEncryption, "MD2WITHRSA");
+ oids.Add(X9ObjectIdentifiers.IdDsaWithSha1, "SHA1WITHDSA");
+ oids.Add(X9ObjectIdentifiers.ECDsaWithSha1, "SHA1WITHECDSA");
+ oids.Add(X9ObjectIdentifiers.ECDsaWithSha224, "SHA224WITHECDSA");
+ oids.Add(X9ObjectIdentifiers.ECDsaWithSha256, "SHA256WITHECDSA");
+ oids.Add(X9ObjectIdentifiers.ECDsaWithSha384, "SHA384WITHECDSA");
+ oids.Add(X9ObjectIdentifiers.ECDsaWithSha512, "SHA512WITHECDSA");
+ oids.Add(OiwObjectIdentifiers.MD5WithRsa, "MD5WITHRSA");
+ oids.Add(OiwObjectIdentifiers.Sha1WithRsa, "SHA1WITHRSA");
+ oids.Add(OiwObjectIdentifiers.DsaWithSha1, "SHA1WITHDSA");
+ oids.Add(NistObjectIdentifiers.DsaWithSha224, "SHA224WITHDSA");
+ oids.Add(NistObjectIdentifiers.DsaWithSha256, "SHA256WITHDSA");
+
+ //
+ // key types
+ //
+ keyAlgorithms.Add(PkcsObjectIdentifiers.RsaEncryption, "RSA");
+ keyAlgorithms.Add(X9ObjectIdentifiers.IdDsa, "DSA");
+
+ //
+ // According to RFC 3279, the ASN.1 encoding SHALL (id-dsa-with-sha1) or MUST (ecdsa-with-SHA*) omit the parameters field.
+ // The parameters field SHALL be NULL for RSA based signature algorithms.
+ //
+ noParams.Add(X9ObjectIdentifiers.ECDsaWithSha1);
+ noParams.Add(X9ObjectIdentifiers.ECDsaWithSha224);
+ noParams.Add(X9ObjectIdentifiers.ECDsaWithSha256);
+ noParams.Add(X9ObjectIdentifiers.ECDsaWithSha384);
+ noParams.Add(X9ObjectIdentifiers.ECDsaWithSha512);
+ noParams.Add(X9ObjectIdentifiers.IdDsaWithSha1);
+ noParams.Add(NistObjectIdentifiers.DsaWithSha224);
+ noParams.Add(NistObjectIdentifiers.DsaWithSha256);
+
+ //
+ // RFC 4491
+ //
+ noParams.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94);
+ noParams.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001);
+
+ //
+ // explicit params
+ //
+ AlgorithmIdentifier sha1AlgId = new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance);
+ exParams.Add("SHA1WITHRSAANDMGF1", CreatePssParams(sha1AlgId, 20));
+
+ AlgorithmIdentifier sha224AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha224, DerNull.Instance);
+ exParams.Add("SHA224WITHRSAANDMGF1", CreatePssParams(sha224AlgId, 28));
+
+ AlgorithmIdentifier sha256AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha256, DerNull.Instance);
+ exParams.Add("SHA256WITHRSAANDMGF1", CreatePssParams(sha256AlgId, 32));
+
+ AlgorithmIdentifier sha384AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha384, DerNull.Instance);
+ exParams.Add("SHA384WITHRSAANDMGF1", CreatePssParams(sha384AlgId, 48));
+
+ AlgorithmIdentifier sha512AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha512, DerNull.Instance);
+ exParams.Add("SHA512WITHRSAANDMGF1", CreatePssParams(sha512AlgId, 64));
+ }
+
+ private static RsassaPssParameters CreatePssParams(
+ AlgorithmIdentifier hashAlgId,
+ int saltSize)
+ {
+ return new RsassaPssParameters(
+ hashAlgId,
+ new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, hashAlgId),
+ new DerInteger(saltSize),
+ new DerInteger(1));
+ }
+
+ protected Pkcs10CertificationRequest()
+ {
+ }
+
+ public Pkcs10CertificationRequest(
+ byte[] encoded)
+ : base((Asn1Sequence) Asn1Object.FromByteArray(encoded))
+ {
+ }
+
+ public Pkcs10CertificationRequest(
+ Asn1Sequence seq)
+ : base(seq)
+ {
+ }
+
+ public Pkcs10CertificationRequest(
+ Stream input)
+ : base((Asn1Sequence) Asn1Object.FromStream(input))
+ {
+ }
+
+ ///
+ /// Instantiate a Pkcs10CertificationRequest object with the necessary credentials.
+ ///
+ ///Name of Sig Alg.
+ /// X509Name of subject eg OU="My unit." O="My Organisatioin" C="au"
+ /// Public Key to be included in cert reqest.
+ /// ASN1Set of Attributes.
+ /// Matching Private key for nominated (above) public key to be used to sign the request.
+ public Pkcs10CertificationRequest(
+ string signatureAlgorithm,
+ X509Name subject,
+ AsymmetricKeyParameter publicKey,
+ Asn1Set attributes,
+ AsymmetricKeyParameter signingKey)
+ : this(new Asn1SignatureFactory(signatureAlgorithm, signingKey), subject, publicKey, attributes)
+ {
+ }
+
+ ///
+ /// Instantiate a Pkcs10CertificationRequest object with the necessary credentials.
+ ///
+ ///The factory for signature calculators to sign the PKCS#10 request with.
+ /// X509Name of subject eg OU="My unit." O="My Organisatioin" C="au"
+ /// Public Key to be included in cert reqest.
+ /// ASN1Set of Attributes.
+ /// Ignored.
+ [Obsolete("Use constructor without 'signingKey' parameter (ignored here)")]
+ public Pkcs10CertificationRequest(
+ ISignatureFactory signatureFactory,
+ X509Name subject,
+ AsymmetricKeyParameter publicKey,
+ Asn1Set attributes,
+ AsymmetricKeyParameter signingKey)
+ : this(signatureFactory, subject, publicKey, attributes)
+ {
+ }
+
+ ///
+ /// Instantiate a Pkcs10CertificationRequest object with the necessary credentials.
+ ///
+ ///The factory for signature calculators to sign the PKCS#10 request with.
+ /// X509Name of subject eg OU="My unit." O="My Organisatioin" C="au"
+ /// Public Key to be included in cert reqest.
+ /// ASN1Set of Attributes.
+ public Pkcs10CertificationRequest(
+ ISignatureFactory signatureFactory,
+ X509Name subject,
+ AsymmetricKeyParameter publicKey,
+ Asn1Set attributes)
+ {
+ if (signatureFactory == null)
+ throw new ArgumentNullException("signatureFactory");
+ if (subject == null)
+ throw new ArgumentNullException("subject");
+ if (publicKey == null)
+ throw new ArgumentNullException("publicKey");
+ if (publicKey.IsPrivate)
+ throw new ArgumentException("expected public key", "publicKey");
+
+ Init(signatureFactory, subject, publicKey, attributes);
+ }
+
+ private void Init(
+ ISignatureFactory signatureFactory,
+ X509Name subject,
+ AsymmetricKeyParameter publicKey,
+ Asn1Set attributes)
+ {
+ this.sigAlgId = (AlgorithmIdentifier)signatureFactory.AlgorithmDetails;
+
+ SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
+
+ this.reqInfo = new CertificationRequestInfo(subject, pubInfo, attributes);
+
+ IStreamCalculator streamCalculator = signatureFactory.CreateCalculator();
+
+ byte[] reqInfoData = reqInfo.GetDerEncoded();
+
+ streamCalculator.Stream.Write(reqInfoData, 0, reqInfoData.Length);
+
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(streamCalculator.Stream);
+
+ // Generate Signature.
+ sigBits = new DerBitString(((IBlockResult)streamCalculator.GetResult()).Collect());
+ }
+
+ // internal Pkcs10CertificationRequest(
+ // Asn1InputStream seqStream)
+ // {
+ // Asn1Sequence seq = (Asn1Sequence) seqStream.ReadObject();
+ // try
+ // {
+ // this.reqInfo = CertificationRequestInfo.GetInstance(seq[0]);
+ // this.sigAlgId = AlgorithmIdentifier.GetInstance(seq[1]);
+ // this.sigBits = (DerBitString) seq[2];
+ // }
+ // catch (Exception ex)
+ // {
+ // throw new ArgumentException("Create From Asn1Sequence: " + ex.Message);
+ // }
+ // }
+
+ ///
+ /// Get the public key.
+ ///
+ /// The public key.
+ public AsymmetricKeyParameter GetPublicKey()
+ {
+ return PublicKeyFactory.CreateKey(reqInfo.SubjectPublicKeyInfo);
+ }
+
+ ///
+ /// Verify Pkcs10 Cert Request is valid.
+ ///
+ /// true = valid.
+ public bool Verify()
+ {
+ return Verify(this.GetPublicKey());
+ }
+
+ public bool Verify(
+ AsymmetricKeyParameter publicKey)
+ {
+ return Verify(new Asn1VerifierFactoryProvider(publicKey));
+ }
+
+ public bool Verify(
+ IVerifierFactoryProvider verifierProvider)
+ {
+ return Verify(verifierProvider.CreateVerifierFactory(sigAlgId));
+ }
+
+ public bool Verify(
+ IVerifierFactory verifier)
+ {
+ try
+ {
+ byte[] b = reqInfo.GetDerEncoded();
+
+ IStreamCalculator streamCalculator = verifier.CreateCalculator();
+
+ streamCalculator.Stream.Write(b, 0, b.Length);
+
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(streamCalculator.Stream);
+
+ return ((IVerifier)streamCalculator.GetResult()).IsVerified(sigBits.GetOctets());
+ }
+ catch (Exception e)
+ {
+ throw new SignatureException("exception encoding TBS cert request", e);
+ }
+ }
+
+ // ///
+ // /// Get the Der Encoded Pkcs10 Certification Request.
+ // ///
+ // /// A byte array.
+ // public byte[] GetEncoded()
+ // {
+ // return new CertificationRequest(reqInfo, sigAlgId, sigBits).GetDerEncoded();
+ // }
+
+ // TODO Figure out how to set parameters on an ISigner
+ private void SetSignatureParameters(
+ ISigner signature,
+ Asn1Encodable asn1Params)
+ {
+ if (asn1Params != null && !(asn1Params is Asn1Null))
+ {
+// AlgorithmParameters sigParams = AlgorithmParameters.GetInstance(signature.getAlgorithm());
+//
+// try
+// {
+// sigParams.init(asn1Params.ToAsn1Object().GetDerEncoded());
+// }
+// catch (IOException e)
+// {
+// throw new SignatureException("IOException decoding parameters: " + e.Message);
+// }
+
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(signature.AlgorithmName, "MGF1"))
+ {
+ throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("signature algorithm with MGF1");
+
+// try
+// {
+// signature.setParameter(sigParams.getParameterSpec(PSSParameterSpec.class));
+// }
+// catch (GeneralSecurityException e)
+// {
+// throw new SignatureException("Exception extracting parameters: " + e.getMessage());
+// }
+ }
+ }
+ }
+
+ internal static string GetSignatureName(
+ AlgorithmIdentifier sigAlgId)
+ {
+ Asn1Encodable asn1Params = sigAlgId.Parameters;
+
+ if (asn1Params != null && !(asn1Params is Asn1Null))
+ {
+ if (sigAlgId.Algorithm.Equals(PkcsObjectIdentifiers.IdRsassaPss))
+ {
+ RsassaPssParameters rsaParams = RsassaPssParameters.GetInstance(asn1Params);
+ return GetDigestAlgName(rsaParams.HashAlgorithm.Algorithm) + "withRSAandMGF1";
+ }
+ }
+
+ return sigAlgId.Algorithm.Id;
+ }
+
+ private static string GetDigestAlgName(
+ DerObjectIdentifier digestAlgOID)
+ {
+ if (PkcsObjectIdentifiers.MD5.Equals(digestAlgOID))
+ {
+ return "MD5";
+ }
+ else if (OiwObjectIdentifiers.IdSha1.Equals(digestAlgOID))
+ {
+ return "SHA1";
+ }
+ else if (NistObjectIdentifiers.IdSha224.Equals(digestAlgOID))
+ {
+ return "SHA224";
+ }
+ else if (NistObjectIdentifiers.IdSha256.Equals(digestAlgOID))
+ {
+ return "SHA256";
+ }
+ else if (NistObjectIdentifiers.IdSha384.Equals(digestAlgOID))
+ {
+ return "SHA384";
+ }
+ else if (NistObjectIdentifiers.IdSha512.Equals(digestAlgOID))
+ {
+ return "SHA512";
+ }
+ else if (TeleTrusTObjectIdentifiers.RipeMD128.Equals(digestAlgOID))
+ {
+ return "RIPEMD128";
+ }
+ else if (TeleTrusTObjectIdentifiers.RipeMD160.Equals(digestAlgOID))
+ {
+ return "RIPEMD160";
+ }
+ else if (TeleTrusTObjectIdentifiers.RipeMD256.Equals(digestAlgOID))
+ {
+ return "RIPEMD256";
+ }
+ else if (CryptoProObjectIdentifiers.GostR3411.Equals(digestAlgOID))
+ {
+ return "GOST3411";
+ }
+ else
+ {
+ return digestAlgOID.Id;
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs10CertificationRequest.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs10CertificationRequest.cs.meta
new file mode 100644
index 00000000..7999a1ad
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs10CertificationRequest.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: d42133b63178b014eb93bfce9e8655e6
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs10CertificationRequestDelaySigned.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs10CertificationRequestDelaySigned.cs
new file mode 100644
index 00000000..b4ec7c64
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs10CertificationRequestDelaySigned.cs
@@ -0,0 +1,154 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.Globalization;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Oiw;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.TeleTrust;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs
+{
+ ///
+ /// A class for creating and verifying Pkcs10 Certification requests (this is an extension on ).
+ /// The requests are made using delay signing. This is useful for situations where
+ /// the private key is in another environment and not directly accessible (e.g. HSM)
+ /// So the first step creates the request, then the signing is done outside this
+ /// object and the signature is then used to complete the request.
+ ///
+ ///
+ /// CertificationRequest ::= Sequence {
+ /// certificationRequestInfo CertificationRequestInfo,
+ /// signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }},
+ /// signature BIT STRING
+ /// }
+ ///
+ /// CertificationRequestInfo ::= Sequence {
+ /// version Integer { v1(0) } (v1,...),
+ /// subject Name,
+ /// subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }},
+ /// attributes [0] Attributes{{ CRIAttributes }}
+ /// }
+ ///
+ /// Attributes { ATTRIBUTE:IOSet } ::= Set OF Attr{{ IOSet }}
+ ///
+ /// Attr { ATTRIBUTE:IOSet } ::= Sequence {
+ /// type ATTRIBUTE.&id({IOSet}),
+ /// values Set SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{\@type})
+ /// }
+ ///
+ /// see
+ public class Pkcs10CertificationRequestDelaySigned : Pkcs10CertificationRequest
+ {
+ protected Pkcs10CertificationRequestDelaySigned()
+ : base()
+ {
+ }
+ public Pkcs10CertificationRequestDelaySigned(
+ byte[] encoded)
+ : base(encoded)
+ {
+ }
+ public Pkcs10CertificationRequestDelaySigned(
+ Asn1Sequence seq)
+ : base(seq)
+ {
+ }
+ public Pkcs10CertificationRequestDelaySigned(
+ Stream input)
+ : base(input)
+ {
+ }
+ public Pkcs10CertificationRequestDelaySigned(
+ string signatureAlgorithm,
+ X509Name subject,
+ AsymmetricKeyParameter publicKey,
+ Asn1Set attributes,
+ AsymmetricKeyParameter signingKey)
+ : base(signatureAlgorithm, subject, publicKey, attributes, signingKey)
+ {
+ }
+ ///
+ /// Instantiate a Pkcs10CertificationRequest object with the necessary credentials.
+ ///
+ /// Name of Sig Alg.
+ /// X509Name of subject eg OU="My unit." O="My Organisatioin" C="au"
+ /// Public Key to be included in cert reqest.
+ /// ASN1Set of Attributes.
+ ///
+ /// After the object is constructed use the and finally the
+ /// SignRequest methods to finalize the request.
+ ///
+ public Pkcs10CertificationRequestDelaySigned(
+ string signatureAlgorithm,
+ X509Name subject,
+ AsymmetricKeyParameter publicKey,
+ Asn1Set attributes)
+ {
+ if (signatureAlgorithm == null)
+ throw new ArgumentNullException("signatureAlgorithm");
+ if (subject == null)
+ throw new ArgumentNullException("subject");
+ if (publicKey == null)
+ throw new ArgumentNullException("publicKey");
+ if (publicKey.IsPrivate)
+ throw new ArgumentException("expected public key", "publicKey");
+// DerObjectIdentifier sigOid = SignerUtilities.GetObjectIdentifier(signatureAlgorithm);
+ string algorithmName = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(signatureAlgorithm);
+ DerObjectIdentifier sigOid = (DerObjectIdentifier) algorithms[algorithmName];
+ if (sigOid == null)
+ {
+ try
+ {
+ sigOid = new DerObjectIdentifier(algorithmName);
+ }
+ catch (Exception e)
+ {
+ throw new ArgumentException("Unknown signature type requested", e);
+ }
+ }
+ if (noParams.Contains(sigOid))
+ {
+ this.sigAlgId = new AlgorithmIdentifier(sigOid);
+ }
+ else if (exParams.Contains(algorithmName))
+ {
+ this.sigAlgId = new AlgorithmIdentifier(sigOid, (Asn1Encodable) exParams[algorithmName]);
+ }
+ else
+ {
+ this.sigAlgId = new AlgorithmIdentifier(sigOid, DerNull.Instance);
+ }
+ SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
+ this.reqInfo = new CertificationRequestInfo(subject, pubInfo, attributes);
+ }
+ public byte[] GetDataToSign()
+ {
+ return reqInfo.GetDerEncoded();
+ }
+ public void SignRequest(byte[] signedData)
+ {
+ //build the signature from the signed data
+ sigBits = new DerBitString(signedData);
+ }
+ public void SignRequest(DerBitString signedData)
+ {
+ //build the signature from the signed data
+ sigBits = signedData;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs10CertificationRequestDelaySigned.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs10CertificationRequestDelaySigned.cs.meta
new file mode 100644
index 00000000..eb010919
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs10CertificationRequestDelaySigned.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 91787b3601b63654b83ed2aaadde6434
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs12Entry.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs12Entry.cs
new file mode 100644
index 00000000..217ae96a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs12Entry.cs
@@ -0,0 +1,68 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs
+{
+ public abstract class Pkcs12Entry
+ {
+ private readonly IDictionary attributes;
+
+ protected internal Pkcs12Entry(
+ IDictionary attributes)
+ {
+ this.attributes = attributes;
+
+ foreach (DictionaryEntry entry in attributes)
+ {
+ if (!(entry.Key is string))
+ throw new ArgumentException("Attribute keys must be of type: " + typeof(string).FullName, "attributes");
+ if (!(entry.Value is Asn1Encodable))
+ throw new ArgumentException("Attribute values must be of type: " + typeof(Asn1Encodable).FullName, "attributes");
+ }
+ }
+
+ [Obsolete("Use 'object[index]' syntax instead")]
+ public Asn1Encodable GetBagAttribute(
+ DerObjectIdentifier oid)
+ {
+ return (Asn1Encodable)this.attributes[oid.Id];
+ }
+
+ [Obsolete("Use 'object[index]' syntax instead")]
+ public Asn1Encodable GetBagAttribute(
+ string oid)
+ {
+ return (Asn1Encodable)this.attributes[oid];
+ }
+
+ [Obsolete("Use 'BagAttributeKeys' property")]
+ public IEnumerator GetBagAttributeKeys()
+ {
+ return this.attributes.Keys.GetEnumerator();
+ }
+
+ public Asn1Encodable this[
+ DerObjectIdentifier oid]
+ {
+ get { return (Asn1Encodable) this.attributes[oid.Id]; }
+ }
+
+ public Asn1Encodable this[
+ string oid]
+ {
+ get { return (Asn1Encodable) this.attributes[oid]; }
+ }
+
+ public IEnumerable BagAttributeKeys
+ {
+ get { return new EnumerableProxy(this.attributes.Keys); }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs12Entry.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs12Entry.cs.meta
new file mode 100644
index 00000000..5b3f66bc
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs12Entry.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: b33d7051f7d07254d99adcf4f11f449f
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs12Store.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs12Store.cs
new file mode 100644
index 00000000..ec8a7e84
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs12Store.cs
@@ -0,0 +1,1108 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Oiw;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs
+{
+ public class Pkcs12Store
+ {
+ private readonly IgnoresCaseHashtable keys = new IgnoresCaseHashtable();
+ private readonly IDictionary localIds = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ private readonly IgnoresCaseHashtable certs = new IgnoresCaseHashtable();
+ private readonly IDictionary chainCerts = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ private readonly IDictionary keyCerts = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ private readonly DerObjectIdentifier keyAlgorithm;
+ private readonly DerObjectIdentifier certAlgorithm;
+ private readonly bool useDerEncoding;
+
+ private AsymmetricKeyEntry unmarkedKeyEntry = null;
+
+ private const int MinIterations = 1024;
+ private const int SaltSize = 20;
+
+ private static SubjectKeyIdentifier CreateSubjectKeyID(
+ AsymmetricKeyParameter pubKey)
+ {
+ return new SubjectKeyIdentifier(
+ SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pubKey));
+ }
+
+ internal class CertId
+ {
+ private readonly byte[] id;
+
+ internal CertId(
+ AsymmetricKeyParameter pubKey)
+ {
+ this.id = CreateSubjectKeyID(pubKey).GetKeyIdentifier();
+ }
+
+ internal CertId(
+ byte[] id)
+ {
+ this.id = id;
+ }
+
+ internal byte[] Id
+ {
+ get { return id; }
+ }
+
+ public override int GetHashCode()
+ {
+ return Arrays.GetHashCode(id);
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return true;
+
+ CertId other = obj as CertId;
+
+ if (other == null)
+ return false;
+
+ return Arrays.AreEqual(id, other.id);
+ }
+ }
+
+ internal Pkcs12Store(
+ DerObjectIdentifier keyAlgorithm,
+ DerObjectIdentifier certAlgorithm,
+ bool useDerEncoding)
+ {
+ this.keyAlgorithm = keyAlgorithm;
+ this.certAlgorithm = certAlgorithm;
+ this.useDerEncoding = useDerEncoding;
+ }
+
+ // TODO Consider making obsolete
+// [Obsolete("Use 'Pkcs12StoreBuilder' instead")]
+ public Pkcs12Store()
+ : this(PkcsObjectIdentifiers.PbeWithShaAnd3KeyTripleDesCbc,
+ PkcsObjectIdentifiers.PbewithShaAnd40BitRC2Cbc, false)
+ {
+ }
+
+ // TODO Consider making obsolete
+// [Obsolete("Use 'Pkcs12StoreBuilder' and 'Load' method instead")]
+ public Pkcs12Store(
+ Stream input,
+ char[] password)
+ : this()
+ {
+ Load(input, password);
+ }
+
+ protected virtual void LoadKeyBag(PrivateKeyInfo privKeyInfo, Asn1Set bagAttributes)
+ {
+ AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privKeyInfo);
+
+ IDictionary attributes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(privKey, attributes);
+
+ string alias = null;
+ Asn1OctetString localId = null;
+
+ if (bagAttributes != null)
+ {
+ foreach (Asn1Sequence sq in bagAttributes)
+ {
+ DerObjectIdentifier aOid = DerObjectIdentifier.GetInstance(sq[0]);
+ Asn1Set attrSet = Asn1Set.GetInstance(sq[1]);
+ Asn1Encodable attr = null;
+
+ if (attrSet.Count > 0)
+ {
+ // TODO We should be adding all attributes in the set
+ attr = attrSet[0];
+
+ // TODO We might want to "merge" attribute sets with
+ // the same OID - currently, differing values give an error
+ if (attributes.Contains(aOid.Id))
+ {
+ // OK, but the value has to be the same
+ if (!attributes[aOid.Id].Equals(attr))
+ throw new IOException("attempt to add existing attribute with different value");
+ }
+ else
+ {
+ attributes.Add(aOid.Id, attr);
+ }
+
+ if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
+ {
+ alias = ((DerBmpString)attr).GetString();
+ // TODO Do these in a separate loop, just collect aliases here
+ keys[alias] = keyEntry;
+ }
+ else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
+ {
+ localId = (Asn1OctetString)attr;
+ }
+ }
+ }
+ }
+
+ if (localId != null)
+ {
+ string name = Hex.ToHexString(localId.GetOctets());
+
+ if (alias == null)
+ {
+ keys[name] = keyEntry;
+ }
+ else
+ {
+ // TODO There may have been more than one alias
+ localIds[alias] = name;
+ }
+ }
+ else
+ {
+ unmarkedKeyEntry = keyEntry;
+ }
+ }
+
+ protected virtual void LoadPkcs8ShroudedKeyBag(EncryptedPrivateKeyInfo encPrivKeyInfo, Asn1Set bagAttributes,
+ char[] password, bool wrongPkcs12Zero)
+ {
+ if (password != null)
+ {
+ PrivateKeyInfo privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(
+ password, wrongPkcs12Zero, encPrivKeyInfo);
+
+ LoadKeyBag(privInfo, bagAttributes);
+ }
+ }
+
+ public void Load(
+ Stream input,
+ char[] password)
+ {
+ if (input == null)
+ throw new ArgumentNullException("input");
+
+ Asn1Sequence obj = (Asn1Sequence) Asn1Object.FromStream(input);
+ Pfx bag = new Pfx(obj);
+ ContentInfo info = bag.AuthSafe;
+ bool wrongPkcs12Zero = false;
+
+ if (password != null && bag.MacData != null) // check the mac code
+ {
+ MacData mData = bag.MacData;
+ DigestInfo dInfo = mData.Mac;
+ AlgorithmIdentifier algId = dInfo.AlgorithmID;
+ byte[] salt = mData.GetSalt();
+ int itCount = mData.IterationCount.IntValue;
+
+ byte[] data = ((Asn1OctetString) info.Content).GetOctets();
+
+ byte[] mac = CalculatePbeMac(algId.Algorithm, salt, itCount, password, false, data);
+ byte[] dig = dInfo.GetDigest();
+
+ if (!Arrays.ConstantTimeAreEqual(mac, dig))
+ {
+ if (password.Length > 0)
+ throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file.");
+
+ // Try with incorrect zero length password
+ mac = CalculatePbeMac(algId.Algorithm, salt, itCount, password, true, data);
+
+ if (!Arrays.ConstantTimeAreEqual(mac, dig))
+ throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file.");
+
+ wrongPkcs12Zero = true;
+ }
+ }
+
+ keys.Clear();
+ localIds.Clear();
+ unmarkedKeyEntry = null;
+
+ IList certBags = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+
+ if (info.ContentType.Equals(PkcsObjectIdentifiers.Data))
+ {
+ byte[] octs = ((Asn1OctetString)info.Content).GetOctets();
+ AuthenticatedSafe authSafe = new AuthenticatedSafe(
+ (Asn1Sequence) Asn1OctetString.FromByteArray(octs));
+ ContentInfo[] cis = authSafe.GetContentInfo();
+
+ foreach (ContentInfo ci in cis)
+ {
+ DerObjectIdentifier oid = ci.ContentType;
+
+ byte[] octets = null;
+ if (oid.Equals(PkcsObjectIdentifiers.Data))
+ {
+ octets = ((Asn1OctetString)ci.Content).GetOctets();
+ }
+ else if (oid.Equals(PkcsObjectIdentifiers.EncryptedData))
+ {
+ if (password != null)
+ {
+ EncryptedData d = EncryptedData.GetInstance(ci.Content);
+ octets = CryptPbeData(false, d.EncryptionAlgorithm,
+ password, wrongPkcs12Zero, d.Content.GetOctets());
+ }
+ }
+ else
+ {
+ // TODO Other data types
+ }
+
+ if (octets != null)
+ {
+ Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(octets);
+
+ foreach (Asn1Sequence subSeq in seq)
+ {
+ SafeBag b = new SafeBag(subSeq);
+
+ if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag))
+ {
+ certBags.Add(b);
+ }
+ else if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag))
+ {
+ LoadPkcs8ShroudedKeyBag(EncryptedPrivateKeyInfo.GetInstance(b.BagValue),
+ b.BagAttributes, password, wrongPkcs12Zero);
+ }
+ else if (b.BagID.Equals(PkcsObjectIdentifiers.KeyBag))
+ {
+ LoadKeyBag(PrivateKeyInfo.GetInstance(b.BagValue), b.BagAttributes);
+ }
+ else
+ {
+ // TODO Other bag types
+ }
+ }
+ }
+ }
+ }
+
+ certs.Clear();
+ chainCerts.Clear();
+ keyCerts.Clear();
+
+ foreach (SafeBag b in certBags)
+ {
+ CertBag certBag = new CertBag((Asn1Sequence)b.BagValue);
+ byte[] octets = ((Asn1OctetString)certBag.CertValue).GetOctets();
+ X509Certificate cert = new X509CertificateParser().ReadCertificate(octets);
+
+ //
+ // set the attributes
+ //
+ IDictionary attributes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ Asn1OctetString localId = null;
+ string alias = null;
+
+ if (b.BagAttributes != null)
+ {
+ foreach (Asn1Sequence sq in b.BagAttributes)
+ {
+ DerObjectIdentifier aOid = DerObjectIdentifier.GetInstance(sq[0]);
+ Asn1Set attrSet = Asn1Set.GetInstance(sq[1]);
+
+ if (attrSet.Count > 0)
+ {
+ // TODO We should be adding all attributes in the set
+ Asn1Encodable attr = attrSet[0];
+
+ // TODO We might want to "merge" attribute sets with
+ // the same OID - currently, differing values give an error
+ if (attributes.Contains(aOid.Id))
+ {
+ // OK, but the value has to be the same
+ if (!attributes[aOid.Id].Equals(attr))
+ {
+ throw new IOException("attempt to add existing attribute with different value");
+ }
+ }
+ else
+ {
+ attributes.Add(aOid.Id, attr);
+ }
+
+ if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
+ {
+ alias = ((DerBmpString)attr).GetString();
+ }
+ else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
+ {
+ localId = (Asn1OctetString)attr;
+ }
+ }
+ }
+ }
+
+ CertId certId = new CertId(cert.GetPublicKey());
+ X509CertificateEntry certEntry = new X509CertificateEntry(cert, attributes);
+
+ chainCerts[certId] = certEntry;
+
+ if (unmarkedKeyEntry != null)
+ {
+ if (keyCerts.Count == 0)
+ {
+ string name = Hex.ToHexString(certId.Id);
+
+ keyCerts[name] = certEntry;
+ keys[name] = unmarkedKeyEntry;
+ }
+ else
+ {
+ keys["unmarked"] = unmarkedKeyEntry;
+ }
+ }
+ else
+ {
+ if (localId != null)
+ {
+ string name = Hex.ToHexString(localId.GetOctets());
+
+ keyCerts[name] = certEntry;
+ }
+
+ if (alias != null)
+ {
+ // TODO There may have been more than one alias
+ certs[alias] = certEntry;
+ }
+ }
+ }
+ }
+
+ public AsymmetricKeyEntry GetKey(
+ string alias)
+ {
+ if (alias == null)
+ throw new ArgumentNullException("alias");
+
+ return (AsymmetricKeyEntry)keys[alias];
+ }
+
+ public bool IsCertificateEntry(
+ string alias)
+ {
+ if (alias == null)
+ throw new ArgumentNullException("alias");
+
+ return (certs[alias] != null && keys[alias] == null);
+ }
+
+ public bool IsKeyEntry(
+ string alias)
+ {
+ if (alias == null)
+ throw new ArgumentNullException("alias");
+
+ return (keys[alias] != null);
+ }
+
+ private IDictionary GetAliasesTable()
+ {
+ IDictionary tab = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+
+ foreach (string key in certs.Keys)
+ {
+ tab[key] = "cert";
+ }
+
+ foreach (string a in keys.Keys)
+ {
+ if (tab[a] == null)
+ {
+ tab[a] = "key";
+ }
+ }
+
+ return tab;
+ }
+
+ public IEnumerable Aliases
+ {
+ get { return new EnumerableProxy(GetAliasesTable().Keys); }
+ }
+
+ public bool ContainsAlias(
+ string alias)
+ {
+ return certs[alias] != null || keys[alias] != null;
+ }
+
+ /**
+ * simply return the cert entry for the private key
+ */
+ public X509CertificateEntry GetCertificate(
+ string alias)
+ {
+ if (alias == null)
+ throw new ArgumentNullException("alias");
+
+ X509CertificateEntry c = (X509CertificateEntry) certs[alias];
+
+ //
+ // look up the key table - and try the local key id
+ //
+ if (c == null)
+ {
+ string id = (string)localIds[alias];
+ if (id != null)
+ {
+ c = (X509CertificateEntry)keyCerts[id];
+ }
+ else
+ {
+ c = (X509CertificateEntry)keyCerts[alias];
+ }
+ }
+
+ return c;
+ }
+
+ public string GetCertificateAlias(
+ X509Certificate cert)
+ {
+ if (cert == null)
+ throw new ArgumentNullException("cert");
+
+ foreach (DictionaryEntry entry in certs)
+ {
+ X509CertificateEntry entryValue = (X509CertificateEntry) entry.Value;
+ if (entryValue.Certificate.Equals(cert))
+ {
+ return (string) entry.Key;
+ }
+ }
+
+ foreach (DictionaryEntry entry in keyCerts)
+ {
+ X509CertificateEntry entryValue = (X509CertificateEntry) entry.Value;
+ if (entryValue.Certificate.Equals(cert))
+ {
+ return (string) entry.Key;
+ }
+ }
+
+ return null;
+ }
+
+ public X509CertificateEntry[] GetCertificateChain(
+ string alias)
+ {
+ if (alias == null)
+ throw new ArgumentNullException("alias");
+
+ if (!IsKeyEntry(alias))
+ {
+ return null;
+ }
+
+ X509CertificateEntry c = GetCertificate(alias);
+
+ if (c != null)
+ {
+ IList cs = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+
+ while (c != null)
+ {
+ X509Certificate x509c = c.Certificate;
+ X509CertificateEntry nextC = null;
+
+ Asn1OctetString ext = x509c.GetExtensionValue(X509Extensions.AuthorityKeyIdentifier);
+ if (ext != null)
+ {
+ AuthorityKeyIdentifier id = AuthorityKeyIdentifier.GetInstance(
+ Asn1Object.FromByteArray(ext.GetOctets()));
+
+ if (id.GetKeyIdentifier() != null)
+ {
+ nextC = (X509CertificateEntry) chainCerts[new CertId(id.GetKeyIdentifier())];
+ }
+ }
+
+ if (nextC == null)
+ {
+ //
+ // no authority key id, try the Issuer DN
+ //
+ X509Name i = x509c.IssuerDN;
+ X509Name s = x509c.SubjectDN;
+
+ if (!i.Equivalent(s))
+ {
+ foreach (CertId certId in chainCerts.Keys)
+ {
+ X509CertificateEntry x509CertEntry = (X509CertificateEntry) chainCerts[certId];
+
+ X509Certificate crt = x509CertEntry.Certificate;
+
+ X509Name sub = crt.SubjectDN;
+ if (sub.Equivalent(i))
+ {
+ try
+ {
+ x509c.Verify(crt.GetPublicKey());
+
+ nextC = x509CertEntry;
+ break;
+ }
+ catch (InvalidKeyException)
+ {
+ // TODO What if it doesn't verify?
+ }
+ }
+ }
+ }
+ }
+
+ cs.Add(c);
+ if (nextC != c) // self signed - end of the chain
+ {
+ c = nextC;
+ }
+ else
+ {
+ c = null;
+ }
+ }
+
+ X509CertificateEntry[] result = new X509CertificateEntry[cs.Count];
+ for (int i = 0; i < cs.Count; ++i)
+ {
+ result[i] = (X509CertificateEntry)cs[i];
+ }
+ return result;
+ }
+
+ return null;
+ }
+
+ public void SetCertificateEntry(
+ string alias,
+ X509CertificateEntry certEntry)
+ {
+ if (alias == null)
+ throw new ArgumentNullException("alias");
+ if (certEntry == null)
+ throw new ArgumentNullException("certEntry");
+ if (keys[alias] != null)
+ throw new ArgumentException("There is a key entry with the name " + alias + ".");
+
+ certs[alias] = certEntry;
+ chainCerts[new CertId(certEntry.Certificate.GetPublicKey())] = certEntry;
+ }
+
+ public void SetKeyEntry(
+ string alias,
+ AsymmetricKeyEntry keyEntry,
+ X509CertificateEntry[] chain)
+ {
+ if (alias == null)
+ throw new ArgumentNullException("alias");
+ if (keyEntry == null)
+ throw new ArgumentNullException("keyEntry");
+ if (keyEntry.Key.IsPrivate && (chain == null))
+ throw new ArgumentException("No certificate chain for private key");
+
+ if (keys[alias] != null)
+ {
+ DeleteEntry(alias);
+ }
+
+ keys[alias] = keyEntry;
+ certs[alias] = chain[0];
+
+ for (int i = 0; i != chain.Length; i++)
+ {
+ chainCerts[new CertId(chain[i].Certificate.GetPublicKey())] = chain[i];
+ }
+ }
+
+ public void DeleteEntry(
+ string alias)
+ {
+ if (alias == null)
+ throw new ArgumentNullException("alias");
+
+ AsymmetricKeyEntry k = (AsymmetricKeyEntry)keys[alias];
+ if (k != null)
+ {
+ keys.Remove(alias);
+ }
+
+ X509CertificateEntry c = (X509CertificateEntry)certs[alias];
+
+ if (c != null)
+ {
+ certs.Remove(alias);
+ chainCerts.Remove(new CertId(c.Certificate.GetPublicKey()));
+ }
+
+ if (k != null)
+ {
+ string id = (string)localIds[alias];
+ if (id != null)
+ {
+ localIds.Remove(alias);
+ c = (X509CertificateEntry)keyCerts[id];
+ }
+ if (c != null)
+ {
+ keyCerts.Remove(id);
+ chainCerts.Remove(new CertId(c.Certificate.GetPublicKey()));
+ }
+ }
+
+ if (c == null && k == null)
+ {
+ throw new ArgumentException("no such entry as " + alias);
+ }
+ }
+
+ public bool IsEntryOfType(
+ string alias,
+ Type entryType)
+ {
+ if (entryType == typeof(X509CertificateEntry))
+ return IsCertificateEntry(alias);
+
+ if (entryType == typeof(AsymmetricKeyEntry))
+ return IsKeyEntry(alias) && GetCertificate(alias) != null;
+
+ return false;
+ }
+
+ [Obsolete("Use 'Count' property instead")]
+ public int Size()
+ {
+ return Count;
+ }
+
+ public int Count
+ {
+ // TODO Seems a little inefficient
+ get { return GetAliasesTable().Count; }
+ }
+
+ public void Save(
+ Stream stream,
+ char[] password,
+ SecureRandom random)
+ {
+ if (stream == null)
+ throw new ArgumentNullException("stream");
+ if (random == null)
+ throw new ArgumentNullException("random");
+
+ //
+ // handle the keys
+ //
+ Asn1EncodableVector keyBags = new Asn1EncodableVector();
+ foreach (string name in keys.Keys)
+ {
+ byte[] kSalt = new byte[SaltSize];
+ random.NextBytes(kSalt);
+
+ AsymmetricKeyEntry privKey = (AsymmetricKeyEntry)keys[name];
+
+ DerObjectIdentifier bagOid;
+ Asn1Encodable bagData;
+
+ if (password == null)
+ {
+ bagOid = PkcsObjectIdentifiers.KeyBag;
+ bagData = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privKey.Key);
+ }
+ else
+ {
+ bagOid = PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag;
+ bagData = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
+ keyAlgorithm, password, kSalt, MinIterations, privKey.Key);
+ }
+
+ Asn1EncodableVector kName = new Asn1EncodableVector();
+
+ foreach (string oid in privKey.BagAttributeKeys)
+ {
+ Asn1Encodable entry = privKey[oid];
+
+ // NB: Ignore any existing FriendlyName
+ if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id))
+ continue;
+
+ kName.Add(
+ new DerSequence(
+ new DerObjectIdentifier(oid),
+ new DerSet(entry)));
+ }
+
+ //
+ // make sure we are using the local alias on store
+ //
+ // NB: We always set the FriendlyName based on 'name'
+ //if (privKey[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null)
+ {
+ kName.Add(
+ new DerSequence(
+ PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
+ new DerSet(new DerBmpString(name))));
+ }
+
+ //
+ // make sure we have a local key-id
+ //
+ if (privKey[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null)
+ {
+ X509CertificateEntry ct = GetCertificate(name);
+ AsymmetricKeyParameter pubKey = ct.Certificate.GetPublicKey();
+ SubjectKeyIdentifier subjectKeyID = CreateSubjectKeyID(pubKey);
+
+ kName.Add(
+ new DerSequence(
+ PkcsObjectIdentifiers.Pkcs9AtLocalKeyID,
+ new DerSet(subjectKeyID)));
+ }
+
+ keyBags.Add(new SafeBag(bagOid, bagData.ToAsn1Object(), new DerSet(kName)));
+ }
+
+ byte[] keyBagsEncoding = new DerSequence(keyBags).GetDerEncoded();
+ ContentInfo keysInfo = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(keyBagsEncoding));
+
+ //
+ // certificate processing
+ //
+ byte[] cSalt = new byte[SaltSize];
+
+ random.NextBytes(cSalt);
+
+ Asn1EncodableVector certBags = new Asn1EncodableVector();
+ Pkcs12PbeParams cParams = new Pkcs12PbeParams(cSalt, MinIterations);
+ AlgorithmIdentifier cAlgId = new AlgorithmIdentifier(certAlgorithm, cParams.ToAsn1Object());
+ ISet doneCerts = new HashSet();
+
+ foreach (string name in keys.Keys)
+ {
+ X509CertificateEntry certEntry = GetCertificate(name);
+ CertBag cBag = new CertBag(
+ PkcsObjectIdentifiers.X509Certificate,
+ new DerOctetString(certEntry.Certificate.GetEncoded()));
+
+ Asn1EncodableVector fName = new Asn1EncodableVector();
+
+ foreach (string oid in certEntry.BagAttributeKeys)
+ {
+ Asn1Encodable entry = certEntry[oid];
+
+ // NB: Ignore any existing FriendlyName
+ if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id))
+ continue;
+
+ fName.Add(
+ new DerSequence(
+ new DerObjectIdentifier(oid),
+ new DerSet(entry)));
+ }
+
+ //
+ // make sure we are using the local alias on store
+ //
+ // NB: We always set the FriendlyName based on 'name'
+ //if (certEntry[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null)
+ {
+ fName.Add(
+ new DerSequence(
+ PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
+ new DerSet(new DerBmpString(name))));
+ }
+
+ //
+ // make sure we have a local key-id
+ //
+ if (certEntry[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null)
+ {
+ AsymmetricKeyParameter pubKey = certEntry.Certificate.GetPublicKey();
+ SubjectKeyIdentifier subjectKeyID = CreateSubjectKeyID(pubKey);
+
+ fName.Add(
+ new DerSequence(
+ PkcsObjectIdentifiers.Pkcs9AtLocalKeyID,
+ new DerSet(subjectKeyID)));
+ }
+
+ certBags.Add(new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)));
+
+ doneCerts.Add(certEntry.Certificate);
+ }
+
+ foreach (string certId in certs.Keys)
+ {
+ X509CertificateEntry cert = (X509CertificateEntry)certs[certId];
+
+ if (keys[certId] != null)
+ continue;
+
+ CertBag cBag = new CertBag(
+ PkcsObjectIdentifiers.X509Certificate,
+ new DerOctetString(cert.Certificate.GetEncoded()));
+
+ Asn1EncodableVector fName = new Asn1EncodableVector();
+
+ foreach (string oid in cert.BagAttributeKeys)
+ {
+ // a certificate not immediately linked to a key doesn't require
+ // a localKeyID and will confuse some PKCS12 implementations.
+ //
+ // If we find one, we'll prune it out.
+ if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id))
+ continue;
+
+ Asn1Encodable entry = cert[oid];
+
+ // NB: Ignore any existing FriendlyName
+ if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id))
+ continue;
+
+ fName.Add(
+ new DerSequence(
+ new DerObjectIdentifier(oid),
+ new DerSet(entry)));
+ }
+
+ //
+ // make sure we are using the local alias on store
+ //
+ // NB: We always set the FriendlyName based on 'certId'
+ //if (cert[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null)
+ {
+ fName.Add(
+ new DerSequence(
+ PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
+ new DerSet(new DerBmpString(certId))));
+ }
+
+ certBags.Add(new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)));
+
+ doneCerts.Add(cert.Certificate);
+ }
+
+ foreach (CertId certId in chainCerts.Keys)
+ {
+ X509CertificateEntry cert = (X509CertificateEntry)chainCerts[certId];
+
+ if (doneCerts.Contains(cert.Certificate))
+ continue;
+
+ CertBag cBag = new CertBag(
+ PkcsObjectIdentifiers.X509Certificate,
+ new DerOctetString(cert.Certificate.GetEncoded()));
+
+ Asn1EncodableVector fName = new Asn1EncodableVector();
+
+ foreach (string oid in cert.BagAttributeKeys)
+ {
+ // a certificate not immediately linked to a key doesn't require
+ // a localKeyID and will confuse some PKCS12 implementations.
+ //
+ // If we find one, we'll prune it out.
+ if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id))
+ continue;
+
+ fName.Add(
+ new DerSequence(
+ new DerObjectIdentifier(oid),
+ new DerSet(cert[oid])));
+ }
+
+ certBags.Add(new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)));
+ }
+
+ byte[] certBagsEncoding = new DerSequence(certBags).GetDerEncoded();
+
+ ContentInfo certsInfo;
+ if (password == null)
+ {
+ certsInfo = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(certBagsEncoding));
+ }
+ else
+ {
+ byte[] certBytes = CryptPbeData(true, cAlgId, password, false, certBagsEncoding);
+ EncryptedData cInfo = new EncryptedData(PkcsObjectIdentifiers.Data, cAlgId, new BerOctetString(certBytes));
+ certsInfo = new ContentInfo(PkcsObjectIdentifiers.EncryptedData, cInfo.ToAsn1Object());
+ }
+
+ ContentInfo[] info = new ContentInfo[]{ keysInfo, certsInfo };
+
+ byte[] data = new AuthenticatedSafe(info).GetEncoded(
+ useDerEncoding ? Asn1Encodable.Der : Asn1Encodable.Ber);
+
+ ContentInfo mainInfo = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(data));
+
+ //
+ // create the mac
+ //
+ MacData macData = null;
+ if (password != null)
+ {
+ byte[] mSalt = new byte[20];
+ random.NextBytes(mSalt);
+
+ byte[] mac = CalculatePbeMac(OiwObjectIdentifiers.IdSha1,
+ mSalt, MinIterations, password, false, data);
+
+ AlgorithmIdentifier algId = new AlgorithmIdentifier(
+ OiwObjectIdentifiers.IdSha1, DerNull.Instance);
+ DigestInfo dInfo = new DigestInfo(algId, mac);
+
+ macData = new MacData(dInfo, mSalt, MinIterations);
+ }
+
+ //
+ // output the Pfx
+ //
+ Pfx pfx = new Pfx(mainInfo, macData);
+
+ DerOutputStream derOut;
+ if (useDerEncoding)
+ {
+ derOut = new DerOutputStream(stream);
+ }
+ else
+ {
+ derOut = new BerOutputStream(stream);
+ }
+
+ derOut.WriteObject(pfx);
+ }
+
+ internal static byte[] CalculatePbeMac(
+ DerObjectIdentifier oid,
+ byte[] salt,
+ int itCount,
+ char[] password,
+ bool wrongPkcs12Zero,
+ byte[] data)
+ {
+ Asn1Encodable asn1Params = PbeUtilities.GenerateAlgorithmParameters(
+ oid, salt, itCount);
+ ICipherParameters cipherParams = PbeUtilities.GenerateCipherParameters(
+ oid, password, wrongPkcs12Zero, asn1Params);
+
+ IMac mac = (IMac) PbeUtilities.CreateEngine(oid);
+ mac.Init(cipherParams);
+ return MacUtilities.DoFinal(mac, data);
+ }
+
+ private static byte[] CryptPbeData(
+ bool forEncryption,
+ AlgorithmIdentifier algId,
+ char[] password,
+ bool wrongPkcs12Zero,
+ byte[] data)
+ {
+ IBufferedCipher cipher = PbeUtilities.CreateEngine(algId.Algorithm) as IBufferedCipher;
+
+ if (cipher == null)
+ throw new Exception("Unknown encryption algorithm: " + algId.Algorithm);
+
+ Pkcs12PbeParams pbeParameters = Pkcs12PbeParams.GetInstance(algId.Parameters);
+ ICipherParameters cipherParams = PbeUtilities.GenerateCipherParameters(
+ algId.Algorithm, password, wrongPkcs12Zero, pbeParameters);
+ cipher.Init(forEncryption, cipherParams);
+ return cipher.DoFinal(data);
+ }
+
+ private class IgnoresCaseHashtable
+ : IEnumerable
+ {
+ private readonly IDictionary orig = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ private readonly IDictionary keys = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+
+ public void Clear()
+ {
+ orig.Clear();
+ keys.Clear();
+ }
+
+ public IEnumerator GetEnumerator()
+ {
+ return orig.GetEnumerator();
+ }
+
+ public ICollection Keys
+ {
+ get { return orig.Keys; }
+ }
+
+ public object Remove(
+ string alias)
+ {
+ string upper = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(alias);
+ string k = (string)keys[upper];
+
+ if (k == null)
+ return null;
+
+ keys.Remove(upper);
+
+ object o = orig[k];
+ orig.Remove(k);
+ return o;
+ }
+
+ public object this[
+ string alias]
+ {
+ get
+ {
+ string upper = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(alias);
+ string k = (string)keys[upper];
+
+ if (k == null)
+ return null;
+
+ return orig[k];
+ }
+ set
+ {
+ string upper = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(alias);
+ string k = (string)keys[upper];
+ if (k != null)
+ {
+ orig.Remove(k);
+ }
+ keys[upper] = alias;
+ orig[alias] = value;
+ }
+ }
+
+ public ICollection Values
+ {
+ get { return orig.Values; }
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs12Store.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs12Store.cs.meta
new file mode 100644
index 00000000..480c210d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs12Store.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 168dce1c98ed30a41b666da9816a25c6
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs12Utilities.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs12Utilities.cs
new file mode 100644
index 00000000..f32bc937
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs12Utilities.cs
@@ -0,0 +1,81 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs
+{
+ /**
+ * Utility class for reencoding PKCS#12 files to definite length.
+ */
+ public class Pkcs12Utilities
+ {
+ /**
+ * Just re-encode the outer layer of the PKCS#12 file to definite length encoding.
+ *
+ * @param berPKCS12File - original PKCS#12 file
+ * @return a byte array representing the DER encoding of the PFX structure
+ * @throws IOException
+ */
+ public static byte[] ConvertToDefiniteLength(
+ byte[] berPkcs12File)
+ {
+ Pfx pfx = new Pfx(Asn1Sequence.GetInstance(Asn1Object.FromByteArray(berPkcs12File)));
+
+ return pfx.GetEncoded(Asn1Encodable.Der);
+ }
+
+ /**
+ * Re-encode the PKCS#12 structure to definite length encoding at the inner layer
+ * as well, recomputing the MAC accordingly.
+ *
+ * @param berPKCS12File - original PKCS12 file.
+ * @param provider - provider to use for MAC calculation.
+ * @return a byte array representing the DER encoding of the PFX structure.
+ * @throws IOException on parsing, encoding errors.
+ */
+ public static byte[] ConvertToDefiniteLength(
+ byte[] berPkcs12File,
+ char[] passwd)
+ {
+ Pfx pfx = new Pfx(Asn1Sequence.GetInstance(Asn1Object.FromByteArray(berPkcs12File)));
+
+ ContentInfo info = pfx.AuthSafe;
+
+ Asn1OctetString content = Asn1OctetString.GetInstance(info.Content);
+ Asn1Object obj = Asn1Object.FromByteArray(content.GetOctets());
+
+ info = new ContentInfo(info.ContentType, new DerOctetString(obj.GetEncoded(Asn1Encodable.Der)));
+
+ MacData mData = pfx.MacData;
+
+ try
+ {
+ int itCount = mData.IterationCount.IntValue;
+ byte[] data = Asn1OctetString.GetInstance(info.Content).GetOctets();
+ byte[] res = Pkcs12Store.CalculatePbeMac(
+ mData.Mac.AlgorithmID.Algorithm, mData.GetSalt(), itCount, passwd, false, data);
+
+ AlgorithmIdentifier algId = new AlgorithmIdentifier(
+ mData.Mac.AlgorithmID.Algorithm, DerNull.Instance);
+ DigestInfo dInfo = new DigestInfo(algId, res);
+
+ mData = new MacData(dInfo, mData.GetSalt(), itCount);
+ }
+ catch (Exception e)
+ {
+ throw new IOException("error constructing MAC: " + e.ToString());
+ }
+
+ pfx = new Pfx(info, mData);
+
+ return pfx.GetEncoded(Asn1Encodable.Der);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs12Utilities.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs12Utilities.cs.meta
new file mode 100644
index 00000000..6ebf168e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/Pkcs12Utilities.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 351095fcda1b7be4fa4bc49f38ce24d7
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/PrivateKeyInfoFactory.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/PrivateKeyInfoFactory.cs
new file mode 100644
index 00000000..2b7631bc
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/PrivateKeyInfoFactory.cs
@@ -0,0 +1,253 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.EdEC;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Oiw;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Sec;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs
+{
+ public sealed class PrivateKeyInfoFactory
+ {
+ private PrivateKeyInfoFactory()
+ {
+ }
+
+ public static PrivateKeyInfo CreatePrivateKeyInfo(
+ AsymmetricKeyParameter privateKey)
+ {
+ return CreatePrivateKeyInfo(privateKey, null);
+ }
+
+ /**
+ * Create a PrivateKeyInfo representation of a private key with attributes.
+ *
+ * @param privateKey the key to be encoded into the info object.
+ * @param attributes the set of attributes to be included.
+ * @return the appropriate PrivateKeyInfo
+ * @throws java.io.IOException on an error encoding the key
+ */
+ public static PrivateKeyInfo CreatePrivateKeyInfo(AsymmetricKeyParameter privateKey, Asn1Set attributes)
+ {
+ if (privateKey == null)
+ throw new ArgumentNullException("privateKey");
+ if (!privateKey.IsPrivate)
+ throw new ArgumentException("Public key passed - private key expected", "privateKey");
+
+ if (privateKey is ElGamalPrivateKeyParameters)
+ {
+ ElGamalPrivateKeyParameters _key = (ElGamalPrivateKeyParameters)privateKey;
+ ElGamalParameters egp = _key.Parameters;
+ return new PrivateKeyInfo(
+ new AlgorithmIdentifier(OiwObjectIdentifiers.ElGamalAlgorithm, new ElGamalParameter(egp.P, egp.G).ToAsn1Object()),
+ new DerInteger(_key.X),
+ attributes);
+ }
+
+ if (privateKey is DsaPrivateKeyParameters)
+ {
+ DsaPrivateKeyParameters _key = (DsaPrivateKeyParameters)privateKey;
+ DsaParameters dp = _key.Parameters;
+ return new PrivateKeyInfo(
+ new AlgorithmIdentifier(X9ObjectIdentifiers.IdDsa, new DsaParameter(dp.P, dp.Q, dp.G).ToAsn1Object()),
+ new DerInteger(_key.X),
+ attributes);
+ }
+
+ if (privateKey is DHPrivateKeyParameters)
+ {
+ DHPrivateKeyParameters _key = (DHPrivateKeyParameters)privateKey;
+
+ DHParameter p = new DHParameter(
+ _key.Parameters.P, _key.Parameters.G, _key.Parameters.L);
+
+ return new PrivateKeyInfo(
+ new AlgorithmIdentifier(_key.AlgorithmOid, p.ToAsn1Object()),
+ new DerInteger(_key.X),
+ attributes);
+ }
+
+ if (privateKey is RsaKeyParameters)
+ {
+ AlgorithmIdentifier algID = new AlgorithmIdentifier(
+ PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance);
+
+ RsaPrivateKeyStructure keyStruct;
+ if (privateKey is RsaPrivateCrtKeyParameters)
+ {
+ RsaPrivateCrtKeyParameters _key = (RsaPrivateCrtKeyParameters)privateKey;
+
+ keyStruct = new RsaPrivateKeyStructure(
+ _key.Modulus,
+ _key.PublicExponent,
+ _key.Exponent,
+ _key.P,
+ _key.Q,
+ _key.DP,
+ _key.DQ,
+ _key.QInv);
+ }
+ else
+ {
+ RsaKeyParameters _key = (RsaKeyParameters) privateKey;
+
+ keyStruct = new RsaPrivateKeyStructure(
+ _key.Modulus,
+ BigInteger.Zero,
+ _key.Exponent,
+ BigInteger.Zero,
+ BigInteger.Zero,
+ BigInteger.Zero,
+ BigInteger.Zero,
+ BigInteger.Zero);
+ }
+
+ return new PrivateKeyInfo(algID, keyStruct.ToAsn1Object(), attributes);
+ }
+
+ if (privateKey is ECPrivateKeyParameters)
+ {
+ ECPrivateKeyParameters priv = (ECPrivateKeyParameters)privateKey;
+ DerBitString publicKey = new DerBitString(ECKeyPairGenerator.GetCorrespondingPublicKey(priv).Q.GetEncoded(false));
+
+ ECDomainParameters dp = priv.Parameters;
+ int orderBitLength = dp.N.BitLength;
+
+ AlgorithmIdentifier algID;
+ ECPrivateKeyStructure ec;
+
+ if (priv.AlgorithmName == "ECGOST3410")
+ {
+ if (priv.PublicKeyParamSet == null)
+ throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("Not a CryptoPro parameter set");
+
+ Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
+ priv.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet);
+
+ algID = new AlgorithmIdentifier(CryptoProObjectIdentifiers.GostR3410x2001, gostParams);
+
+ // TODO Do we need to pass any parameters here?
+ ec = new ECPrivateKeyStructure(orderBitLength, priv.D, publicKey, null);
+ }
+ else
+ {
+ X962Parameters x962;
+ if (priv.PublicKeyParamSet == null)
+ {
+ X9ECParameters ecP = new X9ECParameters(dp.Curve, dp.G, dp.N, dp.H, dp.GetSeed());
+ x962 = new X962Parameters(ecP);
+ }
+ else
+ {
+ x962 = new X962Parameters(priv.PublicKeyParamSet);
+ }
+
+ ec = new ECPrivateKeyStructure(orderBitLength, priv.D, publicKey, x962);
+
+ algID = new AlgorithmIdentifier(X9ObjectIdentifiers.IdECPublicKey, x962);
+ }
+
+ return new PrivateKeyInfo(algID, ec, attributes);
+ }
+
+ if (privateKey is Gost3410PrivateKeyParameters)
+ {
+ Gost3410PrivateKeyParameters _key = (Gost3410PrivateKeyParameters)privateKey;
+
+ if (_key.PublicKeyParamSet == null)
+ throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("Not a CryptoPro parameter set");
+
+ byte[] keyEnc = _key.X.ToByteArrayUnsigned();
+ byte[] keyBytes = new byte[keyEnc.Length];
+
+ for (int i = 0; i != keyBytes.Length; i++)
+ {
+ keyBytes[i] = keyEnc[keyEnc.Length - 1 - i]; // must be little endian
+ }
+
+ Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters(
+ _key.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet, null);
+
+ AlgorithmIdentifier algID = new AlgorithmIdentifier(
+ CryptoProObjectIdentifiers.GostR3410x94,
+ algParams.ToAsn1Object());
+
+ return new PrivateKeyInfo(algID, new DerOctetString(keyBytes), attributes);
+ }
+
+ if (privateKey is X448PrivateKeyParameters)
+ {
+ X448PrivateKeyParameters key = (X448PrivateKeyParameters)privateKey;
+
+ return new PrivateKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_X448),
+ new DerOctetString(key.GetEncoded()), attributes, key.GeneratePublicKey().GetEncoded());
+ }
+
+ if (privateKey is X25519PrivateKeyParameters)
+ {
+ X25519PrivateKeyParameters key = (X25519PrivateKeyParameters)privateKey;
+
+ return new PrivateKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_X25519),
+ new DerOctetString(key.GetEncoded()), attributes, key.GeneratePublicKey().GetEncoded());
+ }
+
+ if (privateKey is Ed448PrivateKeyParameters)
+ {
+ Ed448PrivateKeyParameters key = (Ed448PrivateKeyParameters)privateKey;
+
+ return new PrivateKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed448),
+ new DerOctetString(key.GetEncoded()), attributes, key.GeneratePublicKey().GetEncoded());
+ }
+
+ if (privateKey is Ed25519PrivateKeyParameters)
+ {
+ Ed25519PrivateKeyParameters key = (Ed25519PrivateKeyParameters)privateKey;
+
+ return new PrivateKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed25519),
+ new DerOctetString(key.GetEncoded()), attributes, key.GeneratePublicKey().GetEncoded());
+ }
+
+ throw new ArgumentException("Class provided is not convertible: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(privateKey));
+ }
+
+ public static PrivateKeyInfo CreatePrivateKeyInfo(
+ char[] passPhrase,
+ EncryptedPrivateKeyInfo encInfo)
+ {
+ return CreatePrivateKeyInfo(passPhrase, false, encInfo);
+ }
+
+ public static PrivateKeyInfo CreatePrivateKeyInfo(
+ char[] passPhrase,
+ bool wrongPkcs12Zero,
+ EncryptedPrivateKeyInfo encInfo)
+ {
+ AlgorithmIdentifier algID = encInfo.EncryptionAlgorithm;
+
+ IBufferedCipher cipher = PbeUtilities.CreateEngine(algID) as IBufferedCipher;
+ if (cipher == null)
+ throw new Exception("Unknown encryption algorithm: " + algID.Algorithm);
+
+ ICipherParameters cipherParameters = PbeUtilities.GenerateCipherParameters(
+ algID, passPhrase, wrongPkcs12Zero);
+ cipher.Init(false, cipherParameters);
+ byte[] keyBytes = cipher.DoFinal(encInfo.GetEncryptedData());
+
+ return PrivateKeyInfo.GetInstance(keyBytes);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/PrivateKeyInfoFactory.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/PrivateKeyInfoFactory.cs.meta
new file mode 100644
index 00000000..d1230885
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/PrivateKeyInfoFactory.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: da0b98ec65ab9bd4bae18ff7fbf50ed5
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/X509CertificateEntry.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/X509CertificateEntry.cs
new file mode 100644
index 00000000..f9b71e7f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/X509CertificateEntry.cs
@@ -0,0 +1,64 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs
+{
+ public class X509CertificateEntry
+ : Pkcs12Entry
+ {
+ private readonly X509Certificate cert;
+
+ public X509CertificateEntry(
+ X509Certificate cert)
+ : base(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable())
+ {
+ this.cert = cert;
+ }
+
+#if !(SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Obsolete]
+ public X509CertificateEntry(
+ X509Certificate cert,
+ Hashtable attributes)
+ : base(attributes)
+ {
+ this.cert = cert;
+ }
+#endif
+
+ public X509CertificateEntry(
+ X509Certificate cert,
+ IDictionary attributes)
+ : base(attributes)
+ {
+ this.cert = cert;
+ }
+
+ public X509Certificate Certificate
+ {
+ get { return this.cert; }
+ }
+
+ public override bool Equals(object obj)
+ {
+ X509CertificateEntry other = obj as X509CertificateEntry;
+
+ if (other == null)
+ return false;
+
+ return cert.Equals(other.cert);
+ }
+
+ public override int GetHashCode()
+ {
+ return ~cert.GetHashCode();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/X509CertificateEntry.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/X509CertificateEntry.cs.meta
new file mode 100644
index 00000000..d89466d6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkcs/X509CertificateEntry.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: b0cf80bddefc53c47951df6aac435e62
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix.meta
new file mode 100644
index 00000000..f949ee78
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix.meta
@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: a5512fac3c819e1408d5495e0b9d5eb9
+folderAsset: yes
+timeCreated: 1547039641
+licenseType: Store
+DefaultImporter:
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/CertStatus.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/CertStatus.cs
new file mode 100644
index 00000000..13c88d46
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/CertStatus.cs
@@ -0,0 +1,39 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Date;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix
+{
+ public class CertStatus
+ {
+ public const int Unrevoked = 11;
+
+ public const int Undetermined = 12;
+
+ private int status = Unrevoked;
+
+ DateTimeObject revocationDate = null;
+
+ ///
+ /// Returns the revocationDate.
+ ///
+ public DateTimeObject RevocationDate
+ {
+ get { return revocationDate; }
+ set { this.revocationDate = value; }
+ }
+
+ ///
+ /// Returns the certStatus.
+ ///
+ public int Status
+ {
+ get { return status; }
+ set { this.status = value; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/CertStatus.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/CertStatus.cs.meta
new file mode 100644
index 00000000..2c281262
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/CertStatus.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 12be79f326e3a844f80690ca3213a20a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixAttrCertChecker.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixAttrCertChecker.cs
new file mode 100644
index 00000000..71cc3cb9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixAttrCertChecker.cs
@@ -0,0 +1,61 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix
+{
+ public abstract class PkixAttrCertChecker
+ {
+ /**
+ * Returns an immutable Set of X.509 attribute certificate
+ * extensions that this PkixAttrCertChecker supports or
+ * null if no extensions are supported.
+ *
+ * Each element of the set is a String representing the
+ * Object Identifier (OID) of the X.509 extension that is supported.
+ *
+ *
+ * All X.509 attribute certificate extensions that a
+ * PkixAttrCertChecker might possibly be able to process
+ * should be included in the set.
+ *
+ *
+ * @return an immutable Set of X.509 extension OIDs (in
+ * String format) supported by this
+ * PkixAttrCertChecker, or null if no
+ * extensions are supported
+ */
+ public abstract ISet GetSupportedExtensions();
+
+ /**
+ * Performs checks on the specified attribute certificate. Every handled
+ * extension is rmeoved from the unresolvedCritExts
+ * collection.
+ *
+ * @param attrCert The attribute certificate to be checked.
+ * @param certPath The certificate path which belongs to the attribute
+ * certificate issuer public key certificate.
+ * @param holderCertPath The certificate path which belongs to the holder
+ * certificate.
+ * @param unresolvedCritExts a Collection of OID strings
+ * representing the current set of unresolved critical extensions
+ * @throws CertPathValidatorException if the specified attribute certificate
+ * does not pass the check.
+ */
+ public abstract void Check(IX509AttributeCertificate attrCert, PkixCertPath certPath,
+ PkixCertPath holderCertPath, ICollection unresolvedCritExts);
+
+ /**
+ * Returns a clone of this object.
+ *
+ * @return a copy of this PkixAttrCertChecker
+ */
+ public abstract PkixAttrCertChecker Clone();
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixAttrCertChecker.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixAttrCertChecker.cs.meta
new file mode 100644
index 00000000..e7b3ae9a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixAttrCertChecker.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 55a8146ee5b463942b785a1ef6c9b129
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixAttrCertPathBuilder.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixAttrCertPathBuilder.cs
new file mode 100644
index 00000000..b5d834b7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixAttrCertPathBuilder.cs
@@ -0,0 +1,219 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix
+{
+ public class PkixAttrCertPathBuilder
+ {
+ /**
+ * Build and validate a CertPath using the given parameter.
+ *
+ * @param params PKIXBuilderParameters object containing all information to
+ * build the CertPath
+ */
+ public virtual PkixCertPathBuilderResult Build(
+ PkixBuilderParameters pkixParams)
+ {
+ // search target certificates
+
+ IX509Selector certSelect = pkixParams.GetTargetConstraints();
+ if (!(certSelect is X509AttrCertStoreSelector))
+ {
+ throw new PkixCertPathBuilderException(
+ "TargetConstraints must be an instance of "
+ + typeof(X509AttrCertStoreSelector).FullName
+ + " for "
+ + typeof(PkixAttrCertPathBuilder).FullName + " class.");
+ }
+
+ ICollection targets;
+ try
+ {
+ targets = PkixCertPathValidatorUtilities.FindCertificates(
+ (X509AttrCertStoreSelector)certSelect, pkixParams.GetStores());
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathBuilderException("Error finding target attribute certificate.", e);
+ }
+
+ if (targets.Count == 0)
+ {
+ throw new PkixCertPathBuilderException(
+ "No attribute certificate found matching targetContraints.");
+ }
+
+ PkixCertPathBuilderResult result = null;
+
+ // check all potential target certificates
+ foreach (IX509AttributeCertificate cert in targets)
+ {
+ X509CertStoreSelector selector = new X509CertStoreSelector();
+ X509Name[] principals = cert.Issuer.GetPrincipals();
+ ISet issuers = new HashSet();
+ for (int i = 0; i < principals.Length; i++)
+ {
+ try
+ {
+ selector.Subject = principals[i];
+
+ issuers.AddAll(PkixCertPathValidatorUtilities.FindCertificates(selector, pkixParams.GetStores()));
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathBuilderException(
+ "Public key certificate for attribute certificate cannot be searched.",
+ e);
+ }
+ }
+
+ if (issuers.IsEmpty)
+ throw new PkixCertPathBuilderException("Public key certificate for attribute certificate cannot be found.");
+
+ IList certPathList = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+
+ foreach (X509Certificate issuer in issuers)
+ {
+ result = Build(cert, issuer, pkixParams, certPathList);
+
+ if (result != null)
+ break;
+ }
+
+ if (result != null)
+ break;
+ }
+
+ if (result == null && certPathException != null)
+ {
+ throw new PkixCertPathBuilderException(
+ "Possible certificate chain could not be validated.",
+ certPathException);
+ }
+
+ if (result == null && certPathException == null)
+ {
+ throw new PkixCertPathBuilderException(
+ "Unable to find certificate chain.");
+ }
+
+ return result;
+ }
+
+ private Exception certPathException;
+
+ private PkixCertPathBuilderResult Build(
+ IX509AttributeCertificate attrCert,
+ X509Certificate tbvCert,
+ PkixBuilderParameters pkixParams,
+ IList tbvPath)
+ {
+ // If tbvCert is readily present in tbvPath, it indicates having run
+ // into a cycle in the
+ // PKI graph.
+ if (tbvPath.Contains(tbvCert))
+ return null;
+
+ // step out, the certificate is not allowed to appear in a certification
+ // chain
+ if (pkixParams.GetExcludedCerts().Contains(tbvCert))
+ return null;
+
+ // test if certificate path exceeds maximum length
+ if (pkixParams.MaxPathLength != -1)
+ {
+ if (tbvPath.Count - 1 > pkixParams.MaxPathLength)
+ return null;
+ }
+
+ tbvPath.Add(tbvCert);
+
+ PkixCertPathBuilderResult builderResult = null;
+
+// X509CertificateParser certParser = new X509CertificateParser();
+ PkixAttrCertPathValidator validator = new PkixAttrCertPathValidator();
+
+ try
+ {
+ // check whether the issuer of is a TrustAnchor
+ if (PkixCertPathValidatorUtilities.IsIssuerTrustAnchor(tbvCert, pkixParams.GetTrustAnchors()))
+ {
+ PkixCertPath certPath = new PkixCertPath(tbvPath);
+ PkixCertPathValidatorResult result;
+
+ try
+ {
+ result = validator.Validate(certPath, pkixParams);
+ }
+ catch (Exception e)
+ {
+ throw new Exception("Certification path could not be validated.", e);
+ }
+
+ return new PkixCertPathBuilderResult(certPath, result.TrustAnchor,
+ result.PolicyTree, result.SubjectPublicKey);
+ }
+ else
+ {
+ // add additional X.509 stores from locations in certificate
+ try
+ {
+ PkixCertPathValidatorUtilities.AddAdditionalStoresFromAltNames(tbvCert, pkixParams);
+ }
+ catch (CertificateParsingException e)
+ {
+ throw new Exception("No additional X.509 stores can be added from certificate locations.", e);
+ }
+
+ // try to get the issuer certificate from one of the stores
+ ISet issuers = new HashSet();
+ try
+ {
+ issuers.AddAll(PkixCertPathValidatorUtilities.FindIssuerCerts(tbvCert, pkixParams));
+ }
+ catch (Exception e)
+ {
+ throw new Exception("Cannot find issuer certificate for certificate in certification path.", e);
+ }
+
+ if (issuers.IsEmpty)
+ throw new Exception("No issuer certificate for certificate in certification path found.");
+
+ foreach (X509Certificate issuer in issuers)
+ {
+ // if untrusted self signed certificate continue
+ if (PkixCertPathValidatorUtilities.IsSelfIssued(issuer))
+ continue;
+
+ builderResult = Build(attrCert, issuer, pkixParams, tbvPath);
+
+ if (builderResult != null)
+ break;
+ }
+ }
+ }
+ catch (Exception e)
+ {
+ certPathException = new Exception("No valid certification path could be build.", e);
+ }
+
+ if (builderResult == null)
+ {
+ tbvPath.Remove(tbvCert);
+ }
+
+ return builderResult;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixAttrCertPathBuilder.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixAttrCertPathBuilder.cs.meta
new file mode 100644
index 00000000..9bcbbb77
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixAttrCertPathBuilder.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ecee7bdcfcd47514897052237429c5fa
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixAttrCertPathValidator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixAttrCertPathValidator.cs
new file mode 100644
index 00000000..4e91f63f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixAttrCertPathValidator.cs
@@ -0,0 +1,80 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix
+{
+ /**
+ * CertPathValidatorSpi implementation for X.509 Attribute Certificates la RFC 3281.
+ *
+ * @see org.bouncycastle.x509.ExtendedPkixParameters
+ */
+ public class PkixAttrCertPathValidator
+ // extends CertPathValidatorSpi
+ {
+ /**
+ * Validates an attribute certificate with the given certificate path.
+ *
+ *
+ * params must be an instance of
+ * ExtendedPkixParameters.
+ *
+ * The target constraints in the params must be an
+ * X509AttrCertStoreSelector with at least the attribute
+ * certificate criterion set. Obey that also target informations may be
+ * necessary to correctly validate this attribute certificate.
+ *
+ * The attribute certificate issuer must be added to the trusted attribute
+ * issuers with {@link ExtendedPkixParameters#setTrustedACIssuers(Set)}.
+ *
+ * @param certPath The certificate path which belongs to the attribute
+ * certificate issuer public key certificate.
+ * @param params The PKIX parameters.
+ * @return A PKIXCertPathValidatorResult of the result of
+ * validating the certPath.
+ * @throws InvalidAlgorithmParameterException if params is
+ * inappropriate for this validator.
+ * @throws CertPathValidatorException if the verification fails.
+ */
+ public virtual PkixCertPathValidatorResult Validate(
+ PkixCertPath certPath,
+ PkixParameters pkixParams)
+ {
+ IX509Selector certSelect = pkixParams.GetTargetConstraints();
+ if (!(certSelect is X509AttrCertStoreSelector))
+ {
+ throw new ArgumentException(
+ "TargetConstraints must be an instance of " + typeof(X509AttrCertStoreSelector).FullName,
+ "pkixParams");
+ }
+ IX509AttributeCertificate attrCert = ((X509AttrCertStoreSelector) certSelect).AttributeCert;
+
+ PkixCertPath holderCertPath = Rfc3281CertPathUtilities.ProcessAttrCert1(attrCert, pkixParams);
+ PkixCertPathValidatorResult result = Rfc3281CertPathUtilities.ProcessAttrCert2(certPath, pkixParams);
+ X509Certificate issuerCert = (X509Certificate)certPath.Certificates[0];
+ Rfc3281CertPathUtilities.ProcessAttrCert3(issuerCert, pkixParams);
+ Rfc3281CertPathUtilities.ProcessAttrCert4(issuerCert, pkixParams);
+ Rfc3281CertPathUtilities.ProcessAttrCert5(attrCert, pkixParams);
+ // 6 already done in X509AttrCertStoreSelector
+ Rfc3281CertPathUtilities.ProcessAttrCert7(attrCert, certPath, holderCertPath, pkixParams);
+ Rfc3281CertPathUtilities.AdditionalChecks(attrCert, pkixParams);
+ DateTime date;
+ try
+ {
+ date = PkixCertPathValidatorUtilities.GetValidCertDateFromValidityModel(pkixParams, null, -1);
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathValidatorException(
+ "Could not get validity date from attribute certificate.", e);
+ }
+ Rfc3281CertPathUtilities.CheckCrls(attrCert, pkixParams, issuerCert, date, certPath.Certificates);
+ return result;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixAttrCertPathValidator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixAttrCertPathValidator.cs.meta
new file mode 100644
index 00000000..f59abde0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixAttrCertPathValidator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 85b76d91e2248a64191df671fb900d8b
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixBuilderParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixBuilderParameters.cs
new file mode 100644
index 00000000..8a0ab7c5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixBuilderParameters.cs
@@ -0,0 +1,144 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix
+{
+ ///
+ /// Summary description for PkixBuilderParameters.
+ ///
+ public class PkixBuilderParameters
+ : PkixParameters
+ {
+ private int maxPathLength = 5;
+
+ private ISet excludedCerts = new HashSet();
+
+ /**
+ * Returns an instance of PkixBuilderParameters.
+ *
+ * This method can be used to get a copy from other
+ * PKIXBuilderParameters, PKIXParameters,
+ * and ExtendedPKIXParameters instances.
+ *
+ *
+ * @param pkixParams The PKIX parameters to create a copy of.
+ * @return An PkixBuilderParameters instance.
+ */
+ public static PkixBuilderParameters GetInstance(
+ PkixParameters pkixParams)
+ {
+ PkixBuilderParameters parameters = new PkixBuilderParameters(
+ pkixParams.GetTrustAnchors(),
+ new X509CertStoreSelector(pkixParams.GetTargetCertConstraints()));
+ parameters.SetParams(pkixParams);
+ return parameters;
+ }
+
+ public PkixBuilderParameters(
+ ISet trustAnchors,
+ IX509Selector targetConstraints)
+ : base(trustAnchors)
+ {
+ SetTargetCertConstraints(targetConstraints);
+ }
+
+ public virtual int MaxPathLength
+ {
+ get { return maxPathLength; }
+ set
+ {
+ if (value < -1)
+ {
+ throw new InvalidParameterException(
+ "The maximum path length parameter can not be less than -1.");
+ }
+ this.maxPathLength = value;
+ }
+ }
+
+ ///
+ /// Excluded certificates are not used for building a certification path.
+ ///
+ /// the excluded certificates.
+ public virtual ISet GetExcludedCerts()
+ {
+ return new HashSet(excludedCerts);
+ }
+
+ ///
+ /// Sets the excluded certificates which are not used for building a
+ /// certification path. If the ISet is null an
+ /// empty set is assumed.
+ ///
+ ///
+ /// The given set is cloned to protect it against subsequent modifications.
+ ///
+ /// The excluded certificates to set.
+ public virtual void SetExcludedCerts(
+ ISet excludedCerts)
+ {
+ if (excludedCerts == null)
+ {
+ excludedCerts = new HashSet();
+ }
+ else
+ {
+ this.excludedCerts = new HashSet(excludedCerts);
+ }
+ }
+
+ /**
+ * Can alse handle ExtendedPKIXBuilderParameters and
+ * PKIXBuilderParameters.
+ *
+ * @param params Parameters to set.
+ * @see org.bouncycastle.x509.ExtendedPKIXParameters#setParams(java.security.cert.PKIXParameters)
+ */
+ protected override void SetParams(
+ PkixParameters parameters)
+ {
+ base.SetParams(parameters);
+ if (parameters is PkixBuilderParameters)
+ {
+ PkixBuilderParameters _params = (PkixBuilderParameters) parameters;
+ maxPathLength = _params.maxPathLength;
+ excludedCerts = new HashSet(_params.excludedCerts);
+ }
+ }
+
+ /**
+ * Makes a copy of this PKIXParameters object. Changes to the
+ * copy will not affect the original and vice versa.
+ *
+ * @return a copy of this PKIXParameters object
+ */
+ public override object Clone()
+ {
+ PkixBuilderParameters parameters = new PkixBuilderParameters(
+ GetTrustAnchors(), GetTargetCertConstraints());
+ parameters.SetParams(this);
+ return parameters;
+ }
+
+ public override string ToString()
+ {
+ string nl = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.NewLine;
+ StringBuilder s = new StringBuilder();
+ s.Append("PkixBuilderParameters [" + nl);
+ s.Append(base.ToString());
+ s.Append(" Maximum Path Length: ");
+ s.Append(MaxPathLength);
+ s.Append(nl + "]" + nl);
+ return s.ToString();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixBuilderParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixBuilderParameters.cs.meta
new file mode 100644
index 00000000..6f51b544
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixBuilderParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 4976f361ba4e5544681c44a8ec8d928c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPath.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPath.cs
new file mode 100644
index 00000000..c1f2787f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPath.cs
@@ -0,0 +1,464 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Cms;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.OpenSsl;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix
+{
+ /**
+ * An immutable sequence of certificates (a certification path).
+ *
+ * This is an abstract class that defines the methods common to all CertPaths.
+ * Subclasses can handle different kinds of certificates (X.509, PGP, etc.).
+ *
+ * All CertPath objects have a type, a list of Certificates, and one or more
+ * supported encodings. Because the CertPath class is immutable, a CertPath
+ * cannot change in any externally visible way after being constructed. This
+ * stipulation applies to all public fields and methods of this class and any
+ * added or overridden by subclasses.
+ *
+ * The type is a string that identifies the type of Certificates in the
+ * certification path. For each certificate cert in a certification path
+ * certPath, cert.getType().equals(certPath.getType()) must be true.
+ *
+ * The list of Certificates is an ordered List of zero or more Certificates.
+ * This List and all of the Certificates contained in it must be immutable.
+ *
+ * Each CertPath object must support one or more encodings so that the object
+ * can be translated into a byte array for storage or transmission to other
+ * parties. Preferably, these encodings should be well-documented standards
+ * (such as PKCS#7). One of the encodings supported by a CertPath is considered
+ * the default encoding. This encoding is used if no encoding is explicitly
+ * requested (for the {@link #getEncoded()} method, for instance).
+ *
+ * All CertPath objects are also Serializable. CertPath objects are resolved
+ * into an alternate {@link CertPathRep} object during serialization. This
+ * allows a CertPath object to be serialized into an equivalent representation
+ * regardless of its underlying implementation.
+ *
+ * CertPath objects can be created with a CertificateFactory or they can be
+ * returned by other classes, such as a CertPathBuilder.
+ *
+ * By convention, X.509 CertPaths (consisting of X509Certificates), are ordered
+ * starting with the target certificate and ending with a certificate issued by
+ * the trust anchor. That is, the issuer of one certificate is the subject of
+ * the following one. The certificate representing the
+ * {@link TrustAnchor TrustAnchor} should not be included in the certification
+ * path. Unvalidated X.509 CertPaths may not follow these conventions. PKIX
+ * CertPathValidators will detect any departure from these conventions that
+ * cause the certification path to be invalid and throw a
+ * CertPathValidatorException.
+ *
+ * Concurrent Access
+ *
+ * All CertPath objects must be thread-safe. That is, multiple threads may
+ * concurrently invoke the methods defined in this class on a single CertPath
+ * object (or more than one) with no ill effects. This is also true for the List
+ * returned by CertPath.getCertificates.
+ *
+ * Requiring CertPath objects to be immutable and thread-safe allows them to be
+ * passed around to various pieces of code without worrying about coordinating
+ * access. Providing this thread-safety is generally not difficult, since the
+ * CertPath and List objects in question are immutable.
+ *
+ * @see CertificateFactory
+ * @see CertPathBuilder
+ */
+ ///
+ /// CertPath implementation for X.509 certificates.
+ ///
+ public class PkixCertPath
+// : CertPath
+ {
+ internal static readonly IList certPathEncodings;
+
+ static PkixCertPath()
+ {
+ IList encodings = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ encodings.Add("PkiPath");
+ encodings.Add("PEM");
+ encodings.Add("PKCS7");
+ certPathEncodings = CollectionUtilities.ReadOnly(encodings);
+ }
+
+ private readonly IList certificates;
+
+ /**
+ * @param certs
+ */
+ private static IList SortCerts(
+ IList certs)
+ {
+ if (certs.Count < 2)
+ return certs;
+
+ X509Name issuer = ((X509Certificate)certs[0]).IssuerDN;
+ bool okay = true;
+
+ for (int i = 1; i != certs.Count; i++)
+ {
+ X509Certificate cert = (X509Certificate)certs[i];
+
+ if (issuer.Equivalent(cert.SubjectDN, true))
+ {
+ issuer = ((X509Certificate)certs[i]).IssuerDN;
+ }
+ else
+ {
+ okay = false;
+ break;
+ }
+ }
+
+ if (okay)
+ return certs;
+
+ // find end-entity cert
+ IList retList = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(certs.Count);
+ IList orig = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(certs);
+
+ for (int i = 0; i < certs.Count; i++)
+ {
+ X509Certificate cert = (X509Certificate)certs[i];
+ bool found = false;
+
+ X509Name subject = cert.SubjectDN;
+ foreach (X509Certificate c in certs)
+ {
+ if (c.IssuerDN.Equivalent(subject, true))
+ {
+ found = true;
+ break;
+ }
+ }
+
+ if (!found)
+ {
+ retList.Add(cert);
+ certs.RemoveAt(i);
+ }
+ }
+
+ // can only have one end entity cert - something's wrong, give up.
+ if (retList.Count > 1)
+ return orig;
+
+ for (int i = 0; i != retList.Count; i++)
+ {
+ issuer = ((X509Certificate)retList[i]).IssuerDN;
+
+ for (int j = 0; j < certs.Count; j++)
+ {
+ X509Certificate c = (X509Certificate)certs[j];
+ if (issuer.Equivalent(c.SubjectDN, true))
+ {
+ retList.Add(c);
+ certs.RemoveAt(j);
+ break;
+ }
+ }
+ }
+
+ // make sure all certificates are accounted for.
+ if (certs.Count > 0)
+ return orig;
+
+ return retList;
+ }
+
+ /**
+ * Creates a CertPath of the specified type.
+ * This constructor is protected because most users should use
+ * a CertificateFactory to create CertPaths.
+ * @param type the standard name of the type of Certificatesin this path
+ **/
+ public PkixCertPath(
+ ICollection certificates)
+// : base("X.509")
+ {
+ this.certificates = SortCerts(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(certificates));
+ }
+
+ public PkixCertPath(
+ Stream inStream)
+ : this(inStream, "PkiPath")
+ {
+ }
+
+ /**
+ * Creates a CertPath of the specified type.
+ * This constructor is protected because most users should use
+ * a CertificateFactory to create CertPaths.
+ *
+ * @param type the standard name of the type of Certificatesin this path
+ **/
+ public PkixCertPath(
+ Stream inStream,
+ string encoding)
+// : base("X.509")
+ {
+ string upper = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(encoding);
+
+ IList certs;
+ try
+ {
+ if (upper.Equals(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant("PkiPath")))
+ {
+ Asn1InputStream derInStream = new Asn1InputStream(inStream);
+ Asn1Object derObject = derInStream.ReadObject();
+ if (!(derObject is Asn1Sequence))
+ {
+ throw new CertificateException(
+ "input stream does not contain a ASN1 SEQUENCE while reading PkiPath encoded data to load CertPath");
+ }
+
+ certs = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+
+ foreach (Asn1Encodable ae in (Asn1Sequence)derObject)
+ {
+ byte[] derBytes = ae.GetEncoded(Asn1Encodable.Der);
+ Stream certInStream = new MemoryStream(derBytes, false);
+
+ // TODO Is inserting at the front important (list will be sorted later anyway)?
+ certs.Insert(0, new X509CertificateParser().ReadCertificate(certInStream));
+ }
+ }
+ else if (upper.Equals("PKCS7") || upper.Equals("PEM"))
+ {
+ certs = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(new X509CertificateParser().ReadCertificates(inStream));
+ }
+ else
+ {
+ throw new CertificateException("unsupported encoding: " + encoding);
+ }
+ }
+ catch (IOException ex)
+ {
+ throw new CertificateException(
+ "IOException throw while decoding CertPath:\n"
+ + ex.ToString());
+ }
+
+ this.certificates = SortCerts(certs);
+ }
+
+ /**
+ * Returns an iteration of the encodings supported by this
+ * certification path, with the default encoding
+ * first. Attempts to modify the returned Iterator via its
+ * remove method result in an UnsupportedOperationException.
+ *
+ * @return an Iterator over the names of the supported encodings (as Strings)
+ **/
+ public virtual IEnumerable Encodings
+ {
+ get { return new EnumerableProxy(certPathEncodings); }
+ }
+
+ /**
+ * Compares this certification path for equality with the specified object.
+ * Two CertPaths are equal if and only if their types are equal and their
+ * certificate Lists (and by implication the Certificates in those Lists)
+ * are equal. A CertPath is never equal to an object that is not a CertPath.
+ *
+ * This algorithm is implemented by this method. If it is overridden, the
+ * behavior specified here must be maintained.
+ *
+ * @param other
+ * the object to test for equality with this certification path
+ *
+ * @return true if the specified object is equal to this certification path,
+ * false otherwise
+ *
+ * @see Object#hashCode() Object.hashCode()
+ */
+ public override bool Equals(
+ object obj)
+ {
+ if (this == obj)
+ return true;
+
+ PkixCertPath other = obj as PkixCertPath;
+ if (other == null)
+ return false;
+
+// if (!this.Type.Equals(other.Type))
+// return false;
+
+ //return this.Certificates.Equals(other.Certificates);
+
+ // TODO Extract this to a utility class
+ IList thisCerts = this.Certificates;
+ IList otherCerts = other.Certificates;
+
+ if (thisCerts.Count != otherCerts.Count)
+ return false;
+
+ IEnumerator e1 = thisCerts.GetEnumerator();
+ IEnumerator e2 = thisCerts.GetEnumerator();
+
+ while (e1.MoveNext())
+ {
+ e2.MoveNext();
+
+ if (!BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(e1.Current, e2.Current))
+ return false;
+ }
+
+ return true;
+ }
+
+ public override int GetHashCode()
+ {
+ // FIXME?
+ return this.Certificates.GetHashCode();
+ }
+
+ /**
+ * Returns the encoded form of this certification path, using
+ * the default encoding.
+ *
+ * @return the encoded bytes
+ * @exception CertificateEncodingException if an encoding error occurs
+ **/
+ public virtual byte[] GetEncoded()
+ {
+ foreach (object enc in Encodings)
+ {
+ if (enc is string)
+ {
+ return GetEncoded((string)enc);
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns the encoded form of this certification path, using
+ * the specified encoding.
+ *
+ * @param encoding the name of the encoding to use
+ * @return the encoded bytes
+ * @exception CertificateEncodingException if an encoding error
+ * occurs or the encoding requested is not supported
+ *
+ */
+ public virtual byte[] GetEncoded(
+ string encoding)
+ {
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(encoding, "PkiPath"))
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector();
+
+ for (int i = certificates.Count - 1; i >= 0; i--)
+ {
+ v.Add(ToAsn1Object((X509Certificate) certificates[i]));
+ }
+
+ return ToDerEncoded(new DerSequence(v));
+ }
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(encoding, "PKCS7"))
+ {
+ Asn1.Pkcs.ContentInfo encInfo = new Asn1.Pkcs.ContentInfo(
+ PkcsObjectIdentifiers.Data, null);
+
+ Asn1EncodableVector v = new Asn1EncodableVector();
+ for (int i = 0; i != certificates.Count; i++)
+ {
+ v.Add(ToAsn1Object((X509Certificate)certificates[i]));
+ }
+
+ Asn1.Pkcs.SignedData sd = new Asn1.Pkcs.SignedData(
+ new DerInteger(1),
+ new DerSet(),
+ encInfo,
+ new DerSet(v),
+ null,
+ new DerSet());
+
+ return ToDerEncoded(new Asn1.Pkcs.ContentInfo(PkcsObjectIdentifiers.SignedData, sd));
+ }
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(encoding, "PEM"))
+ {
+ MemoryStream bOut = new MemoryStream();
+ PemWriter pWrt = new PemWriter(new StreamWriter(bOut));
+
+ try
+ {
+ for (int i = 0; i != certificates.Count; i++)
+ {
+ pWrt.WriteObject(certificates[i]);
+ }
+
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(pWrt.Writer);
+ }
+ catch (Exception)
+ {
+ throw new CertificateEncodingException("can't encode certificate for PEM encoded path");
+ }
+
+ return bOut.ToArray();
+ }
+ else
+ {
+ throw new CertificateEncodingException("unsupported encoding: " + encoding);
+ }
+ }
+
+ ///
+ /// Returns the list of certificates in this certification
+ /// path.
+ ///
+ public virtual IList Certificates
+ {
+ get { return CollectionUtilities.ReadOnly(certificates); }
+ }
+
+ /**
+ * Return a DERObject containing the encoded certificate.
+ *
+ * @param cert the X509Certificate object to be encoded
+ *
+ * @return the DERObject
+ **/
+ private Asn1Object ToAsn1Object(
+ X509Certificate cert)
+ {
+ try
+ {
+ return Asn1Object.FromByteArray(cert.GetEncoded());
+ }
+ catch (Exception e)
+ {
+ throw new CertificateEncodingException("Exception while encoding certificate", e);
+ }
+ }
+
+ private byte[] ToDerEncoded(Asn1Encodable obj)
+ {
+ try
+ {
+ return obj.GetEncoded(Asn1Encodable.Der);
+ }
+ catch (IOException e)
+ {
+ throw new CertificateEncodingException("Exception thrown", e);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPath.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPath.cs.meta
new file mode 100644
index 00000000..32468725
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPath.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 565bdea7eb2a46d40ad29b81bc563819
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathBuilder.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathBuilder.cs
new file mode 100644
index 00000000..58331568
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathBuilder.cs
@@ -0,0 +1,209 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.IsisMtt;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X500;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix
+{
+ /**
+ * Implements the PKIX CertPathBuilding algorithm for BouncyCastle.
+ *
+ * @see CertPathBuilderSpi
+ */
+ public class PkixCertPathBuilder
+ // : CertPathBuilderSpi
+ {
+ /**
+ * Build and validate a CertPath using the given parameter.
+ *
+ * @param params PKIXBuilderParameters object containing all information to
+ * build the CertPath
+ */
+ public virtual PkixCertPathBuilderResult Build(
+ PkixBuilderParameters pkixParams)
+ {
+ // search target certificates
+
+ IX509Selector certSelect = pkixParams.GetTargetCertConstraints();
+ if (!(certSelect is X509CertStoreSelector))
+ {
+ throw new PkixCertPathBuilderException(
+ "TargetConstraints must be an instance of "
+ + typeof(X509CertStoreSelector).FullName + " for "
+ + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(this) + " class.");
+ }
+
+ ISet targets = new HashSet();
+ try
+ {
+ targets.AddAll(PkixCertPathValidatorUtilities.FindCertificates((X509CertStoreSelector)certSelect, pkixParams.GetStores()));
+ // TODO Should this include an entry for pkixParams.GetAdditionalStores() too?
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathBuilderException(
+ "Error finding target certificate.", e);
+ }
+
+ if (targets.IsEmpty)
+ throw new PkixCertPathBuilderException("No certificate found matching targetContraints.");
+
+ PkixCertPathBuilderResult result = null;
+ IList certPathList = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+
+ // check all potential target certificates
+ foreach (X509Certificate cert in targets)
+ {
+ result = Build(cert, pkixParams, certPathList);
+
+ if (result != null)
+ break;
+ }
+
+ if (result == null && certPathException != null)
+ {
+ throw new PkixCertPathBuilderException(certPathException.Message, certPathException.InnerException);
+ }
+
+ if (result == null && certPathException == null)
+ {
+ throw new PkixCertPathBuilderException("Unable to find certificate chain.");
+ }
+
+ return result;
+ }
+
+ private Exception certPathException;
+
+ protected virtual PkixCertPathBuilderResult Build(
+ X509Certificate tbvCert,
+ PkixBuilderParameters pkixParams,
+ IList tbvPath)
+ {
+ // If tbvCert is readily present in tbvPath, it indicates having run
+ // into a cycle in the PKI graph.
+ if (tbvPath.Contains(tbvCert))
+ return null;
+
+ // step out, the certificate is not allowed to appear in a certification
+ // chain.
+ if (pkixParams.GetExcludedCerts().Contains(tbvCert))
+ return null;
+
+ // test if certificate path exceeds maximum length
+ if (pkixParams.MaxPathLength != -1)
+ {
+ if (tbvPath.Count - 1 > pkixParams.MaxPathLength)
+ return null;
+ }
+
+ tbvPath.Add(tbvCert);
+
+// X509CertificateParser certParser = new X509CertificateParser();
+ PkixCertPathBuilderResult builderResult = null;
+ PkixCertPathValidator validator = new PkixCertPathValidator();
+
+ try
+ {
+ // check whether the issuer of is a TrustAnchor
+ if (PkixCertPathValidatorUtilities.IsIssuerTrustAnchor(tbvCert, pkixParams.GetTrustAnchors()))
+ {
+ // exception message from possibly later tried certification
+ // chains
+ PkixCertPath certPath = null;
+ try
+ {
+ certPath = new PkixCertPath(tbvPath);
+ }
+ catch (Exception e)
+ {
+ throw new Exception(
+ "Certification path could not be constructed from certificate list.",
+ e);
+ }
+
+ PkixCertPathValidatorResult result = null;
+ try
+ {
+ result = (PkixCertPathValidatorResult)validator.Validate(
+ certPath, pkixParams);
+ }
+ catch (Exception e)
+ {
+ throw new Exception(
+ "Certification path could not be validated.", e);
+ }
+
+ return new PkixCertPathBuilderResult(certPath, result.TrustAnchor,
+ result.PolicyTree, result.SubjectPublicKey);
+ }
+ else
+ {
+ // add additional X.509 stores from locations in certificate
+ try
+ {
+ PkixCertPathValidatorUtilities.AddAdditionalStoresFromAltNames(
+ tbvCert, pkixParams);
+ }
+ catch (CertificateParsingException e)
+ {
+ throw new Exception(
+ "No additiontal X.509 stores can be added from certificate locations.",
+ e);
+ }
+
+ // try to get the issuer certificate from one of the stores
+ HashSet issuers = new HashSet();
+ try
+ {
+ issuers.AddAll(PkixCertPathValidatorUtilities.FindIssuerCerts(tbvCert, pkixParams));
+ }
+ catch (Exception e)
+ {
+ throw new Exception(
+ "Cannot find issuer certificate for certificate in certification path.",
+ e);
+ }
+
+ if (issuers.IsEmpty)
+ throw new Exception("No issuer certificate for certificate in certification path found.");
+
+ foreach (X509Certificate issuer in issuers)
+ {
+ builderResult = Build(issuer, pkixParams, tbvPath);
+
+ if (builderResult != null)
+ break;
+ }
+ }
+ }
+ catch (Exception e)
+ {
+ certPathException = e;
+ }
+
+ if (builderResult == null)
+ {
+ tbvPath.Remove(tbvCert);
+ }
+
+ return builderResult;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathBuilder.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathBuilder.cs.meta
new file mode 100644
index 00000000..fa3a861a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathBuilder.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 3b141fdaa90999d4f848152c584ce4e1
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathBuilderException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathBuilderException.cs
new file mode 100644
index 00000000..6bf59052
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathBuilderException.cs
@@ -0,0 +1,26 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix
+{
+ ///
+ /// Summary description for PkixCertPathBuilderException.
+ ///
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class PkixCertPathBuilderException : GeneralSecurityException
+ {
+ public PkixCertPathBuilderException() : base() { }
+
+ public PkixCertPathBuilderException(string message) : base(message) { }
+
+ public PkixCertPathBuilderException(string message, Exception exception) : base(message, exception) { }
+
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathBuilderException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathBuilderException.cs.meta
new file mode 100644
index 00000000..e719ad6a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathBuilderException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 25a59fe00cb35544dbfaae6c24af2f68
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathBuilderResult.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathBuilderResult.cs
new file mode 100644
index 00000000..5e93dff0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathBuilderResult.cs
@@ -0,0 +1,49 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix
+{
+ ///
+ /// Summary description for PkixCertPathBuilderResult.
+ ///
+ public class PkixCertPathBuilderResult
+ : PkixCertPathValidatorResult//, ICertPathBuilderResult
+ {
+ private PkixCertPath certPath;
+
+ public PkixCertPathBuilderResult(
+ PkixCertPath certPath,
+ TrustAnchor trustAnchor,
+ PkixPolicyNode policyTree,
+ AsymmetricKeyParameter subjectPublicKey)
+ : base(trustAnchor, policyTree, subjectPublicKey)
+ {
+ if (certPath == null)
+ throw new ArgumentNullException("certPath");
+
+ this.certPath = certPath;
+ }
+
+ public PkixCertPath CertPath
+ {
+ get { return certPath; }
+ }
+
+ public override string ToString()
+ {
+ StringBuilder s = new StringBuilder();
+ s.Append("SimplePKIXCertPathBuilderResult: [\n");
+ s.Append(" Certification Path: ").Append(CertPath).Append('\n');
+ s.Append(" Trust Anchor: ").Append(this.TrustAnchor.TrustedCert.IssuerDN.ToString()).Append('\n');
+ s.Append(" Subject Public Key: ").Append(this.SubjectPublicKey).Append("\n]");
+ return s.ToString();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathBuilderResult.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathBuilderResult.cs.meta
new file mode 100644
index 00000000..9df5ca33
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathBuilderResult.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 5bb663b8ed6b4c04ead1d50f1b83b3f7
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathChecker.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathChecker.cs
new file mode 100644
index 00000000..476ec4cd
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathChecker.cs
@@ -0,0 +1,103 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix
+{
+ public abstract class PkixCertPathChecker
+ {
+ protected PkixCertPathChecker()
+ {
+ }
+
+ /**
+ * Initializes the internal state of this PKIXCertPathChecker.
+ *
+ * The forward flag specifies the order that certificates
+ * will be passed to the {@link #check check} method (forward or reverse). A
+ * PKIXCertPathCheckermust support reverse checking
+ * and may support forward checking.
+ *
+ *
+ * @param forward
+ * the order that certificates are presented to the
+ * check method. If true,
+ * certificates are presented from target to most-trusted CA
+ * (forward); if false, from most-trusted CA to
+ * target (reverse).
+ * @exception CertPathValidatorException
+ * if this PKIXCertPathChecker is unable to
+ * check certificates in the specified order; it should never
+ * be thrown if the forward flag is false since reverse
+ * checking must be supported
+ */
+ public abstract void Init(bool forward);
+ //throws CertPathValidatorException;
+
+ /**
+ * Indicates if forward checking is supported. Forward checking refers to
+ * the ability of the PKIXCertPathChecker to perform its
+ * checks when certificates are presented to the check method
+ * in the forward direction (from target to most-trusted CA).
+ *
+ * @return true if forward checking is supported,
+ * false otherwise
+ */
+ public abstract bool IsForwardCheckingSupported();
+
+ /**
+ * Returns an immutable Set of X.509 certificate extensions
+ * that this PKIXCertPathChecker supports (i.e. recognizes,
+ * is able to process), or null if no extensions are
+ * supported.
+ *
+ * Each element of the set is a String representing the
+ * Object Identifier (OID) of the X.509 extension that is supported. The OID
+ * is represented by a set of nonnegative integers separated by periods.
+ *
+ * All X.509 certificate extensions that a PKIXCertPathChecker
+ * might possibly be able to process should be included in the set.
+ *
+ *
+ * @return an immutable Set of X.509 extension OIDs (in
+ * String format) supported by this
+ * PKIXCertPathChecker, or null if no
+ * extensions are supported
+ */
+ public abstract ISet GetSupportedExtensions();
+
+ /**
+ * Performs the check(s) on the specified certificate using its internal
+ * state and removes any critical extensions that it processes from the
+ * specified collection of OID strings that represent the unresolved
+ * critical extensions. The certificates are presented in the order
+ * specified by the init method.
+ *
+ * @param cert
+ * the Certificate to be checked
+ * @param unresolvedCritExts
+ * a Collection of OID strings representing the
+ * current set of unresolved critical extensions
+ * @exception CertPathValidatorException
+ * if the specified certificate does not pass the check
+ */
+ public abstract void Check(X509Certificate cert, ISet unresolvedCritExts);
+ //throws CertPathValidatorException;
+
+ /**
+ * Returns a clone of this object. Calls the Object.clone()
+ * method. All subclasses which maintain state must support and override
+ * this method, if necessary.
+ *
+ * @return a copy of this PKIXCertPathChecker
+ */
+ public virtual object Clone()
+ {
+ // TODO Check this
+ return base.MemberwiseClone();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathChecker.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathChecker.cs.meta
new file mode 100644
index 00000000..34f746c5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathChecker.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 43f01d4bd4f27a943bb693735147c260
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathValidator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathValidator.cs
new file mode 100644
index 00000000..792bc29d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathValidator.cs
@@ -0,0 +1,452 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix
+{
+ /**
+ * The Service Provider Interface (SPI)
+ * for the {@link CertPathValidator CertPathValidator} class. All
+ * CertPathValidator implementations must include a class (the
+ * SPI class) that extends this class (CertPathValidatorSpi)
+ * and implements all of its methods. In general, instances of this class
+ * should only be accessed through the CertPathValidator class.
+ * For details, see the Java Cryptography Architecture.
+ *
+ * Concurrent Access
+ *
+ * Instances of this class need not be protected against concurrent
+ * access from multiple threads. Threads that need to access a single
+ * CertPathValidatorSpi instance concurrently should synchronize
+ * amongst themselves and provide the necessary locking before calling the
+ * wrapping CertPathValidator object.
+ *
+ * However, implementations of CertPathValidatorSpi may still
+ * encounter concurrency issues, since multiple threads each
+ * manipulating a different CertPathValidatorSpi instance need not
+ * synchronize.
+ */
+ ///
+ /// CertPathValidatorSpi implementation for X.509 Certificate validation a la RFC
+ /// 3280.
+ ///
+ public class PkixCertPathValidator
+ {
+ public virtual PkixCertPathValidatorResult Validate(
+ PkixCertPath certPath,
+ PkixParameters paramsPkix)
+ {
+ if (paramsPkix.GetTrustAnchors() == null)
+ {
+ throw new ArgumentException(
+ "trustAnchors is null, this is not allowed for certification path validation.",
+ "parameters");
+ }
+
+ //
+ // 6.1.1 - inputs
+ //
+
+ //
+ // (a)
+ //
+ IList certs = certPath.Certificates;
+ int n = certs.Count;
+
+ if (certs.Count == 0)
+ throw new PkixCertPathValidatorException("Certification path is empty.", null, certPath, 0);
+
+ //
+ // (b)
+ //
+ // DateTime validDate = PkixCertPathValidatorUtilities.GetValidDate(paramsPkix);
+
+ //
+ // (c)
+ //
+ ISet userInitialPolicySet = paramsPkix.GetInitialPolicies();
+
+ //
+ // (d)
+ //
+ TrustAnchor trust;
+ try
+ {
+ trust = PkixCertPathValidatorUtilities.FindTrustAnchor(
+ (X509Certificate)certs[certs.Count - 1],
+ paramsPkix.GetTrustAnchors());
+
+ if (trust == null)
+ throw new PkixCertPathValidatorException("Trust anchor for certification path not found.", null, certPath, -1);
+
+ CheckCertificate(trust.TrustedCert);
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathValidatorException(e.Message, e.InnerException, certPath, certs.Count - 1);
+ }
+
+ //
+ // (e), (f), (g) are part of the paramsPkix object.
+ //
+ IEnumerator certIter;
+ int index = 0;
+ int i;
+ // Certificate for each interation of the validation loop
+ // Signature information for each iteration of the validation loop
+ //
+ // 6.1.2 - setup
+ //
+
+ //
+ // (a)
+ //
+ IList[] policyNodes = new IList[n + 1];
+ for (int j = 0; j < policyNodes.Length; j++)
+ {
+ policyNodes[j] = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ }
+
+ ISet policySet = new HashSet();
+
+ policySet.Add(Rfc3280CertPathUtilities.ANY_POLICY);
+
+ PkixPolicyNode validPolicyTree = new PkixPolicyNode(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(), 0, policySet, null, new HashSet(),
+ Rfc3280CertPathUtilities.ANY_POLICY, false);
+
+ policyNodes[0].Add(validPolicyTree);
+
+ //
+ // (b) and (c)
+ //
+ PkixNameConstraintValidator nameConstraintValidator = new PkixNameConstraintValidator();
+
+ // (d)
+ //
+ int explicitPolicy;
+ ISet acceptablePolicies = new HashSet();
+
+ if (paramsPkix.IsExplicitPolicyRequired)
+ {
+ explicitPolicy = 0;
+ }
+ else
+ {
+ explicitPolicy = n + 1;
+ }
+
+ //
+ // (e)
+ //
+ int inhibitAnyPolicy;
+
+ if (paramsPkix.IsAnyPolicyInhibited)
+ {
+ inhibitAnyPolicy = 0;
+ }
+ else
+ {
+ inhibitAnyPolicy = n + 1;
+ }
+
+ //
+ // (f)
+ //
+ int policyMapping;
+
+ if (paramsPkix.IsPolicyMappingInhibited)
+ {
+ policyMapping = 0;
+ }
+ else
+ {
+ policyMapping = n + 1;
+ }
+
+ //
+ // (g), (h), (i), (j)
+ //
+ AsymmetricKeyParameter workingPublicKey;
+ X509Name workingIssuerName;
+
+ X509Certificate sign = trust.TrustedCert;
+ try
+ {
+ if (sign != null)
+ {
+ workingIssuerName = sign.SubjectDN;
+ workingPublicKey = sign.GetPublicKey();
+ }
+ else
+ {
+ workingIssuerName = new X509Name(trust.CAName);
+ workingPublicKey = trust.CAPublicKey;
+ }
+ }
+ catch (ArgumentException ex)
+ {
+ throw new PkixCertPathValidatorException("Subject of trust anchor could not be (re)encoded.", ex, certPath,
+ -1);
+ }
+
+ AlgorithmIdentifier workingAlgId = null;
+ try
+ {
+ workingAlgId = PkixCertPathValidatorUtilities.GetAlgorithmIdentifier(workingPublicKey);
+ }
+ catch (PkixCertPathValidatorException e)
+ {
+ throw new PkixCertPathValidatorException(
+ "Algorithm identifier of public key of trust anchor could not be read.", e, certPath, -1);
+ }
+
+// DerObjectIdentifier workingPublicKeyAlgorithm = workingAlgId.Algorithm;
+// Asn1Encodable workingPublicKeyParameters = workingAlgId.Parameters;
+
+ //
+ // (k)
+ //
+ int maxPathLength = n;
+
+ //
+ // 6.1.3
+ //
+
+ X509CertStoreSelector certConstraints = paramsPkix.GetTargetCertConstraints();
+ if (certConstraints != null && !certConstraints.Match((X509Certificate)certs[0]))
+ {
+ throw new PkixCertPathValidatorException(
+ "Target certificate in certification path does not match targetConstraints.", null, certPath, 0);
+ }
+
+ //
+ // initialize CertPathChecker's
+ //
+ IList pathCheckers = paramsPkix.GetCertPathCheckers();
+ certIter = pathCheckers.GetEnumerator();
+
+ while (certIter.MoveNext())
+ {
+ ((PkixCertPathChecker)certIter.Current).Init(false);
+ }
+
+ X509Certificate cert = null;
+
+ for (index = certs.Count - 1; index >= 0; index--)
+ {
+ // try
+ // {
+ //
+ // i as defined in the algorithm description
+ //
+ i = n - index;
+
+ //
+ // set certificate to be checked in this round
+ // sign and workingPublicKey and workingIssuerName are set
+ // at the end of the for loop and initialized the
+ // first time from the TrustAnchor
+ //
+ cert = (X509Certificate)certs[index];
+
+ try
+ {
+ CheckCertificate(cert);
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathValidatorException(e.Message, e.InnerException, certPath, index);
+ }
+
+ //
+ // 6.1.3
+ //
+
+ Rfc3280CertPathUtilities.ProcessCertA(certPath, paramsPkix, index, workingPublicKey,
+ workingIssuerName, sign);
+
+ Rfc3280CertPathUtilities.ProcessCertBC(certPath, index, nameConstraintValidator);
+
+ validPolicyTree = Rfc3280CertPathUtilities.ProcessCertD(certPath, index,
+ acceptablePolicies, validPolicyTree, policyNodes, inhibitAnyPolicy);
+
+ validPolicyTree = Rfc3280CertPathUtilities.ProcessCertE(certPath, index, validPolicyTree);
+
+ Rfc3280CertPathUtilities.ProcessCertF(certPath, index, validPolicyTree, explicitPolicy);
+
+ //
+ // 6.1.4
+ //
+
+ if (i != n)
+ {
+ if (cert != null && cert.Version == 1)
+ {
+ // we've found the trust anchor at the top of the path, ignore and keep going
+ if ((i == 1) && cert.Equals(trust.TrustedCert))
+ continue;
+
+ throw new PkixCertPathValidatorException(
+ "Version 1 certificates can't be used as CA ones.", null, certPath, index);
+ }
+
+ Rfc3280CertPathUtilities.PrepareNextCertA(certPath, index);
+
+ validPolicyTree = Rfc3280CertPathUtilities.PrepareCertB(certPath, index, policyNodes,
+ validPolicyTree, policyMapping);
+
+ Rfc3280CertPathUtilities.PrepareNextCertG(certPath, index, nameConstraintValidator);
+
+ // (h)
+ explicitPolicy = Rfc3280CertPathUtilities.PrepareNextCertH1(certPath, index, explicitPolicy);
+ policyMapping = Rfc3280CertPathUtilities.PrepareNextCertH2(certPath, index, policyMapping);
+ inhibitAnyPolicy = Rfc3280CertPathUtilities.PrepareNextCertH3(certPath, index, inhibitAnyPolicy);
+
+ //
+ // (i)
+ //
+ explicitPolicy = Rfc3280CertPathUtilities.PrepareNextCertI1(certPath, index, explicitPolicy);
+ policyMapping = Rfc3280CertPathUtilities.PrepareNextCertI2(certPath, index, policyMapping);
+
+ // (j)
+ inhibitAnyPolicy = Rfc3280CertPathUtilities.PrepareNextCertJ(certPath, index, inhibitAnyPolicy);
+
+ // (k)
+ Rfc3280CertPathUtilities.PrepareNextCertK(certPath, index);
+
+ // (l)
+ maxPathLength = Rfc3280CertPathUtilities.PrepareNextCertL(certPath, index, maxPathLength);
+
+ // (m)
+ maxPathLength = Rfc3280CertPathUtilities.PrepareNextCertM(certPath, index, maxPathLength);
+
+ // (n)
+ Rfc3280CertPathUtilities.PrepareNextCertN(certPath, index);
+
+ ISet criticalExtensions1 = cert.GetCriticalExtensionOids();
+
+ if (criticalExtensions1 != null)
+ {
+ criticalExtensions1 = new HashSet(criticalExtensions1);
+
+ // these extensions are handled by the algorithm
+ criticalExtensions1.Remove(X509Extensions.KeyUsage.Id);
+ criticalExtensions1.Remove(X509Extensions.CertificatePolicies.Id);
+ criticalExtensions1.Remove(X509Extensions.PolicyMappings.Id);
+ criticalExtensions1.Remove(X509Extensions.InhibitAnyPolicy.Id);
+ criticalExtensions1.Remove(X509Extensions.IssuingDistributionPoint.Id);
+ criticalExtensions1.Remove(X509Extensions.DeltaCrlIndicator.Id);
+ criticalExtensions1.Remove(X509Extensions.PolicyConstraints.Id);
+ criticalExtensions1.Remove(X509Extensions.BasicConstraints.Id);
+ criticalExtensions1.Remove(X509Extensions.SubjectAlternativeName.Id);
+ criticalExtensions1.Remove(X509Extensions.NameConstraints.Id);
+ }
+ else
+ {
+ criticalExtensions1 = new HashSet();
+ }
+
+ // (o)
+ Rfc3280CertPathUtilities.PrepareNextCertO(certPath, index, criticalExtensions1, pathCheckers);
+
+ // set signing certificate for next round
+ sign = cert;
+
+ // (c)
+ workingIssuerName = sign.SubjectDN;
+
+ // (d)
+ try
+ {
+ workingPublicKey = PkixCertPathValidatorUtilities.GetNextWorkingKey(certPath.Certificates, index);
+ }
+ catch (PkixCertPathValidatorException e)
+ {
+ throw new PkixCertPathValidatorException("Next working key could not be retrieved.", e, certPath, index);
+ }
+
+ workingAlgId = PkixCertPathValidatorUtilities.GetAlgorithmIdentifier(workingPublicKey);
+ // (f)
+// workingPublicKeyAlgorithm = workingAlgId.Algorithm;
+ // (e)
+// workingPublicKeyParameters = workingAlgId.Parameters;
+ }
+ }
+
+ //
+ // 6.1.5 Wrap-up procedure
+ //
+
+ explicitPolicy = Rfc3280CertPathUtilities.WrapupCertA(explicitPolicy, cert);
+
+ explicitPolicy = Rfc3280CertPathUtilities.WrapupCertB(certPath, index + 1, explicitPolicy);
+
+ //
+ // (c) (d) and (e) are already done
+ //
+
+ //
+ // (f)
+ //
+ ISet criticalExtensions = cert.GetCriticalExtensionOids();
+
+ if (criticalExtensions != null)
+ {
+ criticalExtensions = new HashSet(criticalExtensions);
+
+ // Requires .Id
+ // these extensions are handled by the algorithm
+ criticalExtensions.Remove(X509Extensions.KeyUsage.Id);
+ criticalExtensions.Remove(X509Extensions.CertificatePolicies.Id);
+ criticalExtensions.Remove(X509Extensions.PolicyMappings.Id);
+ criticalExtensions.Remove(X509Extensions.InhibitAnyPolicy.Id);
+ criticalExtensions.Remove(X509Extensions.IssuingDistributionPoint.Id);
+ criticalExtensions.Remove(X509Extensions.DeltaCrlIndicator.Id);
+ criticalExtensions.Remove(X509Extensions.PolicyConstraints.Id);
+ criticalExtensions.Remove(X509Extensions.BasicConstraints.Id);
+ criticalExtensions.Remove(X509Extensions.SubjectAlternativeName.Id);
+ criticalExtensions.Remove(X509Extensions.NameConstraints.Id);
+ criticalExtensions.Remove(X509Extensions.CrlDistributionPoints.Id);
+ }
+ else
+ {
+ criticalExtensions = new HashSet();
+ }
+
+ Rfc3280CertPathUtilities.WrapupCertF(certPath, index + 1, pathCheckers, criticalExtensions);
+
+ PkixPolicyNode intersection = Rfc3280CertPathUtilities.WrapupCertG(certPath, paramsPkix, userInitialPolicySet,
+ index + 1, policyNodes, validPolicyTree, acceptablePolicies);
+
+ if ((explicitPolicy > 0) || (intersection != null))
+ {
+ return new PkixCertPathValidatorResult(trust, intersection, cert.GetPublicKey());
+ }
+
+ throw new PkixCertPathValidatorException("Path processing failed on policy.", null, certPath, index);
+ }
+
+ internal static void CheckCertificate(X509Certificate cert)
+ {
+ try
+ {
+ TbsCertificateStructure.GetInstance(cert.CertificateStructure.TbsCertificate);
+ }
+ catch (CertificateEncodingException e)
+ {
+ throw new Exception("unable to process TBSCertificate", e);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathValidator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathValidator.cs.meta
new file mode 100644
index 00000000..f4940c1b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathValidator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 1230039d20abc264894f233518e57548
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathValidatorException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathValidatorException.cs
new file mode 100644
index 00000000..742ef214
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathValidatorException.cs
@@ -0,0 +1,225 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix
+{
+ /**
+ * An exception indicating one of a variety of problems encountered when
+ * validating a certification path.
+ *
+ * A CertPathValidatorException provides support for wrapping
+ * exceptions. The {@link #getCause getCause} method returns the throwable,
+ * if any, that caused this exception to be thrown.
+ *
+ * A CertPathValidatorException may also include the
+ * certification path that was being validated when the exception was thrown
+ * and the index of the certificate in the certification path that caused the
+ * exception to be thrown. Use the {@link #getCertPath getCertPath} and
+ * {@link #getIndex getIndex} methods to retrieve this information.
+ *
+ * Concurrent Access
+ *
+ * Unless otherwise specified, the methods defined in this class are not
+ * thread-safe. Multiple threads that need to access a single
+ * object concurrently should synchronize amongst themselves and
+ * provide the necessary locking. Multiple threads each manipulating
+ * separate objects need not synchronize.
+ *
+ * @see CertPathValidator
+ **/
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class PkixCertPathValidatorException
+ : GeneralSecurityException
+ {
+ private Exception cause;
+ private PkixCertPath certPath;
+ private int index = -1;
+
+ public PkixCertPathValidatorException() : base() { }
+
+ ///
+ /// Creates a PkixCertPathValidatorException with the given detail
+ /// message. A detail message is a String that describes this
+ /// particular exception.
+ ///
+ /// the detail message
+ public PkixCertPathValidatorException(string message) : base(message) { }
+
+ ///
+ /// Creates a PkixCertPathValidatorException with the specified
+ /// detail message and cause.
+ ///
+ /// the detail message
+ /// the cause (which is saved for later retrieval by the
+ /// {@link #getCause getCause()} method). (A null
+ /// value is permitted, and indicates that the cause is
+ /// nonexistent or unknown.)
+ public PkixCertPathValidatorException(string message, Exception cause) : base(message)
+ {
+ this.cause = cause;
+ }
+
+ ///
+ /// Creates a PkixCertPathValidatorException with the specified
+ /// detail message, cause, certification path, and index.
+ ///
+ /// the detail message (or null if none)
+ /// the cause (or null if none)
+ /// the certification path that was in the process of being
+ /// validated when the error was encountered
+ /// the index of the certificate in the certification path that *
+ public PkixCertPathValidatorException(
+ string message,
+ Exception cause,
+ PkixCertPath certPath,
+ int index)
+ : base(message)
+ {
+ if (certPath == null && index != -1)
+ {
+ throw new ArgumentNullException(
+ "certPath = null and index != -1");
+ }
+ if (index < -1
+ || (certPath != null && index >= certPath.Certificates.Count))
+ {
+ throw new IndexOutOfRangeException(
+ " index < -1 or out of bound of certPath.getCertificates()");
+ }
+
+ this.cause = cause;
+ this.certPath = certPath;
+ this.index = index;
+ }
+
+ //
+ // Prints a stack trace to a PrintWriter, including the
+ // backtrace of the cause, if any.
+ //
+ // @param pw
+ // the PrintWriter to use for output
+ //
+ // public void printStackTrace(PrintWriter pw)
+ // {
+ // super.printStackTrace(pw);
+ // if (getCause() != null)
+ // {
+ // getCause().printStackTrace(pw);
+ // }
+ // }
+ //}
+
+
+ // /**
+ // * Creates a CertPathValidatorException that wraps the
+ // * specified throwable. This allows any exception to be converted into a
+ // * CertPathValidatorException, while retaining information
+ // * about the wrapped exception, which may be useful for debugging. The
+ // * detail message is set to (cause==null ? null : cause.toString()
+ // * )
+ // * (which typically contains the class and detail message of cause).
+ // *
+ // * @param cause
+ // * the cause (which is saved for later retrieval by the
+ // * {@link #getCause getCause()} method). (A null
+ // * value is permitted, and indicates that the cause is
+ // * nonexistent or unknown.)
+ // */
+ // public PkixCertPathValidatorException(Throwable cause)
+ // {
+ // this.cause = cause;
+ // }
+ //
+
+ ///
+ /// Returns the detail message for this CertPathValidatorException.
+ ///
+ /// the detail message, or null if neither the message nor cause were specified
+ public override string Message
+ {
+ get
+ {
+ string message = base.Message;
+
+ if (message != null)
+ {
+ return message;
+ }
+
+ if (cause != null)
+ {
+ return cause.Message;
+ }
+
+ return null;
+ }
+ }
+
+ /**
+ * Returns the certification path that was being validated when the
+ * exception was thrown.
+ *
+ * @return the CertPath that was being validated when the
+ * exception was thrown (or null if not specified)
+ */
+ public PkixCertPath CertPath
+ {
+ get { return certPath; }
+ }
+
+ /**
+ * Returns the index of the certificate in the certification path that
+ * caused the exception to be thrown. Note that the list of certificates in
+ * a CertPath is zero based. If no index has been set, -1 is
+ * returned.
+ *
+ * @return the index that has been set, or -1 if none has been set
+ */
+ public int Index
+ {
+ get { return index; }
+ }
+
+// /**
+// * Returns the cause of this CertPathValidatorException or
+// * null if the cause is nonexistent or unknown.
+// *
+// * @return the cause of this throwable or null if the cause
+// * is nonexistent or unknown.
+// */
+// public Throwable getCause()
+// {
+// return cause;
+// }
+//
+// /**
+// * Returns a string describing this exception, including a description of
+// * the internal (wrapped) cause if there is one.
+// *
+// * @return a string representation of this
+// * CertPathValidatorException
+// */
+// public String toString()
+// {
+// StringBuffer sb = new StringBuffer();
+// String s = getMessage();
+// if (s != null)
+// {
+// sb.append(s);
+// }
+// if (getIndex() >= 0)
+// {
+// sb.append("index in certpath: ").append(getIndex()).append('\n');
+// sb.append(getCertPath());
+// }
+// return sb.toString();
+// }
+
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathValidatorException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathValidatorException.cs.meta
new file mode 100644
index 00000000..b4521bf5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathValidatorException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: db2fbbf90588ea041ab1bf5b62f86bea
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathValidatorResult.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathValidatorResult.cs
new file mode 100644
index 00000000..c9132df6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathValidatorResult.cs
@@ -0,0 +1,73 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix
+{
+ ///
+ /// Summary description for PkixCertPathValidatorResult.
+ ///
+ public class PkixCertPathValidatorResult
+ //: ICertPathValidatorResult
+ {
+ private TrustAnchor trustAnchor;
+ private PkixPolicyNode policyTree;
+ private AsymmetricKeyParameter subjectPublicKey;
+
+ public PkixPolicyNode PolicyTree
+ {
+ get { return this.policyTree; }
+ }
+
+ public TrustAnchor TrustAnchor
+ {
+ get { return this.trustAnchor; }
+ }
+
+ public AsymmetricKeyParameter SubjectPublicKey
+ {
+ get { return this.subjectPublicKey; }
+ }
+
+ public PkixCertPathValidatorResult(
+ TrustAnchor trustAnchor,
+ PkixPolicyNode policyTree,
+ AsymmetricKeyParameter subjectPublicKey)
+ {
+ if (subjectPublicKey == null)
+ {
+ throw new NullReferenceException("subjectPublicKey must be non-null");
+ }
+ if (trustAnchor == null)
+ {
+ throw new NullReferenceException("trustAnchor must be non-null");
+ }
+
+ this.trustAnchor = trustAnchor;
+ this.policyTree = policyTree;
+ this.subjectPublicKey = subjectPublicKey;
+ }
+
+ public object Clone()
+ {
+ return new PkixCertPathValidatorResult(this.TrustAnchor, this.PolicyTree, this.SubjectPublicKey);
+ }
+
+ public override String ToString()
+ {
+ StringBuilder sB = new StringBuilder();
+ sB.Append("PKIXCertPathValidatorResult: [ \n");
+ sB.Append(" Trust Anchor: ").Append(this.TrustAnchor).Append('\n');
+ sB.Append(" Policy Tree: ").Append(this.PolicyTree).Append('\n');
+ sB.Append(" Subject Public Key: ").Append(this.SubjectPublicKey).Append("\n]");
+ return sB.ToString();
+ }
+
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathValidatorResult.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathValidatorResult.cs.meta
new file mode 100644
index 00000000..3bb041cb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathValidatorResult.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: f0872050d12dad44abb76c1745b5f870
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathValidatorUtilities.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathValidatorUtilities.cs
new file mode 100644
index 00000000..af67e95e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathValidatorUtilities.cs
@@ -0,0 +1,1212 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.IsisMtt;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Date;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Extension;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix
+{
+ ///
+ /// Summary description for PkixCertPathValidatorUtilities.
+ ///
+ public class PkixCertPathValidatorUtilities
+ {
+ private static readonly PkixCrlUtilities CrlUtilities = new PkixCrlUtilities();
+
+ internal static readonly string ANY_POLICY = "2.5.29.32.0";
+
+ internal static readonly string CRL_NUMBER = X509Extensions.CrlNumber.Id;
+
+ ///
+ /// key usage bits
+ ///
+ internal static readonly int KEY_CERT_SIGN = 5;
+ internal static readonly int CRL_SIGN = 6;
+
+ internal static readonly string[] crlReasons = new string[]
+ {
+ "unspecified",
+ "keyCompromise",
+ "cACompromise",
+ "affiliationChanged",
+ "superseded",
+ "cessationOfOperation",
+ "certificateHold",
+ "unknown",
+ "removeFromCRL",
+ "privilegeWithdrawn",
+ "aACompromise"
+ };
+
+ ///
+ /// Search the given Set of TrustAnchor's for one that is the
+ /// issuer of the given X509 certificate.
+ ///
+ /// the X509 certificate
+ /// a Set of TrustAnchor's
+ /// the TrustAnchor object if found or
+ /// null if not.
+ ///
+ /// @exception
+ internal static TrustAnchor FindTrustAnchor(
+ X509Certificate cert,
+ ISet trustAnchors)
+ {
+ IEnumerator iter = trustAnchors.GetEnumerator();
+ TrustAnchor trust = null;
+ AsymmetricKeyParameter trustPublicKey = null;
+ Exception invalidKeyEx = null;
+
+ X509CertStoreSelector certSelectX509 = new X509CertStoreSelector();
+
+ try
+ {
+ certSelectX509.Subject = GetIssuerPrincipal(cert);
+ }
+ catch (IOException ex)
+ {
+ throw new Exception("Cannot set subject search criteria for trust anchor.", ex);
+ }
+
+ while (iter.MoveNext() && trust == null)
+ {
+ trust = (TrustAnchor) iter.Current;
+ if (trust.TrustedCert != null)
+ {
+ if (certSelectX509.Match(trust.TrustedCert))
+ {
+ trustPublicKey = trust.TrustedCert.GetPublicKey();
+ }
+ else
+ {
+ trust = null;
+ }
+ }
+ else if (trust.CAName != null && trust.CAPublicKey != null)
+ {
+ try
+ {
+ X509Name certIssuer = GetIssuerPrincipal(cert);
+ X509Name caName = new X509Name(trust.CAName);
+
+ if (certIssuer.Equivalent(caName, true))
+ {
+ trustPublicKey = trust.CAPublicKey;
+ }
+ else
+ {
+ trust = null;
+ }
+ }
+ catch (InvalidParameterException)
+ {
+ trust = null;
+ }
+ }
+ else
+ {
+ trust = null;
+ }
+
+ if (trustPublicKey != null)
+ {
+ try
+ {
+ cert.Verify(trustPublicKey);
+ }
+ catch (Exception ex)
+ {
+ invalidKeyEx = ex;
+ trust = null;
+ }
+ }
+ }
+
+ if (trust == null && invalidKeyEx != null)
+ {
+ throw new Exception("TrustAnchor found but certificate validation failed.", invalidKeyEx);
+ }
+
+ return trust;
+ }
+
+ internal static bool IsIssuerTrustAnchor(
+ X509Certificate cert,
+ ISet trustAnchors)
+ {
+ try
+ {
+ return FindTrustAnchor(cert, trustAnchors) != null;
+ }
+ catch (Exception e)
+ {
+ return false;
+ }
+ }
+
+ internal static void AddAdditionalStoresFromAltNames(
+ X509Certificate cert,
+ PkixParameters pkixParams)
+ {
+ // if in the IssuerAltName extension an URI
+ // is given, add an additinal X.509 store
+ if (cert.GetIssuerAlternativeNames() != null)
+ {
+ IEnumerator it = cert.GetIssuerAlternativeNames().GetEnumerator();
+ while (it.MoveNext())
+ {
+ // look for URI
+ IList list = (IList)it.Current;
+ //if (list[0].Equals(new Integer(GeneralName.UniformResourceIdentifier)))
+ if (list[0].Equals(GeneralName.UniformResourceIdentifier))
+ {
+ // found
+ string temp = (string)list[1];
+ PkixCertPathValidatorUtilities.AddAdditionalStoreFromLocation(temp, pkixParams);
+ }
+ }
+ }
+ }
+
+ internal static DateTime GetValidDate(PkixParameters paramsPKIX)
+ {
+ DateTimeObject validDate = paramsPKIX.Date;
+
+ if (validDate == null)
+ return DateTime.UtcNow;
+
+ return validDate.Value;
+ }
+
+ ///
+ /// Returns the issuer of an attribute certificate or certificate.
+ ///
+ /// The attribute certificate or certificate.
+ /// The issuer as X500Principal.
+ internal static X509Name GetIssuerPrincipal(
+ object cert)
+ {
+ if (cert is X509Certificate)
+ {
+ return ((X509Certificate)cert).IssuerDN;
+ }
+ else
+ {
+ return ((IX509AttributeCertificate)cert).Issuer.GetPrincipals()[0];
+ }
+ }
+
+ internal static bool IsSelfIssued(
+ X509Certificate cert)
+ {
+ return cert.SubjectDN.Equivalent(cert.IssuerDN, true);
+ }
+
+ internal static AlgorithmIdentifier GetAlgorithmIdentifier(
+ AsymmetricKeyParameter key)
+ {
+ try
+ {
+ SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(key);
+
+ return info.AlgorithmID;
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathValidatorException("Subject public key cannot be decoded.", e);
+ }
+ }
+
+ internal static bool IsAnyPolicy(
+ ISet policySet)
+ {
+ return policySet == null || policySet.Contains(ANY_POLICY) || policySet.Count == 0;
+ }
+
+ internal static void AddAdditionalStoreFromLocation(
+ string location,
+ PkixParameters pkixParams)
+ {
+ if (pkixParams.IsAdditionalLocationsEnabled)
+ {
+ try
+ {
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(location, "ldap://"))
+ {
+ // ldap://directory.d-trust.net/CN=D-TRUST
+ // Qualified CA 2003 1:PN,O=D-Trust GmbH,C=DE
+ // skip "ldap://"
+ location = location.Substring(7);
+ // after first / baseDN starts
+ string url;//, baseDN;
+ int slashPos = location.IndexOf('/');
+ if (slashPos != -1)
+ {
+ url = "ldap://" + location.Substring(0, slashPos);
+// baseDN = location.Substring(slashPos);
+ }
+ else
+ {
+ url = "ldap://" + location;
+// baseDN = nsull;
+ }
+
+ throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("LDAP cert/CRL stores");
+
+ // use all purpose parameters
+ //X509LDAPCertStoreParameters ldapParams = new X509LDAPCertStoreParameters.Builder(
+ // url, baseDN).build();
+ //pkixParams.AddAdditionalStore(X509Store.getInstance(
+ // "CERTIFICATE/LDAP", ldapParams));
+ //pkixParams.AddAdditionalStore(X509Store.getInstance(
+ // "CRL/LDAP", ldapParams));
+ //pkixParams.AddAdditionalStore(X509Store.getInstance(
+ // "ATTRIBUTECERTIFICATE/LDAP", ldapParams));
+ //pkixParams.AddAdditionalStore(X509Store.getInstance(
+ // "CERTIFICATEPAIR/LDAP", ldapParams));
+ }
+ }
+ catch (Exception)
+ {
+ // cannot happen
+ throw new Exception("Exception adding X.509 stores.");
+ }
+ }
+ }
+
+ private static BigInteger GetSerialNumber(
+ object cert)
+ {
+ if (cert is X509Certificate)
+ {
+ return ((X509Certificate)cert).SerialNumber;
+ }
+ else
+ {
+ return ((X509V2AttributeCertificate)cert).SerialNumber;
+ }
+ }
+
+ //
+ // policy checking
+ //
+
+ internal static ISet GetQualifierSet(Asn1Sequence qualifiers)
+ {
+ ISet pq = new HashSet();
+
+ if (qualifiers == null)
+ {
+ return pq;
+ }
+
+ foreach (Asn1Encodable ae in qualifiers)
+ {
+ try
+ {
+// pq.Add(PolicyQualifierInfo.GetInstance(Asn1Object.FromByteArray(ae.GetEncoded())));
+ pq.Add(PolicyQualifierInfo.GetInstance(ae.ToAsn1Object()));
+ }
+ catch (IOException ex)
+ {
+ throw new PkixCertPathValidatorException("Policy qualifier info cannot be decoded.", ex);
+ }
+ }
+
+ return pq;
+ }
+
+ internal static PkixPolicyNode RemovePolicyNode(
+ PkixPolicyNode validPolicyTree,
+ IList[] policyNodes,
+ PkixPolicyNode _node)
+ {
+ PkixPolicyNode _parent = (PkixPolicyNode)_node.Parent;
+
+ if (validPolicyTree == null)
+ {
+ return null;
+ }
+
+ if (_parent == null)
+ {
+ for (int j = 0; j < policyNodes.Length; j++)
+ {
+ policyNodes[j] = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ }
+
+ return null;
+ }
+ else
+ {
+ _parent.RemoveChild(_node);
+ RemovePolicyNodeRecurse(policyNodes, _node);
+
+ return validPolicyTree;
+ }
+ }
+
+ private static void RemovePolicyNodeRecurse(IList[] policyNodes, PkixPolicyNode _node)
+ {
+ policyNodes[_node.Depth].Remove(_node);
+
+ if (_node.HasChildren)
+ {
+ foreach (PkixPolicyNode _child in _node.Children)
+ {
+ RemovePolicyNodeRecurse(policyNodes, _child);
+ }
+ }
+ }
+
+ internal static void PrepareNextCertB1(
+ int i,
+ IList[] policyNodes,
+ string id_p,
+ IDictionary m_idp,
+ X509Certificate cert)
+ {
+ bool idp_found = false;
+ IEnumerator nodes_i = policyNodes[i].GetEnumerator();
+ while (nodes_i.MoveNext())
+ {
+ PkixPolicyNode node = (PkixPolicyNode)nodes_i.Current;
+ if (node.ValidPolicy.Equals(id_p))
+ {
+ idp_found = true;
+ node.ExpectedPolicies = (ISet)m_idp[id_p];
+ break;
+ }
+ }
+
+ if (!idp_found)
+ {
+ nodes_i = policyNodes[i].GetEnumerator();
+ while (nodes_i.MoveNext())
+ {
+ PkixPolicyNode node = (PkixPolicyNode)nodes_i.Current;
+ if (ANY_POLICY.Equals(node.ValidPolicy))
+ {
+ ISet pq = null;
+ Asn1Sequence policies = null;
+ try
+ {
+ policies = DerSequence.GetInstance(GetExtensionValue(cert, X509Extensions.CertificatePolicies));
+ }
+ catch (Exception e)
+ {
+ throw new Exception("Certificate policies cannot be decoded.", e);
+ }
+
+ IEnumerator enm = policies.GetEnumerator();
+ while (enm.MoveNext())
+ {
+ PolicyInformation pinfo = null;
+
+ try
+ {
+ pinfo = PolicyInformation.GetInstance(enm.Current);
+ }
+ catch (Exception ex)
+ {
+ throw new Exception("Policy information cannot be decoded.", ex);
+ }
+
+ if (ANY_POLICY.Equals(pinfo.PolicyIdentifier.Id))
+ {
+ try
+ {
+ pq = GetQualifierSet(pinfo.PolicyQualifiers);
+ }
+ catch (PkixCertPathValidatorException ex)
+ {
+ throw new PkixCertPathValidatorException(
+ "Policy qualifier info set could not be built.", ex);
+ }
+ break;
+ }
+ }
+ bool ci = false;
+ ISet critExtOids = cert.GetCriticalExtensionOids();
+ if (critExtOids != null)
+ {
+ ci = critExtOids.Contains(X509Extensions.CertificatePolicies.Id);
+ }
+
+ PkixPolicyNode p_node = (PkixPolicyNode)node.Parent;
+ if (ANY_POLICY.Equals(p_node.ValidPolicy))
+ {
+ PkixPolicyNode c_node = new PkixPolicyNode(
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(), i,
+ (ISet)m_idp[id_p],
+ p_node, pq, id_p, ci);
+ p_node.AddChild(c_node);
+ policyNodes[i].Add(c_node);
+ }
+ break;
+ }
+ }
+ }
+ }
+
+ internal static PkixPolicyNode PrepareNextCertB2(
+ int i,
+ IList[] policyNodes,
+ string id_p,
+ PkixPolicyNode validPolicyTree)
+ {
+ int pos = 0;
+
+ // Copy to avoid RemoveAt calls interfering with enumeration
+ foreach (PkixPolicyNode node in BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(policyNodes[i]))
+ {
+ if (node.ValidPolicy.Equals(id_p))
+ {
+ PkixPolicyNode p_node = (PkixPolicyNode)node.Parent;
+ p_node.RemoveChild(node);
+
+ // Removal of element at current iterator position not supported in C#
+ //nodes_i.remove();
+ policyNodes[i].RemoveAt(pos);
+
+ for (int k = (i - 1); k >= 0; k--)
+ {
+ IList nodes = policyNodes[k];
+ for (int l = 0; l < nodes.Count; l++)
+ {
+ PkixPolicyNode node2 = (PkixPolicyNode)nodes[l];
+ if (!node2.HasChildren)
+ {
+ validPolicyTree = RemovePolicyNode(validPolicyTree, policyNodes, node2);
+ if (validPolicyTree == null)
+ break;
+ }
+ }
+ }
+ }
+ else
+ {
+ ++pos;
+ }
+ }
+ return validPolicyTree;
+ }
+
+ internal static void GetCertStatus(
+ DateTime validDate,
+ X509Crl crl,
+ Object cert,
+ CertStatus certStatus)
+ {
+ X509Crl bcCRL = null;
+
+ try
+ {
+ bcCRL = new X509Crl(CertificateList.GetInstance((Asn1Sequence)Asn1Sequence.FromByteArray(crl.GetEncoded())));
+ }
+ catch (Exception exception)
+ {
+ throw new Exception("Bouncy Castle X509Crl could not be created.", exception);
+ }
+
+ X509CrlEntry crl_entry = (X509CrlEntry)bcCRL.GetRevokedCertificate(GetSerialNumber(cert));
+
+ if (crl_entry == null)
+ return;
+
+ X509Name issuer = GetIssuerPrincipal(cert);
+
+ if (issuer.Equivalent(crl_entry.GetCertificateIssuer(), true)
+ || issuer.Equivalent(crl.IssuerDN, true))
+ {
+ DerEnumerated reasonCode = null;
+ if (crl_entry.HasExtensions)
+ {
+ try
+ {
+ reasonCode = DerEnumerated.GetInstance(
+ GetExtensionValue(crl_entry, X509Extensions.ReasonCode));
+ }
+ catch (Exception e)
+ {
+ throw new Exception(
+ "Reason code CRL entry extension could not be decoded.",
+ e);
+ }
+ }
+
+ // for reason keyCompromise, caCompromise, aACompromise or
+ // unspecified
+ if (!(validDate.Ticks < crl_entry.RevocationDate.Ticks)
+ || reasonCode == null
+ || reasonCode.Value.TestBit(0)
+ || reasonCode.Value.TestBit(1)
+ || reasonCode.Value.TestBit(2)
+ || reasonCode.Value.TestBit(8))
+ {
+ if (reasonCode != null) // (i) or (j) (1)
+ {
+ certStatus.Status = reasonCode.Value.SignValue;
+ }
+ else // (i) or (j) (2)
+ {
+ certStatus.Status = CrlReason.Unspecified;
+ }
+ certStatus.RevocationDate = new DateTimeObject(crl_entry.RevocationDate);
+ }
+ }
+ }
+
+ /**
+ * Return the next working key inheriting DSA parameters if necessary.
+ *
+ * This methods inherits DSA parameters from the indexed certificate or
+ * previous certificates in the certificate chain to the returned
+ * PublicKey. The list is searched upwards, meaning the end
+ * certificate is at position 0 and previous certificates are following.
+ *
+ *
+ * If the indexed certificate does not contain a DSA key this method simply
+ * returns the public key. If the DSA key already contains DSA parameters
+ * the key is also only returned.
+ *
+ *
+ * @param certs The certification path.
+ * @param index The index of the certificate which contains the public key
+ * which should be extended with DSA parameters.
+ * @return The public key of the certificate in list position
+ * index extended with DSA parameters if applicable.
+ * @throws Exception if DSA parameters cannot be inherited.
+ */
+ internal static AsymmetricKeyParameter GetNextWorkingKey(
+ IList certs,
+ int index)
+ {
+ //Only X509Certificate
+ X509Certificate cert = (X509Certificate)certs[index];
+
+ AsymmetricKeyParameter pubKey = cert.GetPublicKey();
+
+ if (!(pubKey is DsaPublicKeyParameters))
+ return pubKey;
+
+ DsaPublicKeyParameters dsaPubKey = (DsaPublicKeyParameters)pubKey;
+
+ if (dsaPubKey.Parameters != null)
+ return dsaPubKey;
+
+ for (int i = index + 1; i < certs.Count; i++)
+ {
+ X509Certificate parentCert = (X509Certificate)certs[i];
+ pubKey = parentCert.GetPublicKey();
+
+ if (!(pubKey is DsaPublicKeyParameters))
+ {
+ throw new PkixCertPathValidatorException(
+ "DSA parameters cannot be inherited from previous certificate.");
+ }
+
+ DsaPublicKeyParameters prevDSAPubKey = (DsaPublicKeyParameters)pubKey;
+
+ if (prevDSAPubKey.Parameters == null)
+ continue;
+
+ DsaParameters dsaParams = prevDSAPubKey.Parameters;
+
+ try
+ {
+ return new DsaPublicKeyParameters(dsaPubKey.Y, dsaParams);
+ }
+ catch (Exception exception)
+ {
+ throw new Exception(exception.Message);
+ }
+ }
+
+ throw new PkixCertPathValidatorException("DSA parameters cannot be inherited from previous certificate.");
+ }
+
+ internal static DateTime GetValidCertDateFromValidityModel(
+ PkixParameters paramsPkix,
+ PkixCertPath certPath,
+ int index)
+ {
+ if (paramsPkix.ValidityModel != PkixParameters.ChainValidityModel)
+ {
+ return GetValidDate(paramsPkix);
+ }
+
+ // if end cert use given signing/encryption/... time
+ if (index <= 0)
+ {
+ return PkixCertPathValidatorUtilities.GetValidDate(paramsPkix);
+ // else use time when previous cert was created
+ }
+
+ if (index - 1 == 0)
+ {
+ DerGeneralizedTime dateOfCertgen = null;
+ try
+ {
+ X509Certificate cert = (X509Certificate)certPath.Certificates[index - 1];
+ Asn1OctetString extVal = cert.GetExtensionValue(
+ IsisMttObjectIdentifiers.IdIsisMttATDateOfCertGen);
+ dateOfCertgen = DerGeneralizedTime.GetInstance(extVal);
+ }
+ catch (ArgumentException)
+ {
+ throw new Exception(
+ "Date of cert gen extension could not be read.");
+ }
+ if (dateOfCertgen != null)
+ {
+ try
+ {
+ return dateOfCertgen.ToDateTime();
+ }
+ catch (ArgumentException e)
+ {
+ throw new Exception(
+ "Date from date of cert gen extension could not be parsed.",
+ e);
+ }
+ }
+ }
+
+ return ((X509Certificate)certPath.Certificates[index - 1]).NotBefore;
+ }
+
+ ///
+ /// Return a Collection of all certificates or attribute certificates found
+ /// in the X509Store's that are matching the certSelect criteriums.
+ ///
+ /// a {@link Selector} object that will be used to select
+ /// the certificates
+ /// a List containing only X509Store objects. These
+ /// are used to search for certificates.
+ /// a Collection of all found or
+ /// objects.
+ /// May be empty but never null.
+ ///
+ internal static ICollection FindCertificates(
+ X509CertStoreSelector certSelect,
+ IList certStores)
+ {
+ ISet certs = new HashSet();
+
+ foreach (IX509Store certStore in certStores)
+ {
+ try
+ {
+// certs.AddAll(certStore.GetMatches(certSelect));
+ foreach (X509Certificate c in certStore.GetMatches(certSelect))
+ {
+ certs.Add(c);
+ }
+ }
+ catch (Exception e)
+ {
+ throw new Exception("Problem while picking certificates from X.509 store.", e);
+ }
+ }
+
+ return certs;
+ }
+
+ /**
+ * Add the CRL issuers from the cRLIssuer field of the distribution point or
+ * from the certificate if not given to the issuer criterion of the
+ * selector.
+ *
+ * The issuerPrincipals are a collection with a single
+ * X500Principal for X509Certificates. For
+ * {@link X509AttributeCertificate}s the issuer may contain more than one
+ * X500Principal.
+ *
+ *
+ * @param dp The distribution point.
+ * @param issuerPrincipals The issuers of the certificate or attribute
+ * certificate which contains the distribution point.
+ * @param selector The CRL selector.
+ * @param pkixParams The PKIX parameters containing the cert stores.
+ * @throws Exception if an exception occurs while processing.
+ * @throws ClassCastException if issuerPrincipals does not
+ * contain only X500Principals.
+ */
+ internal static void GetCrlIssuersFromDistributionPoint(
+ DistributionPoint dp,
+ ICollection issuerPrincipals,
+ X509CrlStoreSelector selector,
+ PkixParameters pkixParams)
+ {
+ IList issuers = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ // indirect CRL
+ if (dp.CrlIssuer != null)
+ {
+ GeneralName[] genNames = dp.CrlIssuer.GetNames();
+ // look for a DN
+ for (int j = 0; j < genNames.Length; j++)
+ {
+ if (genNames[j].TagNo == GeneralName.DirectoryName)
+ {
+ try
+ {
+ issuers.Add(X509Name.GetInstance(genNames[j].Name.ToAsn1Object()));
+ }
+ catch (IOException e)
+ {
+ throw new Exception(
+ "CRL issuer information from distribution point cannot be decoded.",
+ e);
+ }
+ }
+ }
+ }
+ else
+ {
+ /*
+ * certificate issuer is CRL issuer, distributionPoint field MUST be
+ * present.
+ */
+ if (dp.DistributionPointName == null)
+ {
+ throw new Exception(
+ "CRL issuer is omitted from distribution point but no distributionPoint field present.");
+ }
+
+ // add and check issuer principals
+ for (IEnumerator it = issuerPrincipals.GetEnumerator(); it.MoveNext(); )
+ {
+ issuers.Add((X509Name)it.Current);
+ }
+ }
+ // TODO: is not found although this should correctly add the rel name. selector of Sun is buggy here or PKI test case is invalid
+ // distributionPoint
+ // if (dp.getDistributionPoint() != null)
+ // {
+ // // look for nameRelativeToCRLIssuer
+ // if (dp.getDistributionPoint().getType() == DistributionPointName.NAME_RELATIVE_TO_CRL_ISSUER)
+ // {
+ // // append fragment to issuer, only one
+ // // issuer can be there, if this is given
+ // if (issuers.size() != 1)
+ // {
+ // throw new AnnotatedException(
+ // "nameRelativeToCRLIssuer field is given but more than one CRL issuer is given.");
+ // }
+ // DEREncodable relName = dp.getDistributionPoint().getName();
+ // Iterator it = issuers.iterator();
+ // List issuersTemp = new ArrayList(issuers.size());
+ // while (it.hasNext())
+ // {
+ // Enumeration e = null;
+ // try
+ // {
+ // e = ASN1Sequence.getInstance(
+ // new ASN1InputStream(((X500Principal) it.next())
+ // .getEncoded()).readObject()).getObjects();
+ // }
+ // catch (IOException ex)
+ // {
+ // throw new AnnotatedException(
+ // "Cannot decode CRL issuer information.", ex);
+ // }
+ // ASN1EncodableVector v = new ASN1EncodableVector();
+ // while (e.hasMoreElements())
+ // {
+ // v.add((DEREncodable) e.nextElement());
+ // }
+ // v.add(relName);
+ // issuersTemp.add(new X500Principal(new DERSequence(v)
+ // .getDEREncoded()));
+ // }
+ // issuers.clear();
+ // issuers.addAll(issuersTemp);
+ // }
+ // }
+
+ selector.Issuers = issuers;
+ }
+
+ /**
+ * Fetches complete CRLs according to RFC 3280.
+ *
+ * @param dp The distribution point for which the complete CRL
+ * @param cert The X509Certificate or
+ * {@link org.bouncycastle.x509.X509AttributeCertificate} for
+ * which the CRL should be searched.
+ * @param currentDate The date for which the delta CRLs must be valid.
+ * @param paramsPKIX The extended PKIX parameters.
+ * @return A Set of X509CRLs with complete
+ * CRLs.
+ * @throws Exception if an exception occurs while picking the CRLs
+ * or no CRLs are found.
+ */
+ internal static ISet GetCompleteCrls(
+ DistributionPoint dp,
+ object cert,
+ DateTime currentDate,
+ PkixParameters paramsPKIX)
+ {
+ X509CrlStoreSelector crlselect = new X509CrlStoreSelector();
+ try
+ {
+ ISet issuers = new HashSet();
+ if (cert is X509V2AttributeCertificate)
+ {
+ issuers.Add(((X509V2AttributeCertificate)cert)
+ .Issuer.GetPrincipals()[0]);
+ }
+ else
+ {
+ issuers.Add(GetIssuerPrincipal(cert));
+ }
+ PkixCertPathValidatorUtilities.GetCrlIssuersFromDistributionPoint(dp, issuers, crlselect, paramsPKIX);
+ }
+ catch (Exception e)
+ {
+ throw new Exception("Could not get issuer information from distribution point.", e);
+ }
+
+ if (cert is X509Certificate)
+ {
+ crlselect.CertificateChecking = (X509Certificate)cert;
+ }
+ else if (cert is X509V2AttributeCertificate)
+ {
+ crlselect.AttrCertChecking = (IX509AttributeCertificate)cert;
+ }
+
+ crlselect.CompleteCrlEnabled = true;
+ ISet crls = CrlUtilities.FindCrls(crlselect, paramsPKIX, currentDate);
+
+ if (crls.IsEmpty)
+ {
+ if (cert is IX509AttributeCertificate)
+ {
+ IX509AttributeCertificate aCert = (IX509AttributeCertificate)cert;
+
+ throw new Exception("No CRLs found for issuer \"" + aCert.Issuer.GetPrincipals()[0] + "\"");
+ }
+ else
+ {
+ X509Certificate xCert = (X509Certificate)cert;
+
+ throw new Exception("No CRLs found for issuer \"" + xCert.IssuerDN + "\"");
+ }
+ }
+
+ return crls;
+ }
+
+ /**
+ * Fetches delta CRLs according to RFC 3280 section 5.2.4.
+ *
+ * @param currentDate The date for which the delta CRLs must be valid.
+ * @param paramsPKIX The extended PKIX parameters.
+ * @param completeCRL The complete CRL the delta CRL is for.
+ * @return A Set of X509CRLs with delta CRLs.
+ * @throws Exception if an exception occurs while picking the delta
+ * CRLs.
+ */
+ internal static ISet GetDeltaCrls(
+ DateTime currentDate,
+ PkixParameters paramsPKIX,
+ X509Crl completeCRL)
+ {
+ X509CrlStoreSelector deltaSelect = new X509CrlStoreSelector();
+
+ // 5.2.4 (a)
+ try
+ {
+ IList deltaSelectIssuer = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ deltaSelectIssuer.Add(completeCRL.IssuerDN);
+ deltaSelect.Issuers = deltaSelectIssuer;
+ }
+ catch (IOException e)
+ {
+ throw new Exception("Cannot extract issuer from CRL.", e);
+ }
+
+ BigInteger completeCRLNumber = null;
+ try
+ {
+ Asn1Object asn1Object = GetExtensionValue(completeCRL, X509Extensions.CrlNumber);
+ if (asn1Object != null)
+ {
+ completeCRLNumber = CrlNumber.GetInstance(asn1Object).PositiveValue;
+ }
+ }
+ catch (Exception e)
+ {
+ throw new Exception(
+ "CRL number extension could not be extracted from CRL.", e);
+ }
+
+ // 5.2.4 (b)
+ byte[] idp = null;
+
+ try
+ {
+ Asn1Object obj = GetExtensionValue(completeCRL, X509Extensions.IssuingDistributionPoint);
+ if (obj != null)
+ {
+ idp = obj.GetDerEncoded();
+ }
+ }
+ catch (Exception e)
+ {
+ throw new Exception(
+ "Issuing distribution point extension value could not be read.",
+ e);
+ }
+
+ // 5.2.4 (d)
+
+ deltaSelect.MinCrlNumber = (completeCRLNumber == null)
+ ? null
+ : completeCRLNumber.Add(BigInteger.One);
+
+ deltaSelect.IssuingDistributionPoint = idp;
+ deltaSelect.IssuingDistributionPointEnabled = true;
+
+ // 5.2.4 (c)
+ deltaSelect.MaxBaseCrlNumber = completeCRLNumber;
+
+ // find delta CRLs
+ ISet temp = CrlUtilities.FindCrls(deltaSelect, paramsPKIX, currentDate);
+
+ ISet result = new HashSet();
+
+ foreach (X509Crl crl in temp)
+ {
+ if (isDeltaCrl(crl))
+ {
+ result.Add(crl);
+ }
+ }
+
+ return result;
+ }
+
+ private static bool isDeltaCrl(
+ X509Crl crl)
+ {
+ ISet critical = crl.GetCriticalExtensionOids();
+
+ return critical.Contains(X509Extensions.DeltaCrlIndicator.Id);
+ }
+
+ internal static ICollection FindCertificates(
+ X509AttrCertStoreSelector certSelect,
+ IList certStores)
+ {
+ ISet certs = new HashSet();
+
+ foreach (IX509Store certStore in certStores)
+ {
+ try
+ {
+// certs.AddAll(certStore.GetMatches(certSelect));
+ foreach (X509V2AttributeCertificate ac in certStore.GetMatches(certSelect))
+ {
+ certs.Add(ac);
+ }
+ }
+ catch (Exception e)
+ {
+ throw new Exception(
+ "Problem while picking certificates from X.509 store.", e);
+ }
+ }
+
+ return certs;
+ }
+
+ internal static void AddAdditionalStoresFromCrlDistributionPoint(
+ CrlDistPoint crldp,
+ PkixParameters pkixParams)
+ {
+ if (crldp != null)
+ {
+ DistributionPoint[] dps = null;
+ try
+ {
+ dps = crldp.GetDistributionPoints();
+ }
+ catch (Exception e)
+ {
+ throw new Exception(
+ "Distribution points could not be read.", e);
+ }
+ for (int i = 0; i < dps.Length; i++)
+ {
+ DistributionPointName dpn = dps[i].DistributionPointName;
+ // look for URIs in fullName
+ if (dpn != null)
+ {
+ if (dpn.PointType == DistributionPointName.FullName)
+ {
+ GeneralName[] genNames = GeneralNames.GetInstance(
+ dpn.Name).GetNames();
+ // look for an URI
+ for (int j = 0; j < genNames.Length; j++)
+ {
+ if (genNames[j].TagNo == GeneralName.UniformResourceIdentifier)
+ {
+ string location = DerIA5String.GetInstance(
+ genNames[j].Name).GetString();
+ PkixCertPathValidatorUtilities.AddAdditionalStoreFromLocation(
+ location, pkixParams);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ internal static bool ProcessCertD1i(
+ int index,
+ IList[] policyNodes,
+ DerObjectIdentifier pOid,
+ ISet pq)
+ {
+ IList policyNodeVec = policyNodes[index - 1];
+
+ for (int j = 0; j < policyNodeVec.Count; j++)
+ {
+ PkixPolicyNode node = (PkixPolicyNode)policyNodeVec[j];
+ ISet expectedPolicies = node.ExpectedPolicies;
+
+ if (expectedPolicies.Contains(pOid.Id))
+ {
+ ISet childExpectedPolicies = new HashSet();
+ childExpectedPolicies.Add(pOid.Id);
+
+ PkixPolicyNode child = new PkixPolicyNode(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(),
+ index,
+ childExpectedPolicies,
+ node,
+ pq,
+ pOid.Id,
+ false);
+ node.AddChild(child);
+ policyNodes[index].Add(child);
+
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ internal static void ProcessCertD1ii(
+ int index,
+ IList[] policyNodes,
+ DerObjectIdentifier _poid,
+ ISet _pq)
+ {
+ IList policyNodeVec = policyNodes[index - 1];
+
+ for (int j = 0; j < policyNodeVec.Count; j++)
+ {
+ PkixPolicyNode _node = (PkixPolicyNode)policyNodeVec[j];
+
+ if (ANY_POLICY.Equals(_node.ValidPolicy))
+ {
+ ISet _childExpectedPolicies = new HashSet();
+ _childExpectedPolicies.Add(_poid.Id);
+
+ PkixPolicyNode _child = new PkixPolicyNode(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(),
+ index,
+ _childExpectedPolicies,
+ _node,
+ _pq,
+ _poid.Id,
+ false);
+ _node.AddChild(_child);
+ policyNodes[index].Add(_child);
+ return;
+ }
+ }
+ }
+
+ /**
+ * Find the issuer certificates of a given certificate.
+ *
+ * @param cert
+ * The certificate for which an issuer should be found.
+ * @param pkixParams
+ * @return A Collection object containing the issuer
+ * X509Certificates. Never null.
+ *
+ * @exception Exception
+ * if an error occurs.
+ */
+ internal static ICollection FindIssuerCerts(
+ X509Certificate cert,
+ PkixBuilderParameters pkixParams)
+ {
+ X509CertStoreSelector certSelect = new X509CertStoreSelector();
+ ISet certs = new HashSet();
+ try
+ {
+ certSelect.Subject = cert.IssuerDN;
+ }
+ catch (IOException ex)
+ {
+ throw new Exception(
+ "Subject criteria for certificate selector to find issuer certificate could not be set.", ex);
+ }
+
+ try
+ {
+ certs.AddAll(PkixCertPathValidatorUtilities.FindCertificates(certSelect, pkixParams.GetStores()));
+ certs.AddAll(PkixCertPathValidatorUtilities.FindCertificates(certSelect, pkixParams.GetAdditionalStores()));
+ }
+ catch (Exception e)
+ {
+ throw new Exception("Issuer certificate cannot be searched.", e);
+ }
+
+ return certs;
+ }
+
+ ///
+ /// Extract the value of the given extension, if it exists.
+ ///
+ /// The extension object.
+ /// The object identifier to obtain.
+ /// Asn1Object
+ /// if the extension cannot be read.
+ internal static Asn1Object GetExtensionValue(
+ IX509Extension ext,
+ DerObjectIdentifier oid)
+ {
+ Asn1OctetString bytes = ext.GetExtensionValue(oid);
+
+ if (bytes == null)
+ return null;
+
+ return X509ExtensionUtilities.FromExtensionValue(bytes);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathValidatorUtilities.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathValidatorUtilities.cs.meta
new file mode 100644
index 00000000..302b0f9b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCertPathValidatorUtilities.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 7825ba3fb6db65f428b313e1641e481b
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCrlUtilities.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCrlUtilities.cs
new file mode 100644
index 00000000..de9bb78c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCrlUtilities.cs
@@ -0,0 +1,118 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix
+{
+ public class PkixCrlUtilities
+ {
+ public virtual ISet FindCrls(X509CrlStoreSelector crlselect, PkixParameters paramsPkix, DateTime currentDate)
+ {
+ ISet initialSet = new HashSet();
+
+ // get complete CRL(s)
+ try
+ {
+ initialSet.AddAll(FindCrls(crlselect, paramsPkix.GetAdditionalStores()));
+ initialSet.AddAll(FindCrls(crlselect, paramsPkix.GetStores()));
+ }
+ catch (Exception e)
+ {
+ throw new Exception("Exception obtaining complete CRLs.", e);
+ }
+
+ ISet finalSet = new HashSet();
+ DateTime validityDate = currentDate;
+
+ if (paramsPkix.Date != null)
+ {
+ validityDate = paramsPkix.Date.Value;
+ }
+
+ // based on RFC 5280 6.3.3
+ foreach (X509Crl crl in initialSet)
+ {
+ if (crl.NextUpdate.Value.CompareTo(validityDate) > 0)
+ {
+ X509Certificate cert = crlselect.CertificateChecking;
+
+ if (cert != null)
+ {
+ if (crl.ThisUpdate.CompareTo(cert.NotAfter) < 0)
+ {
+ finalSet.Add(crl);
+ }
+ }
+ else
+ {
+ finalSet.Add(crl);
+ }
+ }
+ }
+
+ return finalSet;
+ }
+
+ public virtual ISet FindCrls(X509CrlStoreSelector crlselect, PkixParameters paramsPkix)
+ {
+ ISet completeSet = new HashSet();
+
+ // get complete CRL(s)
+ try
+ {
+ completeSet.AddAll(FindCrls(crlselect, paramsPkix.GetStores()));
+ }
+ catch (Exception e)
+ {
+ throw new Exception("Exception obtaining complete CRLs.", e);
+ }
+
+ return completeSet;
+ }
+
+ ///
+ /// crl checking
+ /// Return a Collection of all CRLs found in the X509Store's that are
+ /// matching the crlSelect criteriums.
+ ///
+ /// a {@link X509CRLStoreSelector} object that will be used
+ /// to select the CRLs
+ /// a List containing only {@link org.bouncycastle.x509.X509Store
+ /// X509Store} objects. These are used to search for CRLs
+ /// a Collection of all found {@link X509CRL X509CRL} objects. May be
+ /// empty but never null.
+ ///
+ private ICollection FindCrls(X509CrlStoreSelector crlSelect, IList crlStores)
+ {
+ ISet crls = new HashSet();
+
+ Exception lastException = null;
+ bool foundValidStore = false;
+
+ foreach (IX509Store store in crlStores)
+ {
+ try
+ {
+ crls.AddAll(store.GetMatches(crlSelect));
+ foundValidStore = true;
+ }
+ catch (X509StoreException e)
+ {
+ lastException = new Exception("Exception searching in X.509 CRL store.", e);
+ }
+ }
+
+ if (!foundValidStore && lastException != null)
+ throw lastException;
+
+ return crls;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCrlUtilities.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCrlUtilities.cs.meta
new file mode 100644
index 00000000..38f64aa7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixCrlUtilities.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 7931f13e3f4ffef48a585b19606b249f
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixNameConstraintValidator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixNameConstraintValidator.cs
new file mode 100644
index 00000000..904f31d7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixNameConstraintValidator.cs
@@ -0,0 +1,1943 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix
+{
+ public class PkixNameConstraintValidator
+ {
+ private ISet excludedSubtreesDN = new HashSet();
+
+ private ISet excludedSubtreesDNS = new HashSet();
+
+ private ISet excludedSubtreesEmail = new HashSet();
+
+ private ISet excludedSubtreesURI = new HashSet();
+
+ private ISet excludedSubtreesIP = new HashSet();
+
+ private ISet permittedSubtreesDN;
+
+ private ISet permittedSubtreesDNS;
+
+ private ISet permittedSubtreesEmail;
+
+ private ISet permittedSubtreesURI;
+
+ private ISet permittedSubtreesIP;
+
+ public PkixNameConstraintValidator()
+ {
+ }
+
+ private static bool WithinDNSubtree(
+ Asn1Sequence dns,
+ Asn1Sequence subtree)
+ {
+ if (subtree.Count < 1)
+ {
+ return false;
+ }
+
+ if (subtree.Count > dns.Count)
+ {
+ return false;
+ }
+
+ for (int j = subtree.Count - 1; j >= 0; j--)
+ {
+ if (!(subtree[j].Equals(dns[j])))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ public void CheckPermittedDN(Asn1Sequence dns)
+ //throws PkixNameConstraintValidatorException
+ {
+ CheckPermittedDN(permittedSubtreesDN, dns);
+ }
+
+ public void CheckExcludedDN(Asn1Sequence dns)
+ //throws PkixNameConstraintValidatorException
+ {
+ CheckExcludedDN(excludedSubtreesDN, dns);
+ }
+
+ private void CheckPermittedDN(ISet permitted, Asn1Sequence dns)
+ //throws PkixNameConstraintValidatorException
+ {
+ if (permitted == null)
+ {
+ return;
+ }
+
+ if ((permitted.Count == 0) && dns.Count == 0)
+ {
+ return;
+ }
+
+ IEnumerator it = permitted.GetEnumerator();
+
+ while (it.MoveNext())
+ {
+ Asn1Sequence subtree = (Asn1Sequence)it.Current;
+
+ if (WithinDNSubtree(dns, subtree))
+ {
+ return;
+ }
+ }
+
+ throw new PkixNameConstraintValidatorException(
+ "Subject distinguished name is not from a permitted subtree");
+ }
+
+ private void CheckExcludedDN(ISet excluded, Asn1Sequence dns)
+ //throws PkixNameConstraintValidatorException
+ {
+ if (excluded.IsEmpty)
+ {
+ return;
+ }
+
+ IEnumerator it = excluded.GetEnumerator();
+
+ while (it.MoveNext())
+ {
+ Asn1Sequence subtree = (Asn1Sequence)it.Current;
+
+ if (WithinDNSubtree(dns, subtree))
+ {
+ throw new PkixNameConstraintValidatorException(
+ "Subject distinguished name is from an excluded subtree");
+ }
+ }
+ }
+
+ private ISet IntersectDN(ISet permitted, ISet dns)
+ {
+ ISet intersect = new HashSet();
+ for (IEnumerator it = dns.GetEnumerator(); it.MoveNext(); )
+ {
+ Asn1Sequence dn = Asn1Sequence.GetInstance(((GeneralSubtree)it
+ .Current).Base.Name.ToAsn1Object());
+ if (permitted == null)
+ {
+ if (dn != null)
+ {
+ intersect.Add(dn);
+ }
+ }
+ else
+ {
+ IEnumerator _iter = permitted.GetEnumerator();
+ while (_iter.MoveNext())
+ {
+ Asn1Sequence subtree = (Asn1Sequence)_iter.Current;
+
+ if (WithinDNSubtree(dn, subtree))
+ {
+ intersect.Add(dn);
+ }
+ else if (WithinDNSubtree(subtree, dn))
+ {
+ intersect.Add(subtree);
+ }
+ }
+ }
+ }
+ return intersect;
+ }
+
+ private ISet UnionDN(ISet excluded, Asn1Sequence dn)
+ {
+ if (excluded.IsEmpty)
+ {
+ if (dn == null)
+ {
+ return excluded;
+ }
+ excluded.Add(dn);
+
+ return excluded;
+ }
+ else
+ {
+ ISet intersect = new HashSet();
+
+ IEnumerator it = excluded.GetEnumerator();
+ while (it.MoveNext())
+ {
+ Asn1Sequence subtree = (Asn1Sequence)it.Current;
+
+ if (WithinDNSubtree(dn, subtree))
+ {
+ intersect.Add(subtree);
+ }
+ else if (WithinDNSubtree(subtree, dn))
+ {
+ intersect.Add(dn);
+ }
+ else
+ {
+ intersect.Add(subtree);
+ intersect.Add(dn);
+ }
+ }
+
+ return intersect;
+ }
+ }
+
+ private ISet IntersectEmail(ISet permitted, ISet emails)
+ {
+ ISet intersect = new HashSet();
+ for (IEnumerator it = emails.GetEnumerator(); it.MoveNext(); )
+ {
+ String email = ExtractNameAsString(((GeneralSubtree)it.Current)
+ .Base);
+
+ if (permitted == null)
+ {
+ if (email != null)
+ {
+ intersect.Add(email);
+ }
+ }
+ else
+ {
+ IEnumerator it2 = permitted.GetEnumerator();
+ while (it2.MoveNext())
+ {
+ String _permitted = (String)it2.Current;
+
+ intersectEmail(email, _permitted, intersect);
+ }
+ }
+ }
+ return intersect;
+ }
+
+ private ISet UnionEmail(ISet excluded, String email)
+ {
+ if (excluded.IsEmpty)
+ {
+ if (email == null)
+ {
+ return excluded;
+ }
+ excluded.Add(email);
+ return excluded;
+ }
+ else
+ {
+ ISet union = new HashSet();
+
+ IEnumerator it = excluded.GetEnumerator();
+ while (it.MoveNext())
+ {
+ String _excluded = (String)it.Current;
+
+ unionEmail(_excluded, email, union);
+ }
+
+ return union;
+ }
+ }
+
+ /**
+ * Returns the intersection of the permitted IP ranges in
+ * permitted with ip.
+ *
+ * @param permitted A Set of permitted IP addresses with
+ * their subnet mask as byte arrays.
+ * @param ips The IP address with its subnet mask.
+ * @return The Set of permitted IP ranges intersected with
+ * ip.
+ */
+ private ISet IntersectIP(ISet permitted, ISet ips)
+ {
+ ISet intersect = new HashSet();
+ for (IEnumerator it = ips.GetEnumerator(); it.MoveNext(); )
+ {
+ byte[] ip = Asn1OctetString.GetInstance(
+ ((GeneralSubtree)it.Current).Base.Name).GetOctets();
+ if (permitted == null)
+ {
+ if (ip != null)
+ {
+ intersect.Add(ip);
+ }
+ }
+ else
+ {
+ IEnumerator it2 = permitted.GetEnumerator();
+ while (it2.MoveNext())
+ {
+ byte[] _permitted = (byte[])it2.Current;
+ intersect.AddAll(IntersectIPRange(_permitted, ip));
+ }
+ }
+ }
+ return intersect;
+ }
+
+ /**
+ * Returns the union of the excluded IP ranges in excluded
+ * with ip.
+ *
+ * @param excluded A Set of excluded IP addresses with their
+ * subnet mask as byte arrays.
+ * @param ip The IP address with its subnet mask.
+ * @return The Set of excluded IP ranges unified with
+ * ip as byte arrays.
+ */
+ private ISet UnionIP(ISet excluded, byte[] ip)
+ {
+ if (excluded.IsEmpty)
+ {
+ if (ip == null)
+ {
+ return excluded;
+ }
+ excluded.Add(ip);
+
+ return excluded;
+ }
+ else
+ {
+ ISet union = new HashSet();
+
+ IEnumerator it = excluded.GetEnumerator();
+ while (it.MoveNext())
+ {
+ byte[] _excluded = (byte[])it.Current;
+ union.AddAll(UnionIPRange(_excluded, ip));
+ }
+
+ return union;
+ }
+ }
+
+ /**
+ * Calculates the union if two IP ranges.
+ *
+ * @param ipWithSubmask1 The first IP address with its subnet mask.
+ * @param ipWithSubmask2 The second IP address with its subnet mask.
+ * @return A Set with the union of both addresses.
+ */
+ private ISet UnionIPRange(byte[] ipWithSubmask1, byte[] ipWithSubmask2)
+ {
+ ISet set = new HashSet();
+
+ // difficult, adding always all IPs is not wrong
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Arrays.AreEqual(ipWithSubmask1, ipWithSubmask2))
+ {
+ set.Add(ipWithSubmask1);
+ }
+ else
+ {
+ set.Add(ipWithSubmask1);
+ set.Add(ipWithSubmask2);
+ }
+ return set;
+ }
+
+ /**
+ * Calculates the interesction if two IP ranges.
+ *
+ * @param ipWithSubmask1 The first IP address with its subnet mask.
+ * @param ipWithSubmask2 The second IP address with its subnet mask.
+ * @return A Set with the single IP address with its subnet
+ * mask as a byte array or an empty Set.
+ */
+ private ISet IntersectIPRange(byte[] ipWithSubmask1, byte[] ipWithSubmask2)
+ {
+ if (ipWithSubmask1.Length != ipWithSubmask2.Length)
+ {
+ //Collections.EMPTY_SET;
+ return new HashSet();
+ }
+
+ byte[][] temp = ExtractIPsAndSubnetMasks(ipWithSubmask1, ipWithSubmask2);
+ byte[] ip1 = temp[0];
+ byte[] subnetmask1 = temp[1];
+ byte[] ip2 = temp[2];
+ byte[] subnetmask2 = temp[3];
+
+ byte[][] minMax = MinMaxIPs(ip1, subnetmask1, ip2, subnetmask2);
+ byte[] min;
+ byte[] max;
+ max = Min(minMax[1], minMax[3]);
+ min = Max(minMax[0], minMax[2]);
+
+ // minimum IP address must be bigger than max
+ if (CompareTo(min, max) == 1)
+ {
+ //return Collections.EMPTY_SET;
+ return new HashSet();
+ }
+ // OR keeps all significant bits
+ byte[] ip = Or(minMax[0], minMax[2]);
+ byte[] subnetmask = Or(subnetmask1, subnetmask2);
+
+ //return new HashSet( ICollectionsingleton(IpWithSubnetMask(ip, subnetmask));
+ ISet hs = new HashSet();
+ hs.Add(IpWithSubnetMask(ip, subnetmask));
+
+ return hs;
+ }
+
+ /**
+ * Concatenates the IP address with its subnet mask.
+ *
+ * @param ip The IP address.
+ * @param subnetMask Its subnet mask.
+ * @return The concatenated IP address with its subnet mask.
+ */
+ private byte[] IpWithSubnetMask(byte[] ip, byte[] subnetMask)
+ {
+ int ipLength = ip.Length;
+ byte[] temp = new byte[ipLength * 2];
+ Array.Copy(ip, 0, temp, 0, ipLength);
+ Array.Copy(subnetMask, 0, temp, ipLength, ipLength);
+ return temp;
+ }
+
+ /**
+ * Splits the IP addresses and their subnet mask.
+ *
+ * @param ipWithSubmask1 The first IP address with the subnet mask.
+ * @param ipWithSubmask2 The second IP address with the subnet mask.
+ * @return An array with two elements. Each element contains the IP address
+ * and the subnet mask in this order.
+ */
+ private byte[][] ExtractIPsAndSubnetMasks(
+ byte[] ipWithSubmask1,
+ byte[] ipWithSubmask2)
+ {
+ int ipLength = ipWithSubmask1.Length / 2;
+ byte[] ip1 = new byte[ipLength];
+ byte[] subnetmask1 = new byte[ipLength];
+ Array.Copy(ipWithSubmask1, 0, ip1, 0, ipLength);
+ Array.Copy(ipWithSubmask1, ipLength, subnetmask1, 0, ipLength);
+
+ byte[] ip2 = new byte[ipLength];
+ byte[] subnetmask2 = new byte[ipLength];
+ Array.Copy(ipWithSubmask2, 0, ip2, 0, ipLength);
+ Array.Copy(ipWithSubmask2, ipLength, subnetmask2, 0, ipLength);
+ return new byte[][]
+ {ip1, subnetmask1, ip2, subnetmask2};
+ }
+
+ /**
+ * Based on the two IP addresses and their subnet masks the IP range is
+ * computed for each IP address - subnet mask pair and returned as the
+ * minimum IP address and the maximum address of the range.
+ *
+ * @param ip1 The first IP address.
+ * @param subnetmask1 The subnet mask of the first IP address.
+ * @param ip2 The second IP address.
+ * @param subnetmask2 The subnet mask of the second IP address.
+ * @return A array with two elements. The first/second element contains the
+ * min and max IP address of the first/second IP address and its
+ * subnet mask.
+ */
+ private byte[][] MinMaxIPs(
+ byte[] ip1,
+ byte[] subnetmask1,
+ byte[] ip2,
+ byte[] subnetmask2)
+ {
+ int ipLength = ip1.Length;
+ byte[] min1 = new byte[ipLength];
+ byte[] max1 = new byte[ipLength];
+
+ byte[] min2 = new byte[ipLength];
+ byte[] max2 = new byte[ipLength];
+
+ for (int i = 0; i < ipLength; i++)
+ {
+ min1[i] = (byte)(ip1[i] & subnetmask1[i]);
+ max1[i] = (byte)(ip1[i] & subnetmask1[i] | ~subnetmask1[i]);
+
+ min2[i] = (byte)(ip2[i] & subnetmask2[i]);
+ max2[i] = (byte)(ip2[i] & subnetmask2[i] | ~subnetmask2[i]);
+ }
+
+ return new byte[][] { min1, max1, min2, max2 };
+ }
+
+ private void CheckPermittedEmail(ISet permitted, String email)
+ //throws PkixNameConstraintValidatorException
+ {
+ if (permitted == null)
+ {
+ return;
+ }
+
+ IEnumerator it = permitted.GetEnumerator();
+
+ while (it.MoveNext())
+ {
+ String str = ((String)it.Current);
+
+ if (EmailIsConstrained(email, str))
+ {
+ return;
+ }
+ }
+
+ if (email.Length == 0 && permitted.Count == 0)
+ {
+ return;
+ }
+
+ throw new PkixNameConstraintValidatorException(
+ "Subject email address is not from a permitted subtree.");
+ }
+
+ private void CheckExcludedEmail(ISet excluded, String email)
+ //throws PkixNameConstraintValidatorException
+ {
+ if (excluded.IsEmpty)
+ {
+ return;
+ }
+
+ IEnumerator it = excluded.GetEnumerator();
+
+ while (it.MoveNext())
+ {
+ String str = (String)it.Current;
+
+ if (EmailIsConstrained(email, str))
+ {
+ throw new PkixNameConstraintValidatorException(
+ "Email address is from an excluded subtree.");
+ }
+ }
+ }
+
+ /**
+ * Checks if the IP ip is included in the permitted ISet
+ * permitted.
+ *
+ * @param permitted A Set of permitted IP addresses with
+ * their subnet mask as byte arrays.
+ * @param ip The IP address.
+ * @throws PkixNameConstraintValidatorException
+ * if the IP is not permitted.
+ */
+ private void CheckPermittedIP(ISet permitted, byte[] ip)
+ //throws PkixNameConstraintValidatorException
+ {
+ if (permitted == null)
+ {
+ return;
+ }
+
+ IEnumerator it = permitted.GetEnumerator();
+
+ while (it.MoveNext())
+ {
+ byte[] ipWithSubnet = (byte[])it.Current;
+
+ if (IsIPConstrained(ip, ipWithSubnet))
+ {
+ return;
+ }
+ }
+ if (ip.Length == 0 && permitted.Count == 0)
+ {
+ return;
+ }
+ throw new PkixNameConstraintValidatorException(
+ "IP is not from a permitted subtree.");
+ }
+
+ /**
+ * Checks if the IP ip is included in the excluded ISet
+ * excluded.
+ *
+ * @param excluded A Set of excluded IP addresses with their
+ * subnet mask as byte arrays.
+ * @param ip The IP address.
+ * @throws PkixNameConstraintValidatorException
+ * if the IP is excluded.
+ */
+ private void checkExcludedIP(ISet excluded, byte[] ip)
+ //throws PkixNameConstraintValidatorException
+ {
+ if (excluded.IsEmpty)
+ {
+ return;
+ }
+
+ IEnumerator it = excluded.GetEnumerator();
+
+ while (it.MoveNext())
+ {
+ byte[] ipWithSubnet = (byte[])it.Current;
+
+ if (IsIPConstrained(ip, ipWithSubnet))
+ {
+ throw new PkixNameConstraintValidatorException(
+ "IP is from an excluded subtree.");
+ }
+ }
+ }
+
+ /**
+ * Checks if the IP address ip is constrained by
+ * constraint.
+ *
+ * @param ip The IP address.
+ * @param constraint The constraint. This is an IP address concatenated with
+ * its subnetmask.
+ * @return true if constrained, false
+ * otherwise.
+ */
+ private bool IsIPConstrained(byte[] ip, byte[] constraint)
+ {
+ int ipLength = ip.Length;
+
+ if (ipLength != (constraint.Length / 2))
+ {
+ return false;
+ }
+
+ byte[] subnetMask = new byte[ipLength];
+ Array.Copy(constraint, ipLength, subnetMask, 0, ipLength);
+
+ byte[] permittedSubnetAddress = new byte[ipLength];
+
+ byte[] ipSubnetAddress = new byte[ipLength];
+
+ // the resulting IP address by applying the subnet mask
+ for (int i = 0; i < ipLength; i++)
+ {
+ permittedSubnetAddress[i] = (byte)(constraint[i] & subnetMask[i]);
+ ipSubnetAddress[i] = (byte)(ip[i] & subnetMask[i]);
+ }
+
+ return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Arrays.AreEqual(permittedSubnetAddress, ipSubnetAddress);
+ }
+
+ private bool EmailIsConstrained(String email, String constraint)
+ {
+ String sub = email.Substring(email.IndexOf('@') + 1);
+ // a particular mailbox
+ if (constraint.IndexOf('@') != -1)
+ {
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(email).Equals(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(constraint)))
+ {
+ return true;
+ }
+ }
+ // on particular host
+ else if (!(constraint[0].Equals('.')))
+ {
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(sub).Equals(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(constraint)))
+ {
+ return true;
+ }
+ }
+ // address in sub domain
+ else if (WithinDomain(sub, constraint))
+ {
+ return true;
+ }
+ return false;
+ }
+
+ private bool WithinDomain(String testDomain, String domain)
+ {
+ String tempDomain = domain;
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(tempDomain, "."))
+ {
+ tempDomain = tempDomain.Substring(1);
+ }
+ String[] domainParts = tempDomain.Split('.'); // Strings.split(tempDomain, '.');
+ String[] testDomainParts = testDomain.Split('.'); // Strings.split(testDomain, '.');
+
+ // must have at least one subdomain
+ if (testDomainParts.Length <= domainParts.Length)
+ {
+ return false;
+ }
+
+ int d = testDomainParts.Length - domainParts.Length;
+ for (int i = -1; i < domainParts.Length; i++)
+ {
+ if (i == -1)
+ {
+ if (testDomainParts[i + d].Equals(""))
+ {
+ return false;
+ }
+ }
+ else if (!BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(testDomainParts[i + d], domainParts[i]))
+ {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private void CheckPermittedDNS(ISet permitted, String dns)
+ //throws PkixNameConstraintValidatorException
+ {
+ if (permitted == null)
+ {
+ return;
+ }
+
+ IEnumerator it = permitted.GetEnumerator();
+
+ while (it.MoveNext())
+ {
+ String str = ((String)it.Current);
+
+ // is sub domain
+ if (WithinDomain(dns, str)
+ || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(dns).Equals(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(str)))
+ {
+ return;
+ }
+ }
+ if (dns.Length == 0 && permitted.Count == 0)
+ {
+ return;
+ }
+ throw new PkixNameConstraintValidatorException(
+ "DNS is not from a permitted subtree.");
+ }
+
+ private void checkExcludedDNS(ISet excluded, String dns)
+ // throws PkixNameConstraintValidatorException
+ {
+ if (excluded.IsEmpty)
+ {
+ return;
+ }
+
+ IEnumerator it = excluded.GetEnumerator();
+
+ while (it.MoveNext())
+ {
+ String str = ((String)it.Current);
+
+ // is sub domain or the same
+ if (WithinDomain(dns, str) || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(dns, str))
+ {
+ throw new PkixNameConstraintValidatorException(
+ "DNS is from an excluded subtree.");
+ }
+ }
+ }
+
+ /**
+ * The common part of email1 and email2 is
+ * added to the union union. If email1 and
+ * email2 have nothing in common they are added both.
+ *
+ * @param email1 Email address constraint 1.
+ * @param email2 Email address constraint 2.
+ * @param union The union.
+ */
+ private void unionEmail(String email1, String email2, ISet union)
+ {
+ // email1 is a particular address
+ if (email1.IndexOf('@') != -1)
+ {
+ String _sub = email1.Substring(email1.IndexOf('@') + 1);
+ // both are a particular mailbox
+ if (email2.IndexOf('@') != -1)
+ {
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2))
+ {
+ union.Add(email1);
+ }
+ else
+ {
+ union.Add(email1);
+ union.Add(email2);
+ }
+ }
+ // email2 specifies a domain
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, "."))
+ {
+ if (WithinDomain(_sub, email2))
+ {
+ union.Add(email2);
+ }
+ else
+ {
+ union.Add(email1);
+ union.Add(email2);
+ }
+ }
+ // email2 specifies a particular host
+ else
+ {
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email2))
+ {
+ union.Add(email2);
+ }
+ else
+ {
+ union.Add(email1);
+ union.Add(email2);
+ }
+ }
+ }
+ // email1 specifies a domain
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email1, "."))
+ {
+ if (email2.IndexOf('@') != -1)
+ {
+ String _sub = email2.Substring(email1.IndexOf('@') + 1);
+ if (WithinDomain(_sub, email1))
+ {
+ union.Add(email1);
+ }
+ else
+ {
+ union.Add(email1);
+ union.Add(email2);
+ }
+ }
+ // email2 specifies a domain
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, "."))
+ {
+ if (WithinDomain(email1, email2) || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2))
+ {
+ union.Add(email2);
+ }
+ else if (WithinDomain(email2, email1))
+ {
+ union.Add(email1);
+ }
+ else
+ {
+ union.Add(email1);
+ union.Add(email2);
+ }
+ }
+ else
+ {
+ if (WithinDomain(email2, email1))
+ {
+ union.Add(email1);
+ }
+ else
+ {
+ union.Add(email1);
+ union.Add(email2);
+ }
+ }
+ }
+ // email specifies a host
+ else
+ {
+ if (email2.IndexOf('@') != -1)
+ {
+ String _sub = email2.Substring(email1.IndexOf('@') + 1);
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email1))
+ {
+ union.Add(email1);
+ }
+ else
+ {
+ union.Add(email1);
+ union.Add(email2);
+ }
+ }
+ // email2 specifies a domain
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, "."))
+ {
+ if (WithinDomain(email1, email2))
+ {
+ union.Add(email2);
+ }
+ else
+ {
+ union.Add(email1);
+ union.Add(email2);
+ }
+ }
+ // email2 specifies a particular host
+ else
+ {
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2))
+ {
+ union.Add(email1);
+ }
+ else
+ {
+ union.Add(email1);
+ union.Add(email2);
+ }
+ }
+ }
+ }
+
+ private void unionURI(String email1, String email2, ISet union)
+ {
+ // email1 is a particular address
+ if (email1.IndexOf('@') != -1)
+ {
+ String _sub = email1.Substring(email1.IndexOf('@') + 1);
+ // both are a particular mailbox
+ if (email2.IndexOf('@') != -1)
+ {
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2))
+ {
+ union.Add(email1);
+ }
+ else
+ {
+ union.Add(email1);
+ union.Add(email2);
+ }
+ }
+ // email2 specifies a domain
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, "."))
+ {
+ if (WithinDomain(_sub, email2))
+ {
+ union.Add(email2);
+ }
+ else
+ {
+ union.Add(email1);
+ union.Add(email2);
+ }
+ }
+ // email2 specifies a particular host
+ else
+ {
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email2))
+ {
+ union.Add(email2);
+ }
+ else
+ {
+ union.Add(email1);
+ union.Add(email2);
+
+ }
+ }
+ }
+ // email1 specifies a domain
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email1, "."))
+ {
+ if (email2.IndexOf('@') != -1)
+ {
+ String _sub = email2.Substring(email1.IndexOf('@') + 1);
+ if (WithinDomain(_sub, email1))
+ {
+ union.Add(email1);
+ }
+ else
+ {
+ union.Add(email1);
+ union.Add(email2);
+ }
+ }
+ // email2 specifies a domain
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, "."))
+ {
+ if (WithinDomain(email1, email2) || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2))
+ {
+ union.Add(email2);
+ }
+ else if (WithinDomain(email2, email1))
+ {
+ union.Add(email1);
+ }
+ else
+ {
+ union.Add(email1);
+ union.Add(email2);
+ }
+ }
+ else
+ {
+ if (WithinDomain(email2, email1))
+ {
+ union.Add(email1);
+ }
+ else
+ {
+ union.Add(email1);
+ union.Add(email2);
+ }
+ }
+ }
+ // email specifies a host
+ else
+ {
+ if (email2.IndexOf('@') != -1)
+ {
+ String _sub = email2.Substring(email1.IndexOf('@') + 1);
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email1))
+ {
+ union.Add(email1);
+ }
+ else
+ {
+ union.Add(email1);
+ union.Add(email2);
+ }
+ }
+ // email2 specifies a domain
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, "."))
+ {
+ if (WithinDomain(email1, email2))
+ {
+ union.Add(email2);
+ }
+ else
+ {
+ union.Add(email1);
+ union.Add(email2);
+ }
+ }
+ // email2 specifies a particular host
+ else
+ {
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2))
+ {
+ union.Add(email1);
+ }
+ else
+ {
+ union.Add(email1);
+ union.Add(email2);
+ }
+ }
+ }
+ }
+
+ private ISet intersectDNS(ISet permitted, ISet dnss)
+ {
+ ISet intersect = new HashSet();
+ for (IEnumerator it = dnss.GetEnumerator(); it.MoveNext(); )
+ {
+ String dns = ExtractNameAsString(((GeneralSubtree)it.Current)
+ .Base);
+ if (permitted == null)
+ {
+ if (dns != null)
+ {
+ intersect.Add(dns);
+ }
+ }
+ else
+ {
+ IEnumerator _iter = permitted.GetEnumerator();
+ while (_iter.MoveNext())
+ {
+ String _permitted = (String)_iter.Current;
+
+ if (WithinDomain(_permitted, dns))
+ {
+ intersect.Add(_permitted);
+ }
+ else if (WithinDomain(dns, _permitted))
+ {
+ intersect.Add(dns);
+ }
+ }
+ }
+ }
+
+ return intersect;
+ }
+
+ protected ISet unionDNS(ISet excluded, String dns)
+ {
+ if (excluded.IsEmpty)
+ {
+ if (dns == null)
+ {
+ return excluded;
+ }
+ excluded.Add(dns);
+
+ return excluded;
+ }
+ else
+ {
+ ISet union = new HashSet();
+
+ IEnumerator _iter = excluded.GetEnumerator();
+ while (_iter.MoveNext())
+ {
+ String _permitted = (String)_iter.Current;
+
+ if (WithinDomain(_permitted, dns))
+ {
+ union.Add(dns);
+ }
+ else if (WithinDomain(dns, _permitted))
+ {
+ union.Add(_permitted);
+ }
+ else
+ {
+ union.Add(_permitted);
+ union.Add(dns);
+ }
+ }
+
+ return union;
+ }
+ }
+
+ /**
+ * The most restricting part from email1 and
+ * email2 is added to the intersection intersect.
+ *
+ * @param email1 Email address constraint 1.
+ * @param email2 Email address constraint 2.
+ * @param intersect The intersection.
+ */
+ private void intersectEmail(String email1, String email2, ISet intersect)
+ {
+ // email1 is a particular address
+ if (email1.IndexOf('@') != -1)
+ {
+ String _sub = email1.Substring(email1.IndexOf('@') + 1);
+ // both are a particular mailbox
+ if (email2.IndexOf('@') != -1)
+ {
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2))
+ {
+ intersect.Add(email1);
+ }
+ }
+ // email2 specifies a domain
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, "."))
+ {
+ if (WithinDomain(_sub, email2))
+ {
+ intersect.Add(email1);
+ }
+ }
+ // email2 specifies a particular host
+ else
+ {
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email2))
+ {
+ intersect.Add(email1);
+ }
+ }
+ }
+ // email specifies a domain
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email1, "."))
+ {
+ if (email2.IndexOf('@') != -1)
+ {
+ String _sub = email2.Substring(email1.IndexOf('@') + 1);
+ if (WithinDomain(_sub, email1))
+ {
+ intersect.Add(email2);
+ }
+ }
+ // email2 specifies a domain
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, "."))
+ {
+ if (WithinDomain(email1, email2) || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2))
+ {
+ intersect.Add(email1);
+ }
+ else if (WithinDomain(email2, email1))
+ {
+ intersect.Add(email2);
+ }
+ }
+ else
+ {
+ if (WithinDomain(email2, email1))
+ {
+ intersect.Add(email2);
+ }
+ }
+ }
+ // email1 specifies a host
+ else
+ {
+ if (email2.IndexOf('@') != -1)
+ {
+ String _sub = email2.Substring(email2.IndexOf('@') + 1);
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email1))
+ {
+ intersect.Add(email2);
+ }
+ }
+ // email2 specifies a domain
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, "."))
+ {
+ if (WithinDomain(email1, email2))
+ {
+ intersect.Add(email1);
+ }
+ }
+ // email2 specifies a particular host
+ else
+ {
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2))
+ {
+ intersect.Add(email1);
+ }
+ }
+ }
+ }
+
+ private void checkExcludedURI(ISet excluded, String uri)
+ // throws PkixNameConstraintValidatorException
+ {
+ if (excluded.IsEmpty)
+ {
+ return;
+ }
+
+ IEnumerator it = excluded.GetEnumerator();
+
+ while (it.MoveNext())
+ {
+ String str = ((String)it.Current);
+
+ if (IsUriConstrained(uri, str))
+ {
+ throw new PkixNameConstraintValidatorException(
+ "URI is from an excluded subtree.");
+ }
+ }
+ }
+
+ private ISet intersectURI(ISet permitted, ISet uris)
+ {
+ ISet intersect = new HashSet();
+ for (IEnumerator it = uris.GetEnumerator(); it.MoveNext(); )
+ {
+ String uri = ExtractNameAsString(((GeneralSubtree)it.Current)
+ .Base);
+ if (permitted == null)
+ {
+ if (uri != null)
+ {
+ intersect.Add(uri);
+ }
+ }
+ else
+ {
+ IEnumerator _iter = permitted.GetEnumerator();
+ while (_iter.MoveNext())
+ {
+ String _permitted = (String)_iter.Current;
+ intersectURI(_permitted, uri, intersect);
+ }
+ }
+ }
+ return intersect;
+ }
+
+ private ISet unionURI(ISet excluded, String uri)
+ {
+ if (excluded.IsEmpty)
+ {
+ if (uri == null)
+ {
+ return excluded;
+ }
+ excluded.Add(uri);
+
+ return excluded;
+ }
+ else
+ {
+ ISet union = new HashSet();
+
+ IEnumerator _iter = excluded.GetEnumerator();
+ while (_iter.MoveNext())
+ {
+ String _excluded = (String)_iter.Current;
+
+ unionURI(_excluded, uri, union);
+ }
+
+ return union;
+ }
+ }
+
+ private void intersectURI(String email1, String email2, ISet intersect)
+ {
+ // email1 is a particular address
+ if (email1.IndexOf('@') != -1)
+ {
+ String _sub = email1.Substring(email1.IndexOf('@') + 1);
+ // both are a particular mailbox
+ if (email2.IndexOf('@') != -1)
+ {
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2))
+ {
+ intersect.Add(email1);
+ }
+ }
+ // email2 specifies a domain
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, "."))
+ {
+ if (WithinDomain(_sub, email2))
+ {
+ intersect.Add(email1);
+ }
+ }
+ // email2 specifies a particular host
+ else
+ {
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email2))
+ {
+ intersect.Add(email1);
+ }
+ }
+ }
+ // email specifies a domain
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email1, "."))
+ {
+ if (email2.IndexOf('@') != -1)
+ {
+ String _sub = email2.Substring(email1.IndexOf('@') + 1);
+ if (WithinDomain(_sub, email1))
+ {
+ intersect.Add(email2);
+ }
+ }
+ // email2 specifies a domain
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, "."))
+ {
+ if (WithinDomain(email1, email2) || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2))
+ {
+ intersect.Add(email1);
+ }
+ else if (WithinDomain(email2, email1))
+ {
+ intersect.Add(email2);
+ }
+ }
+ else
+ {
+ if (WithinDomain(email2, email1))
+ {
+ intersect.Add(email2);
+ }
+ }
+ }
+ // email1 specifies a host
+ else
+ {
+ if (email2.IndexOf('@') != -1)
+ {
+ String _sub = email2.Substring(email2.IndexOf('@') + 1);
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email1))
+ {
+ intersect.Add(email2);
+ }
+ }
+ // email2 specifies a domain
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, "."))
+ {
+ if (WithinDomain(email1, email2))
+ {
+ intersect.Add(email1);
+ }
+ }
+ // email2 specifies a particular host
+ else
+ {
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2))
+ {
+ intersect.Add(email1);
+ }
+ }
+ }
+ }
+
+ private void CheckPermittedURI(ISet permitted, String uri)
+ // throws PkixNameConstraintValidatorException
+ {
+ if (permitted == null)
+ {
+ return;
+ }
+
+ IEnumerator it = permitted.GetEnumerator();
+
+ while (it.MoveNext())
+ {
+ String str = ((String)it.Current);
+
+ if (IsUriConstrained(uri, str))
+ {
+ return;
+ }
+ }
+ if (uri.Length == 0 && permitted.Count == 0)
+ {
+ return;
+ }
+ throw new PkixNameConstraintValidatorException(
+ "URI is not from a permitted subtree.");
+ }
+
+ private bool IsUriConstrained(String uri, String constraint)
+ {
+ String host = ExtractHostFromURL(uri);
+ // a host
+ if (!BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(constraint, "."))
+ {
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(host, constraint))
+ {
+ return true;
+ }
+ }
+
+ // in sub domain or domain
+ else if (WithinDomain(host, constraint))
+ {
+ return true;
+ }
+
+ return false;
+ }
+
+ private static String ExtractHostFromURL(String url)
+ {
+ // see RFC 1738
+ // remove ':' after protocol, e.g. http:
+ String sub = url.Substring(url.IndexOf(':') + 1);
+ // extract host from Common Internet Scheme Syntax, e.g. http://
+ int idxOfSlashes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.IndexOf(sub, "//");
+ if (idxOfSlashes != -1)
+ {
+ sub = sub.Substring(idxOfSlashes + 2);
+ }
+ // first remove port, e.g. http://test.com:21
+ if (sub.LastIndexOf(':') != -1)
+ {
+ sub = sub.Substring(0, sub.LastIndexOf(':'));
+ }
+ // remove user and password, e.g. http://john:password@test.com
+ sub = sub.Substring(sub.IndexOf(':') + 1);
+ sub = sub.Substring(sub.IndexOf('@') + 1);
+ // remove local parts, e.g. http://test.com/bla
+ if (sub.IndexOf('/') != -1)
+ {
+ sub = sub.Substring(0, sub.IndexOf('/'));
+ }
+ return sub;
+ }
+
+ /**
+ * Checks if the given GeneralName is in the permitted ISet.
+ *
+ * @param name The GeneralName
+ * @throws PkixNameConstraintValidatorException
+ * If the name
+ */
+ public void checkPermitted(GeneralName name)
+ // throws PkixNameConstraintValidatorException
+ {
+ switch (name.TagNo)
+ {
+ case 1:
+ CheckPermittedEmail(permittedSubtreesEmail,
+ ExtractNameAsString(name));
+ break;
+ case 2:
+ CheckPermittedDNS(permittedSubtreesDNS, DerIA5String.GetInstance(
+ name.Name).GetString());
+ break;
+ case 4:
+ CheckPermittedDN(Asn1Sequence.GetInstance(name.Name.ToAsn1Object()));
+ break;
+ case 6:
+ CheckPermittedURI(permittedSubtreesURI, DerIA5String.GetInstance(
+ name.Name).GetString());
+ break;
+ case 7:
+ byte[] ip = Asn1OctetString.GetInstance(name.Name).GetOctets();
+
+ CheckPermittedIP(permittedSubtreesIP, ip);
+ break;
+ }
+ }
+
+ /**
+ * Check if the given GeneralName is contained in the excluded ISet.
+ *
+ * @param name The GeneralName.
+ * @throws PkixNameConstraintValidatorException
+ * If the name is
+ * excluded.
+ */
+ public void checkExcluded(GeneralName name)
+ // throws PkixNameConstraintValidatorException
+ {
+ switch (name.TagNo)
+ {
+ case 1:
+ CheckExcludedEmail(excludedSubtreesEmail, ExtractNameAsString(name));
+ break;
+ case 2:
+ checkExcludedDNS(excludedSubtreesDNS, DerIA5String.GetInstance(
+ name.Name).GetString());
+ break;
+ case 4:
+ CheckExcludedDN(Asn1Sequence.GetInstance(name.Name.ToAsn1Object()));
+ break;
+ case 6:
+ checkExcludedURI(excludedSubtreesURI, DerIA5String.GetInstance(
+ name.Name).GetString());
+ break;
+ case 7:
+ byte[] ip = Asn1OctetString.GetInstance(name.Name).GetOctets();
+
+ checkExcludedIP(excludedSubtreesIP, ip);
+ break;
+ }
+ }
+
+ /**
+ * Updates the permitted ISet of these name constraints with the intersection
+ * with the given subtree.
+ *
+ * @param permitted The permitted subtrees
+ */
+
+ public void IntersectPermittedSubtree(Asn1Sequence permitted)
+ {
+ IDictionary subtreesMap = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+
+ // group in ISets in a map ordered by tag no.
+ for (IEnumerator e = permitted.GetEnumerator(); e.MoveNext(); )
+ {
+ GeneralSubtree subtree = GeneralSubtree.GetInstance(e.Current);
+
+ int tagNo = subtree.Base.TagNo;
+ if (subtreesMap[tagNo] == null)
+ {
+ subtreesMap[tagNo] = new HashSet();
+ }
+
+ ((ISet)subtreesMap[tagNo]).Add(subtree);
+ }
+
+ for (IEnumerator it = subtreesMap.GetEnumerator(); it.MoveNext(); )
+ {
+ DictionaryEntry entry = (DictionaryEntry)it.Current;
+
+ // go through all subtree groups
+ switch ((int)entry.Key )
+ {
+ case 1:
+ permittedSubtreesEmail = IntersectEmail(permittedSubtreesEmail,
+ (ISet)entry.Value);
+ break;
+ case 2:
+ permittedSubtreesDNS = intersectDNS(permittedSubtreesDNS,
+ (ISet)entry.Value);
+ break;
+ case 4:
+ permittedSubtreesDN = IntersectDN(permittedSubtreesDN,
+ (ISet)entry.Value);
+ break;
+ case 6:
+ permittedSubtreesURI = intersectURI(permittedSubtreesURI,
+ (ISet)entry.Value);
+ break;
+ case 7:
+ permittedSubtreesIP = IntersectIP(permittedSubtreesIP,
+ (ISet)entry.Value);
+ break;
+ }
+ }
+ }
+
+ private String ExtractNameAsString(GeneralName name)
+ {
+ return DerIA5String.GetInstance(name.Name).GetString();
+ }
+
+ public void IntersectEmptyPermittedSubtree(int nameType)
+ {
+ switch (nameType)
+ {
+ case 1:
+ permittedSubtreesEmail = new HashSet();
+ break;
+ case 2:
+ permittedSubtreesDNS = new HashSet();
+ break;
+ case 4:
+ permittedSubtreesDN = new HashSet();
+ break;
+ case 6:
+ permittedSubtreesURI = new HashSet();
+ break;
+ case 7:
+ permittedSubtreesIP = new HashSet();
+ break;
+ }
+ }
+
+ /**
+ * Adds a subtree to the excluded ISet of these name constraints.
+ *
+ * @param subtree A subtree with an excluded GeneralName.
+ */
+ public void AddExcludedSubtree(GeneralSubtree subtree)
+ {
+ GeneralName subTreeBase = subtree.Base;
+
+ switch (subTreeBase.TagNo)
+ {
+ case 1:
+ excludedSubtreesEmail = UnionEmail(excludedSubtreesEmail,
+ ExtractNameAsString(subTreeBase));
+ break;
+ case 2:
+ excludedSubtreesDNS = unionDNS(excludedSubtreesDNS,
+ ExtractNameAsString(subTreeBase));
+ break;
+ case 4:
+ excludedSubtreesDN = UnionDN(excludedSubtreesDN,
+ (Asn1Sequence)subTreeBase.Name.ToAsn1Object());
+ break;
+ case 6:
+ excludedSubtreesURI = unionURI(excludedSubtreesURI,
+ ExtractNameAsString(subTreeBase));
+ break;
+ case 7:
+ excludedSubtreesIP = UnionIP(excludedSubtreesIP, Asn1OctetString
+ .GetInstance(subTreeBase.Name).GetOctets());
+ break;
+ }
+ }
+
+ /**
+ * Returns the maximum IP address.
+ *
+ * @param ip1 The first IP address.
+ * @param ip2 The second IP address.
+ * @return The maximum IP address.
+ */
+ private static byte[] Max(byte[] ip1, byte[] ip2)
+ {
+ for (int i = 0; i < ip1.Length; i++)
+ {
+ if ((ip1[i] & 0xFFFF) > (ip2[i] & 0xFFFF))
+ {
+ return ip1;
+ }
+ }
+ return ip2;
+ }
+
+ /**
+ * Returns the minimum IP address.
+ *
+ * @param ip1 The first IP address.
+ * @param ip2 The second IP address.
+ * @return The minimum IP address.
+ */
+ private static byte[] Min(byte[] ip1, byte[] ip2)
+ {
+ for (int i = 0; i < ip1.Length; i++)
+ {
+ if ((ip1[i] & 0xFFFF) < (ip2[i] & 0xFFFF))
+ {
+ return ip1;
+ }
+ }
+ return ip2;
+ }
+
+ /**
+ * Compares IP address ip1 with ip2. If ip1
+ * is equal to ip2 0 is returned. If ip1 is bigger 1 is returned, -1
+ * otherwise.
+ *
+ * @param ip1 The first IP address.
+ * @param ip2 The second IP address.
+ * @return 0 if ip1 is equal to ip2, 1 if ip1 is bigger, -1 otherwise.
+ */
+ private static int CompareTo(byte[] ip1, byte[] ip2)
+ {
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Arrays.AreEqual(ip1, ip2))
+ {
+ return 0;
+ }
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Arrays.AreEqual(Max(ip1, ip2), ip1))
+ {
+ return 1;
+ }
+ return -1;
+ }
+
+ /**
+ * Returns the logical OR of the IP addresses ip1 and
+ * ip2.
+ *
+ * @param ip1 The first IP address.
+ * @param ip2 The second IP address.
+ * @return The OR of ip1 and ip2.
+ */
+ private static byte[] Or(byte[] ip1, byte[] ip2)
+ {
+ byte[] temp = new byte[ip1.Length];
+ for (int i = 0; i < ip1.Length; i++)
+ {
+ temp[i] = (byte)(ip1[i] | ip2[i]);
+ }
+ return temp;
+ }
+
+ [Obsolete("Use GetHashCode instead")]
+ public int HashCode()
+ {
+ return GetHashCode();
+ }
+
+ public override int GetHashCode()
+ {
+ return HashCollection(excludedSubtreesDN)
+ + HashCollection(excludedSubtreesDNS)
+ + HashCollection(excludedSubtreesEmail)
+ + HashCollection(excludedSubtreesIP)
+ + HashCollection(excludedSubtreesURI)
+ + HashCollection(permittedSubtreesDN)
+ + HashCollection(permittedSubtreesDNS)
+ + HashCollection(permittedSubtreesEmail)
+ + HashCollection(permittedSubtreesIP)
+ + HashCollection(permittedSubtreesURI);
+ }
+
+ private int HashCollection(ICollection coll)
+ {
+ if (coll == null)
+ {
+ return 0;
+ }
+ int hash = 0;
+ IEnumerator it1 = coll.GetEnumerator();
+ while (it1.MoveNext())
+ {
+ Object o = it1.Current;
+ if (o is byte[])
+ {
+ hash += BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Arrays.GetHashCode((byte[])o);
+ }
+ else
+ {
+ hash += o.GetHashCode();
+ }
+ }
+ return hash;
+ }
+
+ public override bool Equals(Object o)
+ {
+ if (!(o is PkixNameConstraintValidator))
+ return false;
+
+ PkixNameConstraintValidator constraintValidator = (PkixNameConstraintValidator)o;
+
+ return CollectionsAreEqual(constraintValidator.excludedSubtreesDN, excludedSubtreesDN)
+ && CollectionsAreEqual(constraintValidator.excludedSubtreesDNS, excludedSubtreesDNS)
+ && CollectionsAreEqual(constraintValidator.excludedSubtreesEmail, excludedSubtreesEmail)
+ && CollectionsAreEqual(constraintValidator.excludedSubtreesIP, excludedSubtreesIP)
+ && CollectionsAreEqual(constraintValidator.excludedSubtreesURI, excludedSubtreesURI)
+ && CollectionsAreEqual(constraintValidator.permittedSubtreesDN, permittedSubtreesDN)
+ && CollectionsAreEqual(constraintValidator.permittedSubtreesDNS, permittedSubtreesDNS)
+ && CollectionsAreEqual(constraintValidator.permittedSubtreesEmail, permittedSubtreesEmail)
+ && CollectionsAreEqual(constraintValidator.permittedSubtreesIP, permittedSubtreesIP)
+ && CollectionsAreEqual(constraintValidator.permittedSubtreesURI, permittedSubtreesURI);
+ }
+
+ private bool CollectionsAreEqual(ICollection coll1, ICollection coll2)
+ {
+ if (coll1 == coll2)
+ {
+ return true;
+ }
+ if (coll1 == null || coll2 == null)
+ {
+ return false;
+ }
+ if (coll1.Count != coll2.Count)
+ {
+ return false;
+ }
+ IEnumerator it1 = coll1.GetEnumerator();
+
+ while (it1.MoveNext())
+ {
+ Object a = it1.Current;
+ IEnumerator it2 = coll2.GetEnumerator();
+ bool found = false;
+ while (it2.MoveNext())
+ {
+ Object b = it2.Current;
+ if (SpecialEquals(a, b))
+ {
+ found = true;
+ break;
+ }
+ }
+ if (!found)
+ {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private bool SpecialEquals(Object o1, Object o2)
+ {
+ if (o1 == o2)
+ {
+ return true;
+ }
+ if (o1 == null || o2 == null)
+ {
+ return false;
+ }
+ if ((o1 is byte[]) && (o2 is byte[]))
+ {
+ return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Arrays.AreEqual((byte[])o1, (byte[])o2);
+ }
+ else
+ {
+ return o1.Equals(o2);
+ }
+ }
+
+ /**
+ * Stringifies an IPv4 or v6 address with subnet mask.
+ *
+ * @param ip The IP with subnet mask.
+ * @return The stringified IP address.
+ */
+ private String StringifyIP(byte[] ip)
+ {
+ String temp = "";
+ for (int i = 0; i < ip.Length / 2; i++)
+ {
+ //temp += Integer.toString(ip[i] & 0x00FF) + ".";
+ temp += (ip[i] & 0x00FF) + ".";
+ }
+ temp = temp.Substring(0, temp.Length - 1);
+ temp += "/";
+ for (int i = ip.Length / 2; i < ip.Length; i++)
+ {
+ //temp += Integer.toString(ip[i] & 0x00FF) + ".";
+ temp += (ip[i] & 0x00FF) + ".";
+ }
+ temp = temp.Substring(0, temp.Length - 1);
+ return temp;
+ }
+
+ private String StringifyIPCollection(ISet ips)
+ {
+ String temp = "";
+ temp += "[";
+ for (IEnumerator it = ips.GetEnumerator(); it.MoveNext(); )
+ {
+ temp += StringifyIP((byte[])it.Current) + ",";
+ }
+ if (temp.Length > 1)
+ {
+ temp = temp.Substring(0, temp.Length - 1);
+ }
+ temp += "]";
+
+ return temp;
+ }
+
+ public override String ToString()
+ {
+ String temp = "";
+
+ temp += "permitted:\n";
+ if (permittedSubtreesDN != null)
+ {
+ temp += "DN:\n";
+ temp += permittedSubtreesDN.ToString() + "\n";
+ }
+ if (permittedSubtreesDNS != null)
+ {
+ temp += "DNS:\n";
+ temp += permittedSubtreesDNS.ToString() + "\n";
+ }
+ if (permittedSubtreesEmail != null)
+ {
+ temp += "Email:\n";
+ temp += permittedSubtreesEmail.ToString() + "\n";
+ }
+ if (permittedSubtreesURI != null)
+ {
+ temp += "URI:\n";
+ temp += permittedSubtreesURI.ToString() + "\n";
+ }
+ if (permittedSubtreesIP != null)
+ {
+ temp += "IP:\n";
+ temp += StringifyIPCollection(permittedSubtreesIP) + "\n";
+ }
+ temp += "excluded:\n";
+ if (!(excludedSubtreesDN.IsEmpty))
+ {
+ temp += "DN:\n";
+ temp += excludedSubtreesDN.ToString() + "\n";
+ }
+ if (!excludedSubtreesDNS.IsEmpty)
+ {
+ temp += "DNS:\n";
+ temp += excludedSubtreesDNS.ToString() + "\n";
+ }
+ if (!excludedSubtreesEmail.IsEmpty)
+ {
+ temp += "Email:\n";
+ temp += excludedSubtreesEmail.ToString() + "\n";
+ }
+ if (!excludedSubtreesURI.IsEmpty)
+ {
+ temp += "URI:\n";
+ temp += excludedSubtreesURI.ToString() + "\n";
+ }
+ if (!excludedSubtreesIP.IsEmpty)
+ {
+ temp += "IP:\n";
+ temp += StringifyIPCollection(excludedSubtreesIP) + "\n";
+ }
+ return temp;
+ }
+
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixNameConstraintValidator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixNameConstraintValidator.cs.meta
new file mode 100644
index 00000000..eb5e5c36
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixNameConstraintValidator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: f526512b4e00a18408980528de75bc05
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixNameConstraintValidatorException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixNameConstraintValidatorException.cs
new file mode 100644
index 00000000..89157ed7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixNameConstraintValidatorException.cs
@@ -0,0 +1,20 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix
+{
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class PkixNameConstraintValidatorException
+ : Exception
+ {
+ public PkixNameConstraintValidatorException(String msg)
+ : base(msg)
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixNameConstraintValidatorException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixNameConstraintValidatorException.cs.meta
new file mode 100644
index 00000000..d0dce51b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixNameConstraintValidatorException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 7731ec37d612ebe4998773dbfb370c49
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixParameters.cs
new file mode 100644
index 00000000..45e20bc9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixParameters.cs
@@ -0,0 +1,897 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Date;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix
+{
+ ///
+ /// Summary description for PkixParameters.
+ ///
+ public class PkixParameters
+// : ICertPathParameters
+ {
+ /**
+ * This is the default PKIX validity model. Actually there are two variants
+ * of this: The PKIX model and the modified PKIX model. The PKIX model
+ * verifies that all involved certificates must have been valid at the
+ * current time. The modified PKIX model verifies that all involved
+ * certificates were valid at the signing time. Both are indirectly choosen
+ * with the {@link PKIXParameters#setDate(java.util.Date)} method, so this
+ * methods sets the Date when all certificates must have been
+ * valid.
+ */
+ public const int PkixValidityModel = 0;
+
+ /**
+ * This model uses the following validity model. Each certificate must have
+ * been valid at the moment where is was used. That means the end
+ * certificate must have been valid at the time the signature was done. The
+ * CA certificate which signed the end certificate must have been valid,
+ * when the end certificate was signed. The CA (or Root CA) certificate must
+ * have been valid, when the CA certificate was signed and so on. So the
+ * {@link PKIXParameters#setDate(java.util.Date)} method sets the time, when
+ * the end certificate must have been valid. It is used e.g.
+ * in the German signature law.
+ */
+ public const int ChainValidityModel = 1;
+
+ private ISet trustAnchors;
+ private DateTimeObject date;
+ private IList certPathCheckers;
+ private bool revocationEnabled = true;
+ private ISet initialPolicies;
+ //private bool checkOnlyEECertificateCrl = false;
+ private bool explicitPolicyRequired = false;
+ private bool anyPolicyInhibited = false;
+ private bool policyMappingInhibited = false;
+ private bool policyQualifiersRejected = true;
+ private IX509Selector certSelector;
+ private IList stores;
+ private IX509Selector selector;
+ private bool additionalLocationsEnabled;
+ private IList additionalStores;
+ private ISet trustedACIssuers;
+ private ISet necessaryACAttributes;
+ private ISet prohibitedACAttributes;
+ private ISet attrCertCheckers;
+ private int validityModel = PkixValidityModel;
+ private bool useDeltas = false;
+
+ /**
+ * Creates an instance of PKIXParameters with the specified Set of
+ * most-trusted CAs. Each element of the set is a TrustAnchor.
+ *
+ * Note that the Set is copied to protect against subsequent modifications.
+ *
+ * @param trustAnchors
+ * a Set of TrustAnchors
+ *
+ * @exception InvalidAlgorithmParameterException
+ * if the specified Set is empty
+ * (trustAnchors.isEmpty() == true)
+ * @exception NullPointerException
+ * if the specified Set is null
+ * @exception ClassCastException
+ * if any of the elements in the Set are not of type
+ * java.security.cert.TrustAnchor
+ */
+ public PkixParameters(
+ ISet trustAnchors)
+ {
+ SetTrustAnchors(trustAnchors);
+
+ this.initialPolicies = new HashSet();
+ this.certPathCheckers = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ this.stores = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ this.additionalStores = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ this.trustedACIssuers = new HashSet();
+ this.necessaryACAttributes = new HashSet();
+ this.prohibitedACAttributes = new HashSet();
+ this.attrCertCheckers = new HashSet();
+ }
+
+// // TODO implement for other keystores (see Java build)?
+// /**
+// * Creates an instance of PKIXParameters that
+// * populates the set of most-trusted CAs from the trusted
+// * certificate entries contained in the specified KeyStore.
+// * Only keystore entries that contain trusted X509Certificates
+// * are considered; all other certificate types are ignored.
+// *
+// * @param keystore a KeyStore from which the set of
+// * most-trusted CAs will be populated
+// * @throws KeyStoreException if the keystore has not been initialized
+// * @throws InvalidAlgorithmParameterException if the keystore does
+// * not contain at least one trusted certificate entry
+// * @throws NullPointerException if the keystore is null
+// */
+// public PkixParameters(
+// Pkcs12Store keystore)
+//// throws KeyStoreException, InvalidAlgorithmParameterException
+// {
+// if (keystore == null)
+// throw new ArgumentNullException("keystore");
+// ISet trustAnchors = new HashSet();
+// foreach (string alias in keystore.Aliases)
+// {
+// if (keystore.IsCertificateEntry(alias))
+// {
+// X509CertificateEntry x509Entry = keystore.GetCertificate(alias);
+// trustAnchors.Add(new TrustAnchor(x509Entry.Certificate, null));
+// }
+// }
+// SetTrustAnchors(trustAnchors);
+//
+// this.initialPolicies = new HashSet();
+// this.certPathCheckers = new ArrayList();
+// this.stores = new ArrayList();
+// this.additionalStores = new ArrayList();
+// this.trustedACIssuers = new HashSet();
+// this.necessaryACAttributes = new HashSet();
+// this.prohibitedACAttributes = new HashSet();
+// this.attrCertCheckers = new HashSet();
+// }
+
+ public virtual bool IsRevocationEnabled
+ {
+ get { return revocationEnabled; }
+ set { revocationEnabled = value; }
+ }
+
+ public virtual bool IsExplicitPolicyRequired
+ {
+ get { return explicitPolicyRequired; }
+ set { this.explicitPolicyRequired = value; }
+ }
+
+ public virtual bool IsAnyPolicyInhibited
+ {
+ get { return anyPolicyInhibited; }
+ set { this.anyPolicyInhibited = value; }
+ }
+
+ public virtual bool IsPolicyMappingInhibited
+ {
+ get { return policyMappingInhibited; }
+ set { this.policyMappingInhibited = value; }
+ }
+
+ public virtual bool IsPolicyQualifiersRejected
+ {
+ get { return policyQualifiersRejected; }
+ set { this.policyQualifiersRejected = value; }
+ }
+
+ //public bool IsCheckOnlyEECertificateCrl
+ //{
+ // get { return this.checkOnlyEECertificateCrl; }
+ // set { this.checkOnlyEECertificateCrl = value; }
+ //}
+
+ public virtual DateTimeObject Date
+ {
+ get { return this.date; }
+ set { this.date = value; }
+ }
+
+ // Returns a Set of the most-trusted CAs.
+ public virtual ISet GetTrustAnchors()
+ {
+ return new HashSet(this.trustAnchors);
+ }
+
+ // Sets the set of most-trusted CAs.
+ // Set is copied to protect against subsequent modifications.
+ public virtual void SetTrustAnchors(
+ ISet tas)
+ {
+ if (tas == null)
+ throw new ArgumentNullException("value");
+ if (tas.IsEmpty)
+ throw new ArgumentException("non-empty set required", "value");
+
+ // Explicit copy to enforce type-safety
+ this.trustAnchors = new HashSet();
+ foreach (TrustAnchor ta in tas)
+ {
+ if (ta != null)
+ {
+ trustAnchors.Add(ta);
+ }
+ }
+ }
+
+ /**
+ * Returns the required constraints on the target certificate. The
+ * constraints are returned as an instance of CertSelector. If
+ * null, no constraints are defined.
+ *
+ * Note that the CertSelector returned is cloned to protect against
+ * subsequent modifications.
+ *
+ * @return a CertSelector specifying the constraints on the target
+ * certificate (or null)
+ *
+ * @see #setTargetCertConstraints(CertSelector)
+ */
+ public virtual X509CertStoreSelector GetTargetCertConstraints()
+ {
+ if (certSelector == null)
+ {
+ return null;
+ }
+
+ return (X509CertStoreSelector)certSelector.Clone();
+ }
+
+ /**
+ * Sets the required constraints on the target certificate. The constraints
+ * are specified as an instance of CertSelector. If null, no constraints are
+ * defined.
+ *
+ * Note that the CertSelector specified is cloned to protect against
+ * subsequent modifications.
+ *
+ * @param selector
+ * a CertSelector specifying the constraints on the target
+ * certificate (or null)
+ *
+ * @see #getTargetCertConstraints()
+ */
+ public virtual void SetTargetCertConstraints(
+ IX509Selector selector)
+ {
+ if (selector == null)
+ {
+ certSelector = null;
+ }
+ else
+ {
+ certSelector = (IX509Selector)selector.Clone();
+ }
+ }
+
+ /**
+ * Returns an immutable Set of initial policy identifiers (OID strings),
+ * indicating that any one of these policies would be acceptable to the
+ * certificate user for the purposes of certification path processing. The
+ * default return value is an empty Set, which is
+ * interpreted as meaning that any policy would be acceptable.
+ *
+ * @return an immutable Set of initial policy OIDs in String
+ * format, or an empty Set (implying any policy is
+ * acceptable). Never returns null.
+ *
+ * @see #setInitialPolicies(java.util.Set)
+ */
+ public virtual ISet GetInitialPolicies()
+ {
+ ISet returnSet = initialPolicies;
+
+ // TODO Can it really be null?
+ if (initialPolicies == null)
+ {
+ returnSet = new HashSet();
+ }
+
+ return new HashSet(returnSet);
+ }
+
+ /**
+ * Sets the Set of initial policy identifiers (OID strings),
+ * indicating that any one of these policies would be acceptable to the
+ * certificate user for the purposes of certification path processing. By
+ * default, any policy is acceptable (i.e. all policies), so a user that
+ * wants to allow any policy as acceptable does not need to call this
+ * method, or can call it with an empty Set (or
+ * null).
+ *
+ * Note that the Set is copied to protect against subsequent modifications.
+ *
+ *
+ * @param initialPolicies
+ * a Set of initial policy OIDs in String format (or
+ * null)
+ *
+ * @exception ClassCastException
+ * if any of the elements in the set are not of type String
+ *
+ * @see #getInitialPolicies()
+ */
+ public virtual void SetInitialPolicies(
+ ISet initialPolicies)
+ {
+ this.initialPolicies = new HashSet();
+ if (initialPolicies != null)
+ {
+ foreach (string obj in initialPolicies)
+ {
+ if (obj != null)
+ {
+ this.initialPolicies.Add(obj);
+ }
+ }
+ }
+ }
+
+ /**
+ * Sets a List of additional certification path checkers. If
+ * the specified List contains an object that is not a PKIXCertPathChecker,
+ * it is ignored.
+ *
+ * Each PKIXCertPathChecker specified implements additional
+ * checks on a certificate. Typically, these are checks to process and
+ * verify private extensions contained in certificates. Each
+ * PKIXCertPathChecker should be instantiated with any
+ * initialization parameters needed to execute the check.
+ *
+ * This method allows sophisticated applications to extend a PKIX
+ * CertPathValidator or CertPathBuilder. Each
+ * of the specified PKIXCertPathCheckers will be called, in turn, by a PKIX
+ * CertPathValidator or CertPathBuilder for
+ * each certificate processed or validated.
+ *
+ * Regardless of whether these additional PKIXCertPathCheckers are set, a
+ * PKIX CertPathValidator or CertPathBuilder
+ * must perform all of the required PKIX checks on each certificate. The one
+ * exception to this rule is if the RevocationEnabled flag is set to false
+ * (see the {@link #setRevocationEnabled(boolean) setRevocationEnabled}
+ * method).
+ *
+ * Note that the List supplied here is copied and each PKIXCertPathChecker
+ * in the list is cloned to protect against subsequent modifications.
+ *
+ * @param checkers
+ * a List of PKIXCertPathCheckers. May be null, in which case no
+ * additional checkers will be used.
+ * @exception ClassCastException
+ * if any of the elements in the list are not of type
+ * java.security.cert.PKIXCertPathChecker
+ * @see #getCertPathCheckers()
+ */
+ public virtual void SetCertPathCheckers(IList checkers)
+ {
+ certPathCheckers = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ if (checkers != null)
+ {
+ foreach (PkixCertPathChecker obj in checkers)
+ {
+ certPathCheckers.Add(obj.Clone());
+ }
+ }
+ }
+
+ /**
+ * Returns the List of certification path checkers. Each PKIXCertPathChecker
+ * in the returned IList is cloned to protect against subsequent modifications.
+ *
+ * @return an immutable List of PKIXCertPathCheckers (may be empty, but not
+ * null)
+ *
+ * @see #setCertPathCheckers(java.util.List)
+ */
+ public virtual IList GetCertPathCheckers()
+ {
+ IList checkers = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ foreach (PkixCertPathChecker obj in certPathCheckers)
+ {
+ checkers.Add(obj.Clone());
+ }
+ return checkers;
+ }
+
+ /**
+ * Adds a PKIXCertPathChecker to the list of certification
+ * path checkers. See the {@link #setCertPathCheckers setCertPathCheckers}
+ * method for more details.
+ *
+ * Note that the PKIXCertPathChecker is cloned to protect
+ * against subsequent modifications.
+ *
+ * @param checker a PKIXCertPathChecker to add to the list of
+ * checks. If null, the checker is ignored (not added to list).
+ */
+ public virtual void AddCertPathChecker(
+ PkixCertPathChecker checker)
+ {
+ if (checker != null)
+ {
+ certPathCheckers.Add(checker.Clone());
+ }
+ }
+
+ public virtual object Clone()
+ {
+ // FIXME Check this whole method against the Java implementation!
+
+ PkixParameters parameters = new PkixParameters(GetTrustAnchors());
+ parameters.SetParams(this);
+ return parameters;
+
+
+// PkixParameters obj = new PkixParameters(new HashSet());
+//// (PkixParameters) this.MemberwiseClone();
+// obj.x509Stores = new ArrayList(x509Stores);
+// obj.certPathCheckers = new ArrayList(certPathCheckers);
+//
+// //Iterator iter = certPathCheckers.iterator();
+// //obj.certPathCheckers = new ArrayList();
+// //while (iter.hasNext())
+// //{
+// // obj.certPathCheckers.add(((PKIXCertPathChecker)iter.next())
+// // .clone());
+// //}
+// //if (initialPolicies != null)
+// //{
+// // obj.initialPolicies = new HashSet(initialPolicies);
+// //}
+//// if (trustAnchors != null)
+//// {
+//// obj.trustAnchors = new HashSet(trustAnchors);
+//// }
+//// if (certSelector != null)
+//// {
+//// obj.certSelector = (X509CertStoreSelector) certSelector.Clone();
+//// }
+// return obj;
+ }
+
+ /**
+ * Method to support Clone() under J2ME.
+ * super.Clone() does not exist and fields are not copied.
+ *
+ * @param params Parameters to set. If this are
+ * ExtendedPkixParameters they are copied to.
+ */
+ protected virtual void SetParams(
+ PkixParameters parameters)
+ {
+ Date = parameters.Date;
+ SetCertPathCheckers(parameters.GetCertPathCheckers());
+ IsAnyPolicyInhibited = parameters.IsAnyPolicyInhibited;
+ IsExplicitPolicyRequired = parameters.IsExplicitPolicyRequired;
+ IsPolicyMappingInhibited = parameters.IsPolicyMappingInhibited;
+ IsRevocationEnabled = parameters.IsRevocationEnabled;
+ SetInitialPolicies(parameters.GetInitialPolicies());
+ IsPolicyQualifiersRejected = parameters.IsPolicyQualifiersRejected;
+ SetTargetCertConstraints(parameters.GetTargetCertConstraints());
+ SetTrustAnchors(parameters.GetTrustAnchors());
+
+ validityModel = parameters.validityModel;
+ useDeltas = parameters.useDeltas;
+ additionalLocationsEnabled = parameters.additionalLocationsEnabled;
+ selector = parameters.selector == null ? null
+ : (IX509Selector) parameters.selector.Clone();
+ stores = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(parameters.stores);
+ additionalStores = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(parameters.additionalStores);
+ trustedACIssuers = new HashSet(parameters.trustedACIssuers);
+ prohibitedACAttributes = new HashSet(parameters.prohibitedACAttributes);
+ necessaryACAttributes = new HashSet(parameters.necessaryACAttributes);
+ attrCertCheckers = new HashSet(parameters.attrCertCheckers);
+ }
+
+ /**
+ * Whether delta CRLs should be used for checking the revocation status.
+ * Defaults to false.
+ */
+ public virtual bool IsUseDeltasEnabled
+ {
+ get { return useDeltas; }
+ set { useDeltas = value; }
+ }
+
+ /**
+ * The validity model.
+ * @see #CHAIN_VALIDITY_MODEL
+ * @see #PKIX_VALIDITY_MODEL
+ */
+ public virtual int ValidityModel
+ {
+ get { return validityModel; }
+ set { validityModel = value; }
+ }
+
+ /**
+ * Sets the Bouncy Castle Stores for finding CRLs, certificates, attribute
+ * certificates or cross certificates.
+ *
+ * The IList is cloned.
+ *
+ *
+ * @param stores A list of stores to use.
+ * @see #getStores
+ * @throws ClassCastException if an element of stores is not
+ * a {@link Store}.
+ */
+ public virtual void SetStores(
+ IList stores)
+ {
+ if (stores == null)
+ {
+ this.stores = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ }
+ else
+ {
+ foreach (object obj in stores)
+ {
+ if (!(obj is IX509Store))
+ {
+ throw new InvalidCastException(
+ "All elements of list must be of type " + typeof(IX509Store).FullName);
+ }
+ }
+ this.stores = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(stores);
+ }
+ }
+
+ /**
+ * Adds a Bouncy Castle {@link Store} to find CRLs, certificates, attribute
+ * certificates or cross certificates.
+ *
+ * This method should be used to add local stores, like collection based
+ * X.509 stores, if available. Local stores should be considered first,
+ * before trying to use additional (remote) locations, because they do not
+ * need possible additional network traffic.
+ *
+ * If store is null it is ignored.
+ *
+ *
+ * @param store The store to add.
+ * @see #getStores
+ */
+ public virtual void AddStore(
+ IX509Store store)
+ {
+ if (store != null)
+ {
+ stores.Add(store);
+ }
+ }
+
+ /**
+ * Adds an additional Bouncy Castle {@link Store} to find CRLs, certificates,
+ * attribute certificates or cross certificates.
+ *
+ * You should not use this method. This method is used for adding additional
+ * X.509 stores, which are used to add (remote) locations, e.g. LDAP, found
+ * during X.509 object processing, e.g. in certificates or CRLs. This method
+ * is used in PKIX certification path processing.
+ *
+ * If store is null it is ignored.
+ *
+ *
+ * @param store The store to add.
+ * @see #getStores()
+ */
+ public virtual void AddAdditionalStore(
+ IX509Store store)
+ {
+ if (store != null)
+ {
+ additionalStores.Add(store);
+ }
+ }
+
+ /**
+ * Returns an IList of additional Bouncy Castle
+ * Stores used for finding CRLs, certificates, attribute
+ * certificates or cross certificates.
+ *
+ * @return an immutable IList of additional Bouncy Castle
+ * Stores. Never null.
+ *
+ * @see #addAddionalStore(Store)
+ */
+ public virtual IList GetAdditionalStores()
+ {
+ return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(additionalStores);
+ }
+
+ /**
+ * Returns an IList of Bouncy Castle
+ * Stores used for finding CRLs, certificates, attribute
+ * certificates or cross certificates.
+ *
+ * @return an immutable IList of Bouncy Castle
+ * Stores. Never null.
+ *
+ * @see #setStores(IList)
+ */
+ public virtual IList GetStores()
+ {
+ return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(stores);
+ }
+
+ /**
+ * Returns if additional {@link X509Store}s for locations like LDAP found
+ * in certificates or CRLs should be used.
+ *
+ * @return Returns true if additional stores are used.
+ */
+ public virtual bool IsAdditionalLocationsEnabled
+ {
+ get { return additionalLocationsEnabled; }
+ }
+
+ /**
+ * Sets if additional {@link X509Store}s for locations like LDAP found in
+ * certificates or CRLs should be used.
+ *
+ * @param enabled true if additional stores are used.
+ */
+ public virtual void SetAdditionalLocationsEnabled(
+ bool enabled)
+ {
+ additionalLocationsEnabled = enabled;
+ }
+
+ /**
+ * Returns the required constraints on the target certificate or attribute
+ * certificate. The constraints are returned as an instance of
+ * IX509Selector. If null, no constraints are
+ * defined.
+ *
+ *
+ * The target certificate in a PKIX path may be a certificate or an
+ * attribute certificate.
+ *
+ * Note that the IX509Selector returned is cloned to protect
+ * against subsequent modifications.
+ *
+ * @return a IX509Selector specifying the constraints on the
+ * target certificate or attribute certificate (or null)
+ * @see #setTargetConstraints
+ * @see X509CertStoreSelector
+ * @see X509AttributeCertStoreSelector
+ */
+ public virtual IX509Selector GetTargetConstraints()
+ {
+ if (selector != null)
+ {
+ return (IX509Selector) selector.Clone();
+ }
+ else
+ {
+ return null;
+ }
+ }
+
+ /**
+ * Sets the required constraints on the target certificate or attribute
+ * certificate. The constraints are specified as an instance of
+ * IX509Selector. If null, no constraints are
+ * defined.
+ *
+ * The target certificate in a PKIX path may be a certificate or an
+ * attribute certificate.
+ *
+ * Note that the IX509Selector specified is cloned to protect
+ * against subsequent modifications.
+ *
+ *
+ * @param selector a IX509Selector specifying the constraints on
+ * the target certificate or attribute certificate (or
+ * null)
+ * @see #getTargetConstraints
+ * @see X509CertStoreSelector
+ * @see X509AttributeCertStoreSelector
+ */
+ public virtual void SetTargetConstraints(IX509Selector selector)
+ {
+ if (selector != null)
+ {
+ this.selector = (IX509Selector) selector.Clone();
+ }
+ else
+ {
+ this.selector = null;
+ }
+ }
+
+ /**
+ * Returns the trusted attribute certificate issuers. If attribute
+ * certificates is verified the trusted AC issuers must be set.
+ *
+ * The returned ISet consists of TrustAnchors.
+ *
+ * The returned ISet is immutable. Never null
+ *
+ *
+ * @return Returns an immutable set of the trusted AC issuers.
+ */
+ public virtual ISet GetTrustedACIssuers()
+ {
+ return new HashSet(trustedACIssuers);
+ }
+
+ /**
+ * Sets the trusted attribute certificate issuers. If attribute certificates
+ * is verified the trusted AC issuers must be set.
+ *
+ * The trustedACIssuers must be a ISet of
+ * TrustAnchor
+ *
+ * The given set is cloned.
+ *
+ *
+ * @param trustedACIssuers The trusted AC issuers to set. Is never
+ * null.
+ * @throws ClassCastException if an element of stores is not
+ * a TrustAnchor.
+ */
+ public virtual void SetTrustedACIssuers(
+ ISet trustedACIssuers)
+ {
+ if (trustedACIssuers == null)
+ {
+ this.trustedACIssuers = new HashSet();
+ }
+ else
+ {
+ foreach (object obj in trustedACIssuers)
+ {
+ if (!(obj is TrustAnchor))
+ {
+ throw new InvalidCastException("All elements of set must be "
+ + "of type " + typeof(TrustAnchor).FullName + ".");
+ }
+ }
+ this.trustedACIssuers = new HashSet(trustedACIssuers);
+ }
+ }
+
+ /**
+ * Returns the necessary attributes which must be contained in an attribute
+ * certificate.
+ *
+ * The returned ISet is immutable and contains
+ * Strings with the OIDs.
+ *
+ *
+ * @return Returns the necessary AC attributes.
+ */
+ public virtual ISet GetNecessaryACAttributes()
+ {
+ return new HashSet(necessaryACAttributes);
+ }
+
+ /**
+ * Sets the necessary which must be contained in an attribute certificate.
+ *
+ * The ISet must contain Strings with the
+ * OIDs.
+ *
+ * The set is cloned.
+ *
+ *
+ * @param necessaryACAttributes The necessary AC attributes to set.
+ * @throws ClassCastException if an element of
+ * necessaryACAttributes is not a
+ * String.
+ */
+ public virtual void SetNecessaryACAttributes(
+ ISet necessaryACAttributes)
+ {
+ if (necessaryACAttributes == null)
+ {
+ this.necessaryACAttributes = new HashSet();
+ }
+ else
+ {
+ foreach (object obj in necessaryACAttributes)
+ {
+ if (!(obj is string))
+ {
+ throw new InvalidCastException("All elements of set must be "
+ + "of type string.");
+ }
+ }
+ this.necessaryACAttributes = new HashSet(necessaryACAttributes);
+ }
+ }
+
+ /**
+ * Returns the attribute certificates which are not allowed.
+ *
+ * The returned ISet is immutable and contains
+ * Strings with the OIDs.
+ *
+ *
+ * @return Returns the prohibited AC attributes. Is never null.
+ */
+ public virtual ISet GetProhibitedACAttributes()
+ {
+ return new HashSet(prohibitedACAttributes);
+ }
+
+ /**
+ * Sets the attribute certificates which are not allowed.
+ *
+ * The ISet must contain Strings with the
+ * OIDs.
+ *
+ * The set is cloned.
+ *
+ *
+ * @param prohibitedACAttributes The prohibited AC attributes to set.
+ * @throws ClassCastException if an element of
+ * prohibitedACAttributes is not a
+ * String.
+ */
+ public virtual void SetProhibitedACAttributes(
+ ISet prohibitedACAttributes)
+ {
+ if (prohibitedACAttributes == null)
+ {
+ this.prohibitedACAttributes = new HashSet();
+ }
+ else
+ {
+ foreach (object obj in prohibitedACAttributes)
+ {
+ if (!(obj is String))
+ {
+ throw new InvalidCastException("All elements of set must be "
+ + "of type string.");
+ }
+ }
+ this.prohibitedACAttributes = new HashSet(prohibitedACAttributes);
+ }
+ }
+
+ /**
+ * Returns the attribute certificate checker. The returned set contains
+ * {@link PKIXAttrCertChecker}s and is immutable.
+ *
+ * @return Returns the attribute certificate checker. Is never
+ * null.
+ */
+ public virtual ISet GetAttrCertCheckers()
+ {
+ return new HashSet(attrCertCheckers);
+ }
+
+ /**
+ * Sets the attribute certificate checkers.
+ *
+ * All elements in the ISet must a {@link PKIXAttrCertChecker}.
+ *
+ *
+ * The given set is cloned.
+ *
+ *
+ * @param attrCertCheckers The attribute certificate checkers to set. Is
+ * never null.
+ * @throws ClassCastException if an element of attrCertCheckers
+ * is not a PKIXAttrCertChecker.
+ */
+ public virtual void SetAttrCertCheckers(
+ ISet attrCertCheckers)
+ {
+ if (attrCertCheckers == null)
+ {
+ this.attrCertCheckers = new HashSet();
+ }
+ else
+ {
+ foreach (object obj in attrCertCheckers)
+ {
+ if (!(obj is PkixAttrCertChecker))
+ {
+ throw new InvalidCastException("All elements of set must be "
+ + "of type " + typeof(PkixAttrCertChecker).FullName + ".");
+ }
+ }
+ this.attrCertCheckers = new HashSet(attrCertCheckers);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixParameters.cs.meta
new file mode 100644
index 00000000..fb4cff4f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: bddc2e795cf6cd046bbd64b225ce7cdc
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixPolicyNode.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixPolicyNode.cs
new file mode 100644
index 00000000..60a58c37
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixPolicyNode.cs
@@ -0,0 +1,162 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix
+{
+ ///
+ /// Summary description for PkixPolicyNode.
+ ///
+ public class PkixPolicyNode
+// : IPolicyNode
+ {
+ protected IList mChildren;
+ protected int mDepth;
+ protected ISet mExpectedPolicies;
+ protected PkixPolicyNode mParent;
+ protected ISet mPolicyQualifiers;
+ protected string mValidPolicy;
+ protected bool mCritical;
+
+ public virtual int Depth
+ {
+ get { return this.mDepth; }
+ }
+
+ public virtual IEnumerable Children
+ {
+ get { return new EnumerableProxy(mChildren); }
+ }
+
+ public virtual bool IsCritical
+ {
+ get { return this.mCritical; }
+ set { this.mCritical = value; }
+ }
+
+ public virtual ISet PolicyQualifiers
+ {
+ get { return new HashSet(this.mPolicyQualifiers); }
+ }
+
+ public virtual string ValidPolicy
+ {
+ get { return this.mValidPolicy; }
+ }
+
+ public virtual bool HasChildren
+ {
+ get { return mChildren.Count != 0; }
+ }
+
+ public virtual ISet ExpectedPolicies
+ {
+ get { return new HashSet(this.mExpectedPolicies); }
+ set { this.mExpectedPolicies = new HashSet(value); }
+ }
+
+ public virtual PkixPolicyNode Parent
+ {
+ get { return this.mParent; }
+ set { this.mParent = value; }
+ }
+
+ /// Constructors
+ public PkixPolicyNode(
+ IList children,
+ int depth,
+ ISet expectedPolicies,
+ PkixPolicyNode parent,
+ ISet policyQualifiers,
+ string validPolicy,
+ bool critical)
+ {
+ if (children == null)
+ {
+ this.mChildren = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ }
+ else
+ {
+ this.mChildren = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(children);
+ }
+
+ this.mDepth = depth;
+ this.mExpectedPolicies = expectedPolicies;
+ this.mParent = parent;
+ this.mPolicyQualifiers = policyQualifiers;
+ this.mValidPolicy = validPolicy;
+ this.mCritical = critical;
+ }
+
+ public virtual void AddChild(
+ PkixPolicyNode child)
+ {
+ child.Parent = this;
+ mChildren.Add(child);
+ }
+
+ public virtual void RemoveChild(
+ PkixPolicyNode child)
+ {
+ mChildren.Remove(child);
+ }
+
+ public override string ToString()
+ {
+ return ToString("");
+ }
+
+ public virtual string ToString(
+ string indent)
+ {
+ StringBuilder buf = new StringBuilder();
+ buf.Append(indent);
+ buf.Append(mValidPolicy);
+ buf.Append(" {");
+ buf.Append(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.NewLine);
+
+ foreach (PkixPolicyNode child in mChildren)
+ {
+ buf.Append(child.ToString(indent + " "));
+ }
+
+ buf.Append(indent);
+ buf.Append("}");
+ buf.Append(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.NewLine);
+ return buf.ToString();
+ }
+
+ public virtual object Clone()
+ {
+ return Copy();
+ }
+
+ public virtual PkixPolicyNode Copy()
+ {
+ PkixPolicyNode node = new PkixPolicyNode(
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(),
+ mDepth,
+ new HashSet(mExpectedPolicies),
+ null,
+ new HashSet(mPolicyQualifiers),
+ mValidPolicy,
+ mCritical);
+
+ foreach (PkixPolicyNode child in mChildren)
+ {
+ PkixPolicyNode copy = child.Copy();
+ copy.Parent = node;
+ node.AddChild(copy);
+ }
+
+ return node;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixPolicyNode.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixPolicyNode.cs.meta
new file mode 100644
index 00000000..21f6ba3e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/PkixPolicyNode.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: d33024da030accb498009e4aecd51fe9
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/ReasonsMask.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/ReasonsMask.cs
new file mode 100644
index 00000000..c03f4bbb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/ReasonsMask.cs
@@ -0,0 +1,100 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix
+{
+ ///
+ /// This class helps to handle CRL revocation reasons mask. Each CRL handles a
+ /// certain set of revocation reasons.
+ ///
+ internal class ReasonsMask
+ {
+ private int _reasons;
+
+ ///
+ /// Constructs are reason mask with the reasons.
+ ///
+ /// The reasons.
+ internal ReasonsMask(
+ int reasons)
+ {
+ _reasons = reasons;
+ }
+
+ ///
+ /// A reason mask with no reason.
+ ///
+ internal ReasonsMask()
+ : this(0)
+ {
+ }
+
+ ///
+ /// A mask with all revocation reasons.
+ ///
+ internal static readonly ReasonsMask AllReasons = new ReasonsMask(
+ ReasonFlags.AACompromise | ReasonFlags.AffiliationChanged | ReasonFlags.CACompromise
+ | ReasonFlags.CertificateHold | ReasonFlags.CessationOfOperation
+ | ReasonFlags.KeyCompromise | ReasonFlags.PrivilegeWithdrawn | ReasonFlags.Unused
+ | ReasonFlags.Superseded);
+
+ /**
+ * Adds all reasons from the reasons mask to this mask.
+ *
+ * @param mask The reasons mask to add.
+ */
+ internal void AddReasons(
+ ReasonsMask mask)
+ {
+ _reasons = _reasons | mask.Reasons.IntValue;
+ }
+
+ ///
+ /// Returns true if this reasons mask contains all possible
+ /// reasons.
+ ///
+ /// true if this reasons mask contains all possible reasons.
+ ///
+ internal bool IsAllReasons
+ {
+ get { return _reasons == AllReasons._reasons; }
+ }
+
+ ///
+ /// Intersects this mask with the given reasons mask.
+ ///
+ /// mask The mask to intersect with.
+ /// The intersection of this and teh given mask.
+ internal ReasonsMask Intersect(
+ ReasonsMask mask)
+ {
+ ReasonsMask _mask = new ReasonsMask();
+ _mask.AddReasons(new ReasonsMask(_reasons & mask.Reasons.IntValue));
+ return _mask;
+ }
+
+ ///
+ /// Returns true if the passed reasons mask has new reasons.
+ ///
+ /// The reasons mask which should be tested for new reasons.
+ /// true if the passed reasons mask has new reasons.
+ internal bool HasNewReasons(
+ ReasonsMask mask)
+ {
+ return ((_reasons | mask.Reasons.IntValue ^ _reasons) != 0);
+ }
+
+ ///
+ /// Returns the reasons in this mask.
+ ///
+ public ReasonFlags Reasons
+ {
+ get { return new ReasonFlags(_reasons); }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/ReasonsMask.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/ReasonsMask.cs.meta
new file mode 100644
index 00000000..f79ac275
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/ReasonsMask.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 82782c3f371478d4788bfedceeac9754
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/Rfc3280CertPathUtilities.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/Rfc3280CertPathUtilities.cs
new file mode 100644
index 00000000..e8270fb6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/Rfc3280CertPathUtilities.cs
@@ -0,0 +1,2452 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.Globalization;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Date;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix
+{
+ public class Rfc3280CertPathUtilities
+ {
+ private static readonly PkixCrlUtilities CrlUtilities = new PkixCrlUtilities();
+
+ internal static readonly string ANY_POLICY = "2.5.29.32.0";
+
+ // key usage bits
+ internal static readonly int KEY_CERT_SIGN = 5;
+ internal static readonly int CRL_SIGN = 6;
+
+ /**
+ * If the complete CRL includes an issuing distribution point (IDP) CRL
+ * extension check the following:
+ *
+ * (i) If the distribution point name is present in the IDP CRL extension
+ * and the distribution field is present in the DP, then verify that one of
+ * the names in the IDP matches one of the names in the DP. If the
+ * distribution point name is present in the IDP CRL extension and the
+ * distribution field is omitted from the DP, then verify that one of the
+ * names in the IDP matches one of the names in the cRLIssuer field of the
+ * DP.
+ *
+ *
+ * (ii) If the onlyContainsUserCerts boolean is asserted in the IDP CRL
+ * extension, verify that the certificate does not include the basic
+ * constraints extension with the cA boolean asserted.
+ *
+ *
+ * (iii) If the onlyContainsCACerts boolean is asserted in the IDP CRL
+ * extension, verify that the certificate includes the basic constraints
+ * extension with the cA boolean asserted.
+ *
+ *
+ * (iv) Verify that the onlyContainsAttributeCerts boolean is not asserted.
+ *
+ *
+ * @param dp The distribution point.
+ * @param cert The certificate.
+ * @param crl The CRL.
+ * @throws AnnotatedException if one of the conditions is not met or an error occurs.
+ */
+ internal static void ProcessCrlB2(
+ DistributionPoint dp,
+ object cert,
+ X509Crl crl)
+ {
+ IssuingDistributionPoint idp = null;
+ try
+ {
+ idp = IssuingDistributionPoint.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(crl, X509Extensions.IssuingDistributionPoint));
+ }
+ catch (Exception e)
+ {
+ throw new Exception("0 Issuing distribution point extension could not be decoded.", e);
+ }
+ // (b) (2) (i)
+ // distribution point name is present
+ if (idp != null)
+ {
+ if (idp.DistributionPoint != null)
+ {
+ // make list of names
+ DistributionPointName dpName = IssuingDistributionPoint.GetInstance(idp).DistributionPoint;
+ IList names = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+
+ if (dpName.PointType == DistributionPointName.FullName)
+ {
+ GeneralName[] genNames = GeneralNames.GetInstance(dpName.Name).GetNames();
+ for (int j = 0; j < genNames.Length; j++)
+ {
+ names.Add(genNames[j]);
+ }
+ }
+ if (dpName.PointType == DistributionPointName.NameRelativeToCrlIssuer)
+ {
+ Asn1EncodableVector vec = new Asn1EncodableVector();
+ try
+ {
+ IEnumerator e = Asn1Sequence.GetInstance(
+ Asn1Sequence.FromByteArray(crl.IssuerDN.GetEncoded())).GetEnumerator();
+ while (e.MoveNext())
+ {
+ vec.Add((Asn1Encodable)e.Current);
+ }
+ }
+ catch (IOException e)
+ {
+ throw new Exception("Could not read CRL issuer.", e);
+ }
+ vec.Add(dpName.Name);
+ names.Add(new GeneralName(X509Name.GetInstance(new DerSequence(vec))));
+ }
+ bool matches = false;
+ // verify that one of the names in the IDP matches one
+ // of the names in the DP.
+ if (dp.DistributionPointName != null)
+ {
+ dpName = dp.DistributionPointName;
+ GeneralName[] genNames = null;
+ if (dpName.PointType == DistributionPointName.FullName)
+ {
+ genNames = GeneralNames.GetInstance(dpName.Name).GetNames();
+ }
+ if (dpName.PointType == DistributionPointName.NameRelativeToCrlIssuer)
+ {
+ if (dp.CrlIssuer != null)
+ {
+ genNames = dp.CrlIssuer.GetNames();
+ }
+ else
+ {
+ genNames = new GeneralName[1];
+ try
+ {
+ genNames[0] = new GeneralName(
+ PkixCertPathValidatorUtilities.GetIssuerPrincipal(cert));
+ }
+ catch (IOException e)
+ {
+ throw new Exception("Could not read certificate issuer.", e);
+ }
+ }
+ for (int j = 0; j < genNames.Length; j++)
+ {
+ IEnumerator e = Asn1Sequence.GetInstance(genNames[j].Name.ToAsn1Object()).GetEnumerator();
+ Asn1EncodableVector vec = new Asn1EncodableVector();
+ while (e.MoveNext())
+ {
+ vec.Add((Asn1Encodable)e.Current);
+ }
+ vec.Add(dpName.Name);
+ genNames[j] = new GeneralName(X509Name.GetInstance(new DerSequence(vec)));
+ }
+ }
+ if (genNames != null)
+ {
+ for (int j = 0; j < genNames.Length; j++)
+ {
+ if (names.Contains(genNames[j]))
+ {
+ matches = true;
+ break;
+ }
+ }
+ }
+ if (!matches)
+ {
+ throw new Exception(
+ "No match for certificate CRL issuing distribution point name to cRLIssuer CRL distribution point.");
+ }
+ }
+ // verify that one of the names in
+ // the IDP matches one of the names in the cRLIssuer field of
+ // the DP
+ else
+ {
+ if (dp.CrlIssuer == null)
+ {
+ throw new Exception("Either the cRLIssuer or the distributionPoint field must "
+ + "be contained in DistributionPoint.");
+ }
+ GeneralName[] genNames = dp.CrlIssuer.GetNames();
+ for (int j = 0; j < genNames.Length; j++)
+ {
+ if (names.Contains(genNames[j]))
+ {
+ matches = true;
+ break;
+ }
+ }
+ if (!matches)
+ {
+ throw new Exception(
+ "No match for certificate CRL issuing distribution point name to cRLIssuer CRL distribution point.");
+ }
+ }
+ }
+ BasicConstraints bc = null;
+ try
+ {
+ bc = BasicConstraints.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(
+ (IX509Extension)cert, X509Extensions.BasicConstraints));
+ }
+ catch (Exception e)
+ {
+ throw new Exception("Basic constraints extension could not be decoded.", e);
+ }
+
+ //if (cert is X509Certificate)
+ {
+ // (b) (2) (ii)
+ if (idp.OnlyContainsUserCerts && ((bc != null) && bc.IsCA()))
+ {
+ throw new Exception("CA Cert CRL only contains user certificates.");
+ }
+
+ // (b) (2) (iii)
+ if (idp.OnlyContainsCACerts && (bc == null || !bc.IsCA()))
+ {
+ throw new Exception("End CRL only contains CA certificates.");
+ }
+ }
+
+ // (b) (2) (iv)
+ if (idp.OnlyContainsAttributeCerts)
+ {
+ throw new Exception("onlyContainsAttributeCerts boolean is asserted.");
+ }
+ }
+ }
+
+ internal static void ProcessCertBC(
+ PkixCertPath certPath,
+ int index,
+ PkixNameConstraintValidator nameConstraintValidator)
+ //throws CertPathValidatorException
+ {
+ IList certs = certPath.Certificates;
+ X509Certificate cert = (X509Certificate)certs[index];
+ int n = certs.Count;
+ // i as defined in the algorithm description
+ int i = n - index;
+ //
+ // (b), (c) permitted and excluded subtree checking.
+ //
+ if (!(PkixCertPathValidatorUtilities.IsSelfIssued(cert) && (i < n)))
+ {
+ X509Name principal = cert.SubjectDN;
+ Asn1InputStream aIn = new Asn1InputStream(principal.GetEncoded());
+ Asn1Sequence dns;
+
+ try
+ {
+ dns = DerSequence.GetInstance(aIn.ReadObject());
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathValidatorException(
+ "Exception extracting subject name when checking subtrees.", e, certPath, index);
+ }
+
+ try
+ {
+ nameConstraintValidator.CheckPermittedDN(dns);
+ nameConstraintValidator.CheckExcludedDN(dns);
+ }
+ catch (PkixNameConstraintValidatorException e)
+ {
+ throw new PkixCertPathValidatorException(
+ "Subtree check for certificate subject failed.", e, certPath, index);
+ }
+
+ GeneralNames altName = null;
+ try
+ {
+ altName = GeneralNames.GetInstance(
+ PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.SubjectAlternativeName));
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathValidatorException(
+ "Subject alternative name extension could not be decoded.", e, certPath, index);
+ }
+
+ IList emails = X509Name.GetInstance(dns).GetValueList(X509Name.EmailAddress);
+ foreach (string email in emails)
+ {
+ GeneralName emailAsGeneralName = new GeneralName(GeneralName.Rfc822Name, email);
+ try
+ {
+ nameConstraintValidator.checkPermitted(emailAsGeneralName);
+ nameConstraintValidator.checkExcluded(emailAsGeneralName);
+ }
+ catch (PkixNameConstraintValidatorException ex)
+ {
+ throw new PkixCertPathValidatorException(
+ "Subtree check for certificate subject alternative email failed.", ex, certPath, index);
+ }
+ }
+ if (altName != null)
+ {
+ GeneralName[] genNames = null;
+ try
+ {
+ genNames = altName.GetNames();
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathValidatorException(
+ "Subject alternative name contents could not be decoded.", e, certPath, index);
+ }
+ foreach (GeneralName genName in genNames)
+ {
+ try
+ {
+ nameConstraintValidator.checkPermitted(genName);
+ nameConstraintValidator.checkExcluded(genName);
+ }
+ catch (PkixNameConstraintValidatorException e)
+ {
+ throw new PkixCertPathValidatorException(
+ "Subtree check for certificate subject alternative name failed.", e, certPath, index);
+ }
+ }
+ }
+ }
+ }
+
+ internal static void PrepareNextCertA(
+ PkixCertPath certPath,
+ int index)
+ //throws CertPathValidatorException
+ {
+ IList certs = certPath.Certificates;
+ X509Certificate cert = (X509Certificate)certs[index];
+ //
+ //
+ // (a) check the policy mappings
+ //
+ Asn1Sequence pm = null;
+ try
+ {
+ pm = Asn1Sequence.GetInstance(
+ PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.PolicyMappings));
+ }
+ catch (Exception ex)
+ {
+ throw new PkixCertPathValidatorException(
+ "Policy mappings extension could not be decoded.", ex, certPath, index);
+ }
+ if (pm != null)
+ {
+ Asn1Sequence mappings = pm;
+
+ for (int j = 0; j < mappings.Count; j++)
+ {
+ DerObjectIdentifier issuerDomainPolicy = null;
+ DerObjectIdentifier subjectDomainPolicy = null;
+ try
+ {
+ Asn1Sequence mapping = DerSequence.GetInstance(mappings[j]);
+
+ issuerDomainPolicy = DerObjectIdentifier.GetInstance(mapping[0]);
+ subjectDomainPolicy = DerObjectIdentifier.GetInstance(mapping[1]);
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathValidatorException(
+ "Policy mappings extension contents could not be decoded.", e, certPath, index);
+ }
+
+ if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(issuerDomainPolicy.Id))
+ throw new PkixCertPathValidatorException(
+ "IssuerDomainPolicy is anyPolicy", null, certPath, index);
+
+ if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(subjectDomainPolicy.Id))
+ throw new PkixCertPathValidatorException(
+ "SubjectDomainPolicy is anyPolicy,", null, certPath, index);
+ }
+ }
+ }
+
+ internal static PkixPolicyNode ProcessCertD(
+ PkixCertPath certPath,
+ int index,
+ ISet acceptablePolicies,
+ PkixPolicyNode validPolicyTree,
+ IList[] policyNodes,
+ int inhibitAnyPolicy)
+ //throws CertPathValidatorException
+ {
+ IList certs = certPath.Certificates;
+ X509Certificate cert = (X509Certificate)certs[index];
+ int n = certs.Count;
+ // i as defined in the algorithm description
+ int i = n - index;
+ //
+ // (d) policy Information checking against initial policy and
+ // policy mapping
+ //
+ Asn1Sequence certPolicies = null;
+ try
+ {
+ certPolicies = DerSequence.GetInstance(
+ PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.CertificatePolicies));
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathValidatorException(
+ "Could not read certificate policies extension from certificate.", e, certPath, index);
+ }
+ if (certPolicies != null && validPolicyTree != null)
+ {
+ //
+ // (d) (1)
+ //
+ ISet pols = new HashSet();
+
+ foreach (Asn1Encodable ae in certPolicies)
+ {
+ PolicyInformation pInfo = PolicyInformation.GetInstance(ae.ToAsn1Object());
+ DerObjectIdentifier pOid = pInfo.PolicyIdentifier;
+
+ pols.Add(pOid.Id);
+
+ if (!Rfc3280CertPathUtilities.ANY_POLICY.Equals(pOid.Id))
+ {
+ ISet pq = null;
+ try
+ {
+ pq = PkixCertPathValidatorUtilities.GetQualifierSet(pInfo.PolicyQualifiers);
+ }
+ catch (PkixCertPathValidatorException ex)
+ {
+ throw new PkixCertPathValidatorException(
+ "Policy qualifier info set could not be build.", ex, certPath, index);
+ }
+
+ bool match = PkixCertPathValidatorUtilities.ProcessCertD1i(i, policyNodes, pOid, pq);
+
+ if (!match)
+ {
+ PkixCertPathValidatorUtilities.ProcessCertD1ii(i, policyNodes, pOid, pq);
+ }
+ }
+ }
+
+ if (acceptablePolicies.IsEmpty || acceptablePolicies.Contains(Rfc3280CertPathUtilities.ANY_POLICY))
+ {
+ acceptablePolicies.Clear();
+ acceptablePolicies.AddAll(pols);
+ }
+ else
+ {
+ ISet t1 = new HashSet();
+
+ foreach (object o in acceptablePolicies)
+ {
+ if (pols.Contains(o))
+ {
+ t1.Add(o);
+ }
+ }
+ acceptablePolicies.Clear();
+ acceptablePolicies.AddAll(t1);
+ }
+
+ //
+ // (d) (2)
+ //
+ if ((inhibitAnyPolicy > 0) || ((i < n) && PkixCertPathValidatorUtilities.IsSelfIssued(cert)))
+ {
+ foreach (Asn1Encodable ae in certPolicies)
+ {
+ PolicyInformation pInfo = PolicyInformation.GetInstance(ae.ToAsn1Object());
+ if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(pInfo.PolicyIdentifier.Id))
+ {
+ ISet _apq = PkixCertPathValidatorUtilities.GetQualifierSet(pInfo.PolicyQualifiers);
+ IList _nodes = policyNodes[i - 1];
+
+ for (int k = 0; k < _nodes.Count; k++)
+ {
+ PkixPolicyNode _node = (PkixPolicyNode)_nodes[k];
+
+ IEnumerator _policySetIter = _node.ExpectedPolicies.GetEnumerator();
+ while (_policySetIter.MoveNext())
+ {
+ object _tmp = _policySetIter.Current;
+
+ string _policy;
+ if (_tmp is string)
+ {
+ _policy = (string)_tmp;
+ }
+ else if (_tmp is DerObjectIdentifier)
+ {
+ _policy = ((DerObjectIdentifier)_tmp).Id;
+ }
+ else
+ {
+ continue;
+ }
+
+ bool _found = false;
+
+ foreach (PkixPolicyNode _child in _node.Children)
+ {
+ if (_policy.Equals(_child.ValidPolicy))
+ {
+ _found = true;
+ }
+ }
+
+ if (!_found)
+ {
+ ISet _newChildExpectedPolicies = new HashSet();
+ _newChildExpectedPolicies.Add(_policy);
+
+ PkixPolicyNode _newChild = new PkixPolicyNode(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(), i,
+ _newChildExpectedPolicies, _node, _apq, _policy, false);
+ _node.AddChild(_newChild);
+ policyNodes[i].Add(_newChild);
+ }
+ }
+ }
+ break;
+ }
+ }
+ }
+
+ PkixPolicyNode _validPolicyTree = validPolicyTree;
+ //
+ // (d) (3)
+ //
+ for (int j = (i - 1); j >= 0; j--)
+ {
+ IList nodes = policyNodes[j];
+
+ for (int k = 0; k < nodes.Count; k++)
+ {
+ PkixPolicyNode node = (PkixPolicyNode)nodes[k];
+ if (!node.HasChildren)
+ {
+ _validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode(_validPolicyTree, policyNodes,
+ node);
+ if (_validPolicyTree == null)
+ {
+ break;
+ }
+ }
+ }
+ }
+
+ //
+ // d (4)
+ //
+ ISet criticalExtensionOids = cert.GetCriticalExtensionOids();
+
+ if (criticalExtensionOids != null)
+ {
+ bool critical = criticalExtensionOids.Contains(X509Extensions.CertificatePolicies.Id);
+
+ IList nodes = policyNodes[i];
+ for (int j = 0; j < nodes.Count; j++)
+ {
+ PkixPolicyNode node = (PkixPolicyNode)nodes[j];
+ node.IsCritical = critical;
+ }
+ }
+ return _validPolicyTree;
+ }
+ return null;
+ }
+
+ /**
+ * If the DP includes cRLIssuer, then verify that the issuer field in the
+ * complete CRL matches cRLIssuer in the DP and that the complete CRL
+ * contains an
+ * g distribution point extension with the indirectCRL
+ * boolean asserted. Otherwise, verify that the CRL issuer matches the
+ * certificate issuer.
+ *
+ * @param dp The distribution point.
+ * @param cert The certificate ot attribute certificate.
+ * @param crl The CRL for cert.
+ * @throws AnnotatedException if one of the above conditions does not apply or an error
+ * occurs.
+ */
+ internal static void ProcessCrlB1(
+ DistributionPoint dp,
+ object cert,
+ X509Crl crl)
+ {
+ Asn1Object idp = PkixCertPathValidatorUtilities.GetExtensionValue(
+ crl, X509Extensions.IssuingDistributionPoint);
+
+ bool isIndirect = false;
+ if (idp != null)
+ {
+ if (IssuingDistributionPoint.GetInstance(idp).IsIndirectCrl)
+ {
+ isIndirect = true;
+ }
+ }
+ byte[] issuerBytes = crl.IssuerDN.GetEncoded();
+
+ bool matchIssuer = false;
+ if (dp.CrlIssuer != null)
+ {
+ GeneralName[] genNames = dp.CrlIssuer.GetNames();
+ for (int j = 0; j < genNames.Length; j++)
+ {
+ if (genNames[j].TagNo == GeneralName.DirectoryName)
+ {
+ try
+ {
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Arrays.AreEqual(genNames[j].Name.ToAsn1Object().GetEncoded(), issuerBytes))
+ {
+ matchIssuer = true;
+ }
+ }
+ catch (IOException e)
+ {
+ throw new Exception(
+ "CRL issuer information from distribution point cannot be decoded.", e);
+ }
+ }
+ }
+ if (matchIssuer && !isIndirect)
+ {
+ throw new Exception("Distribution point contains cRLIssuer field but CRL is not indirect.");
+ }
+ if (!matchIssuer)
+ {
+ throw new Exception("CRL issuer of CRL does not match CRL issuer of distribution point.");
+ }
+ }
+ else
+ {
+ if (crl.IssuerDN.Equivalent(PkixCertPathValidatorUtilities.GetIssuerPrincipal(cert), true))
+ {
+ matchIssuer = true;
+ }
+ }
+ if (!matchIssuer)
+ {
+ throw new Exception("Cannot find matching CRL issuer for certificate.");
+ }
+ }
+
+ internal static ReasonsMask ProcessCrlD(
+ X509Crl crl,
+ DistributionPoint dp)
+ //throws AnnotatedException
+ {
+ IssuingDistributionPoint idp = null;
+ try
+ {
+ idp = IssuingDistributionPoint.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(crl, X509Extensions.IssuingDistributionPoint));
+ }
+ catch (Exception e)
+ {
+ throw new Exception("issuing distribution point extension could not be decoded.", e);
+ }
+
+ // (d) (1)
+ if (idp != null && idp.OnlySomeReasons != null && dp.Reasons != null)
+ {
+ return new ReasonsMask(dp.Reasons.IntValue).Intersect(new ReasonsMask(idp.OnlySomeReasons
+ .IntValue));
+ }
+ // (d) (4)
+ if ((idp == null || idp.OnlySomeReasons == null) && dp.Reasons == null)
+ {
+ return ReasonsMask.AllReasons;
+ }
+
+ // (d) (2) and (d)(3)
+
+ ReasonsMask dpReasons = null;
+
+ if (dp.Reasons == null)
+ {
+ dpReasons = ReasonsMask.AllReasons;
+ }
+ else
+ {
+ dpReasons = new ReasonsMask(dp.Reasons.IntValue);
+ }
+
+ ReasonsMask idpReasons = null;
+
+ if (idp == null)
+ {
+ idpReasons = ReasonsMask.AllReasons;
+ }
+ else
+ {
+ idpReasons = new ReasonsMask(idp.OnlySomeReasons.IntValue);
+ }
+
+ return dpReasons.Intersect(idpReasons);
+ }
+
+ /**
+ * Obtain and validate the certification path for the complete CRL issuer.
+ * If a key usage extension is present in the CRL issuer's certificate,
+ * verify that the cRLSign bit is set.
+ *
+ * @param crl CRL which contains revocation information for the certificate
+ * cert.
+ * @param cert The attribute certificate or certificate to check if it is
+ * revoked.
+ * @param defaultCRLSignCert The issuer certificate of the certificate cert.
+ * @param defaultCRLSignKey The public key of the issuer certificate
+ * defaultCRLSignCert.
+ * @param paramsPKIX paramsPKIX PKIX parameters.
+ * @param certPathCerts The certificates on the certification path.
+ * @return A Set with all keys of possible CRL issuer
+ * certificates.
+ * @throws AnnotatedException if the CRL is not valid or the status cannot be checked or
+ * some error occurs.
+ */
+ internal static ISet ProcessCrlF(
+ X509Crl crl,
+ object cert,
+ X509Certificate defaultCRLSignCert,
+ AsymmetricKeyParameter defaultCRLSignKey,
+ PkixParameters paramsPKIX,
+ IList certPathCerts)
+ {
+ // (f)
+
+ // get issuer from CRL
+ X509CertStoreSelector selector = new X509CertStoreSelector();
+ try
+ {
+ selector.Subject = crl.IssuerDN;
+ }
+ catch (IOException e)
+ {
+ throw new Exception(
+ "Subject criteria for certificate selector to find issuer certificate for CRL could not be set.", e);
+ }
+
+ // get CRL signing certs
+ IList coll = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+
+ try
+ {
+ CollectionUtilities.AddRange(coll, PkixCertPathValidatorUtilities.FindCertificates(selector, paramsPKIX.GetStores()));
+ CollectionUtilities.AddRange(coll, PkixCertPathValidatorUtilities.FindCertificates(selector, paramsPKIX.GetAdditionalStores()));
+ }
+ catch (Exception e)
+ {
+ throw new Exception("Issuer certificate for CRL cannot be searched.", e);
+ }
+
+ coll.Add(defaultCRLSignCert);
+
+ IEnumerator cert_it = coll.GetEnumerator();
+
+ IList validCerts = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ IList validKeys = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+
+ while (cert_it.MoveNext())
+ {
+ X509Certificate signingCert = (X509Certificate)cert_it.Current;
+
+ /*
+ * CA of the certificate, for which this CRL is checked, has also
+ * signed CRL, so skip the path validation, because is already done
+ */
+ if (signingCert.Equals(defaultCRLSignCert))
+ {
+ validCerts.Add(signingCert);
+ validKeys.Add(defaultCRLSignKey);
+ continue;
+ }
+ try
+ {
+// CertPathBuilder builder = CertPathBuilder.GetInstance("PKIX");
+ PkixCertPathBuilder builder = new PkixCertPathBuilder();
+ selector = new X509CertStoreSelector();
+ selector.Certificate = signingCert;
+
+ PkixParameters temp = (PkixParameters)paramsPKIX.Clone();
+ temp.SetTargetCertConstraints(selector);
+
+ PkixBuilderParameters parameters = (PkixBuilderParameters)
+ PkixBuilderParameters.GetInstance(temp);
+
+ /*
+ * if signingCert is placed not higher on the cert path a
+ * dependency loop results. CRL for cert is checked, but
+ * signingCert is needed for checking the CRL which is dependent
+ * on checking cert because it is higher in the cert path and so
+ * signing signingCert transitively. so, revocation is disabled,
+ * forgery attacks of the CRL are detected in this outer loop
+ * for all other it must be enabled to prevent forgery attacks
+ */
+ if (certPathCerts.Contains(signingCert))
+ {
+ parameters.IsRevocationEnabled = false;
+ }
+ else
+ {
+ parameters.IsRevocationEnabled = true;
+ }
+ IList certs = builder.Build(parameters).CertPath.Certificates;
+ validCerts.Add(signingCert);
+ validKeys.Add(PkixCertPathValidatorUtilities.GetNextWorkingKey(certs, 0));
+ }
+ catch (PkixCertPathBuilderException e)
+ {
+ throw new Exception("Internal error.", e);
+ }
+ catch (PkixCertPathValidatorException e)
+ {
+ throw new Exception("Public key of issuer certificate of CRL could not be retrieved.", e);
+ }
+ //catch (Exception e)
+ //{
+ // throw new Exception(e.Message);
+ //}
+ }
+
+ ISet checkKeys = new HashSet();
+
+ Exception lastException = null;
+ for (int i = 0; i < validCerts.Count; i++)
+ {
+ X509Certificate signCert = (X509Certificate)validCerts[i];
+ bool[] keyusage = signCert.GetKeyUsage();
+
+ if (keyusage != null && (keyusage.Length < 7 || !keyusage[CRL_SIGN]))
+ {
+ lastException = new Exception(
+ "Issuer certificate key usage extension does not permit CRL signing.");
+ }
+ else
+ {
+ checkKeys.Add(validKeys[i]);
+ }
+ }
+
+ if ((checkKeys.Count == 0) && lastException == null)
+ {
+ throw new Exception("Cannot find a valid issuer certificate.");
+ }
+ if ((checkKeys.Count == 0) && lastException != null)
+ {
+ throw lastException;
+ }
+
+ return checkKeys;
+ }
+
+ internal static AsymmetricKeyParameter ProcessCrlG(
+ X509Crl crl,
+ ISet keys)
+ {
+ Exception lastException = null;
+ foreach (AsymmetricKeyParameter key in keys)
+ {
+ try
+ {
+ crl.Verify(key);
+ return key;
+ }
+ catch (Exception e)
+ {
+ lastException = e;
+ }
+ }
+ throw new Exception("Cannot verify CRL.", lastException);
+ }
+
+ internal static X509Crl ProcessCrlH(
+ ISet deltaCrls,
+ AsymmetricKeyParameter key)
+ {
+ Exception lastException = null;
+ foreach (X509Crl crl in deltaCrls)
+ {
+ try
+ {
+ crl.Verify(key);
+ return crl;
+ }
+ catch (Exception e)
+ {
+ lastException = e;
+ }
+ }
+ if (lastException != null)
+ {
+ throw new Exception("Cannot verify delta CRL.", lastException);
+ }
+ return null;
+ }
+
+ /**
+ * Checks a distribution point for revocation information for the
+ * certificate cert.
+ *
+ * @param dp The distribution point to consider.
+ * @param paramsPKIX PKIX parameters.
+ * @param cert Certificate to check if it is revoked.
+ * @param validDate The date when the certificate revocation status should be
+ * checked.
+ * @param defaultCRLSignCert The issuer certificate of the certificate cert.
+ * @param defaultCRLSignKey The public key of the issuer certificate
+ * defaultCRLSignCert.
+ * @param certStatus The current certificate revocation status.
+ * @param reasonMask The reasons mask which is already checked.
+ * @param certPathCerts The certificates of the certification path.
+ * @throws AnnotatedException if the certificate is revoked or the status cannot be checked
+ * or some error occurs.
+ */
+ private static void CheckCrl(
+ DistributionPoint dp,
+ PkixParameters paramsPKIX,
+ X509Certificate cert,
+ DateTime validDate,
+ X509Certificate defaultCRLSignCert,
+ AsymmetricKeyParameter defaultCRLSignKey,
+ CertStatus certStatus,
+ ReasonsMask reasonMask,
+ IList certPathCerts)
+ //throws AnnotatedException
+ {
+ DateTime currentDate = DateTime.UtcNow;
+
+ if (validDate.Ticks > currentDate.Ticks)
+ {
+ throw new Exception("Validation time is in future.");
+ }
+
+ // (a)
+ /*
+ * We always get timely valid CRLs, so there is no step (a) (1).
+ * "locally cached" CRLs are assumed to be in getStore(), additional
+ * CRLs must be enabled in the ExtendedPKIXParameters and are in
+ * getAdditionalStore()
+ */
+
+ ISet crls = PkixCertPathValidatorUtilities.GetCompleteCrls(dp, cert, currentDate, paramsPKIX);
+ bool validCrlFound = false;
+ Exception lastException = null;
+
+ IEnumerator crl_iter = crls.GetEnumerator();
+
+ while (crl_iter.MoveNext() && certStatus.Status == CertStatus.Unrevoked && !reasonMask.IsAllReasons)
+ {
+ try
+ {
+ X509Crl crl = (X509Crl)crl_iter.Current;
+
+ // (d)
+ ReasonsMask interimReasonsMask = Rfc3280CertPathUtilities.ProcessCrlD(crl, dp);
+
+ // (e)
+ /*
+ * The reasons mask is updated at the end, so only valid CRLs
+ * can update it. If this CRL does not contain new reasons it
+ * must be ignored.
+ */
+ if (!interimReasonsMask.HasNewReasons(reasonMask))
+ {
+ continue;
+ }
+
+ // (f)
+ ISet keys = Rfc3280CertPathUtilities.ProcessCrlF(crl, cert, defaultCRLSignCert, defaultCRLSignKey,
+ paramsPKIX, certPathCerts);
+ // (g)
+ AsymmetricKeyParameter key = Rfc3280CertPathUtilities.ProcessCrlG(crl, keys);
+
+ X509Crl deltaCRL = null;
+
+ if (paramsPKIX.IsUseDeltasEnabled)
+ {
+ // get delta CRLs
+ ISet deltaCRLs = PkixCertPathValidatorUtilities.GetDeltaCrls(currentDate, paramsPKIX, crl);
+ // we only want one valid delta CRL
+ // (h)
+ deltaCRL = Rfc3280CertPathUtilities.ProcessCrlH(deltaCRLs, key);
+ }
+
+ /*
+ * CRL must be be valid at the current time, not the validation
+ * time. If a certificate is revoked with reason keyCompromise,
+ * cACompromise, it can be used for forgery, also for the past.
+ * This reason may not be contained in older CRLs.
+ */
+
+ /*
+ * in the chain model signatures stay valid also after the
+ * certificate has been expired, so they do not have to be in
+ * the CRL validity time
+ */
+
+ if (paramsPKIX.ValidityModel != PkixParameters.ChainValidityModel)
+ {
+ /*
+ * if a certificate has expired, but was revoked, it is not
+ * more in the CRL, so it would be regarded as valid if the
+ * first check is not done
+ */
+ if (cert.NotAfter.Ticks < crl.ThisUpdate.Ticks)
+ {
+ throw new Exception("No valid CRL for current time found.");
+ }
+ }
+
+ Rfc3280CertPathUtilities.ProcessCrlB1(dp, cert, crl);
+
+ // (b) (2)
+ Rfc3280CertPathUtilities.ProcessCrlB2(dp, cert, crl);
+
+ // (c)
+ Rfc3280CertPathUtilities.ProcessCrlC(deltaCRL, crl, paramsPKIX);
+
+ // (i)
+ Rfc3280CertPathUtilities.ProcessCrlI(validDate, deltaCRL, cert, certStatus, paramsPKIX);
+
+ // (j)
+ Rfc3280CertPathUtilities.ProcessCrlJ(validDate, crl, cert, certStatus);
+
+ // (k)
+ if (certStatus.Status == CrlReason.RemoveFromCrl)
+ {
+ certStatus.Status = CertStatus.Unrevoked;
+ }
+
+ // update reasons mask
+ reasonMask.AddReasons(interimReasonsMask);
+
+ ISet criticalExtensions = crl.GetCriticalExtensionOids();
+
+ if (criticalExtensions != null)
+ {
+ criticalExtensions = new HashSet(criticalExtensions);
+ criticalExtensions.Remove(X509Extensions.IssuingDistributionPoint.Id);
+ criticalExtensions.Remove(X509Extensions.DeltaCrlIndicator.Id);
+
+ if (!criticalExtensions.IsEmpty)
+ throw new Exception("CRL contains unsupported critical extensions.");
+ }
+
+ if (deltaCRL != null)
+ {
+ criticalExtensions = deltaCRL.GetCriticalExtensionOids();
+ if (criticalExtensions != null)
+ {
+ criticalExtensions = new HashSet(criticalExtensions);
+ criticalExtensions.Remove(X509Extensions.IssuingDistributionPoint.Id);
+ criticalExtensions.Remove(X509Extensions.DeltaCrlIndicator.Id);
+
+ if (!criticalExtensions.IsEmpty)
+ throw new Exception("Delta CRL contains unsupported critical extension.");
+ }
+ }
+
+ validCrlFound = true;
+ }
+ catch (Exception e)
+ {
+ lastException = e;
+ }
+ }
+ if (!validCrlFound)
+ {
+ throw lastException;
+ }
+ }
+
+ /**
+ * Checks a certificate if it is revoked.
+ *
+ * @param paramsPKIX PKIX parameters.
+ * @param cert Certificate to check if it is revoked.
+ * @param validDate The date when the certificate revocation status should be
+ * checked.
+ * @param sign The issuer certificate of the certificate cert.
+ * @param workingPublicKey The public key of the issuer certificate sign.
+ * @param certPathCerts The certificates of the certification path.
+ * @throws AnnotatedException if the certificate is revoked or the status cannot be checked
+ * or some error occurs.
+ */
+ protected static void CheckCrls(
+ PkixParameters paramsPKIX,
+ X509Certificate cert,
+ DateTime validDate,
+ X509Certificate sign,
+ AsymmetricKeyParameter workingPublicKey,
+ IList certPathCerts)
+ {
+ Exception lastException = null;
+ CrlDistPoint crldp = null;
+
+ try
+ {
+ crldp = CrlDistPoint.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.CrlDistributionPoints));
+ }
+ catch (Exception e)
+ {
+ throw new Exception("CRL distribution point extension could not be read.", e);
+ }
+
+ try
+ {
+ PkixCertPathValidatorUtilities.AddAdditionalStoresFromCrlDistributionPoint(crldp, paramsPKIX);
+ }
+ catch (Exception e)
+ {
+ throw new Exception(
+ "No additional CRL locations could be decoded from CRL distribution point extension.", e);
+ }
+ CertStatus certStatus = new CertStatus();
+ ReasonsMask reasonsMask = new ReasonsMask();
+
+ bool validCrlFound = false;
+
+ // for each distribution point
+ if (crldp != null)
+ {
+ DistributionPoint[] dps = null;
+ try
+ {
+ dps = crldp.GetDistributionPoints();
+ }
+ catch (Exception e)
+ {
+ throw new Exception("Distribution points could not be read.", e);
+ }
+ if (dps != null)
+ {
+ for (int i = 0; i < dps.Length && certStatus.Status == CertStatus.Unrevoked && !reasonsMask.IsAllReasons; i++)
+ {
+ PkixParameters paramsPKIXClone = (PkixParameters)paramsPKIX.Clone();
+ try
+ {
+ CheckCrl(dps[i], paramsPKIXClone, cert, validDate, sign, workingPublicKey, certStatus, reasonsMask, certPathCerts);
+ validCrlFound = true;
+ }
+ catch (Exception e)
+ {
+ lastException = e;
+ }
+ }
+ }
+ }
+
+ /*
+ * If the revocation status has not been determined, repeat the process
+ * above with any available CRLs not specified in a distribution point
+ * but issued by the certificate issuer.
+ */
+
+ if (certStatus.Status == CertStatus.Unrevoked && !reasonsMask.IsAllReasons)
+ {
+ try
+ {
+ /*
+ * assume a DP with both the reasons and the cRLIssuer fields
+ * omitted and a distribution point name of the certificate
+ * issuer.
+ */
+ Asn1Object issuer = null;
+ try
+ {
+ issuer = new Asn1InputStream(cert.IssuerDN.GetEncoded()).ReadObject();
+ }
+ catch (Exception e)
+ {
+ throw new Exception("Issuer from certificate for CRL could not be reencoded.", e);
+ }
+ DistributionPoint dp = new DistributionPoint(new DistributionPointName(0, new GeneralNames(
+ new GeneralName(GeneralName.DirectoryName, issuer))), null, null);
+ PkixParameters paramsPKIXClone = (PkixParameters)paramsPKIX.Clone();
+
+ CheckCrl(dp, paramsPKIXClone, cert, validDate, sign, workingPublicKey, certStatus, reasonsMask,
+ certPathCerts);
+
+ validCrlFound = true;
+ }
+ catch (Exception e)
+ {
+ lastException = e;
+ }
+ }
+
+ if (!validCrlFound)
+ {
+ throw lastException;
+ }
+ if (certStatus.Status != CertStatus.Unrevoked)
+ {
+ // This format is enforced by the NistCertPath tests
+ string formattedDate = certStatus.RevocationDate.Value.ToString(
+ "ddd MMM dd HH:mm:ss K yyyy");
+ string message = "Certificate revocation after " + formattedDate;
+ message += ", reason: " + CrlReasons[certStatus.Status];
+ throw new Exception(message);
+ }
+
+ if (!reasonsMask.IsAllReasons && certStatus.Status == CertStatus.Unrevoked)
+ {
+ certStatus.Status = CertStatus.Undetermined;
+ }
+
+ if (certStatus.Status == CertStatus.Undetermined)
+ {
+ throw new Exception("Certificate status could not be determined.");
+ }
+ }
+
+ internal static PkixPolicyNode PrepareCertB(
+ PkixCertPath certPath,
+ int index,
+ IList[] policyNodes,
+ PkixPolicyNode validPolicyTree,
+ int policyMapping)
+ //throws CertPathValidatorException
+ {
+ IList certs = certPath.Certificates;
+ X509Certificate cert = (X509Certificate)certs[index];
+ int n = certs.Count;
+ // i as defined in the algorithm description
+ int i = n - index;
+ // (b)
+ //
+ Asn1Sequence pm = null;
+ try
+ {
+ pm = (Asn1Sequence)Asn1Sequence.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.PolicyMappings));
+ }
+ catch (Exception ex)
+ {
+ throw new PkixCertPathValidatorException(
+ "Policy mappings extension could not be decoded.", ex, certPath, index);
+ }
+ PkixPolicyNode _validPolicyTree = validPolicyTree;
+ if (pm != null)
+ {
+ Asn1Sequence mappings = (Asn1Sequence)pm;
+ IDictionary m_idp = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ ISet s_idp = new HashSet();
+
+ for (int j = 0; j < mappings.Count; j++)
+ {
+ Asn1Sequence mapping = (Asn1Sequence) mappings[j];
+ string id_p = ((DerObjectIdentifier) mapping[0]).Id;
+ string sd_p = ((DerObjectIdentifier) mapping[1]).Id;
+ ISet tmp;
+
+ if (!m_idp.Contains(id_p))
+ {
+ tmp = new HashSet();
+ tmp.Add(sd_p);
+ m_idp[id_p] = tmp;
+ s_idp.Add(id_p);
+ }
+ else
+ {
+ tmp = (ISet)m_idp[id_p];
+ tmp.Add(sd_p);
+ }
+ }
+
+ IEnumerator it_idp = s_idp.GetEnumerator();
+ while (it_idp.MoveNext())
+ {
+ string id_p = (string)it_idp.Current;
+
+ //
+ // (1)
+ //
+ if (policyMapping > 0)
+ {
+ bool idp_found = false;
+ IEnumerator nodes_i = policyNodes[i].GetEnumerator();
+
+ while (nodes_i.MoveNext())
+ {
+ PkixPolicyNode node = (PkixPolicyNode)nodes_i.Current;
+ if (node.ValidPolicy.Equals(id_p))
+ {
+ idp_found = true;
+ node.ExpectedPolicies = (ISet)m_idp[id_p];
+ break;
+ }
+ }
+
+ if (!idp_found)
+ {
+ nodes_i = policyNodes[i].GetEnumerator();
+ while (nodes_i.MoveNext())
+ {
+ PkixPolicyNode node = (PkixPolicyNode)nodes_i.Current;
+ if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(node.ValidPolicy))
+ {
+ ISet pq = null;
+ Asn1Sequence policies = null;
+ try
+ {
+ policies = (Asn1Sequence)PkixCertPathValidatorUtilities.GetExtensionValue(cert,
+ X509Extensions.CertificatePolicies);
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathValidatorException(
+ "Certificate policies extension could not be decoded.", e, certPath, index);
+ }
+
+ foreach (Asn1Encodable ae in policies)
+ {
+ PolicyInformation pinfo = null;
+ try
+ {
+ pinfo = PolicyInformation.GetInstance(ae.ToAsn1Object());
+ }
+ catch (Exception ex)
+ {
+ throw new PkixCertPathValidatorException(
+ "Policy information could not be decoded.", ex, certPath, index);
+ }
+ if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(pinfo.PolicyIdentifier.Id))
+ {
+ try
+ {
+ pq = PkixCertPathValidatorUtilities
+ .GetQualifierSet(pinfo.PolicyQualifiers);
+ }
+ catch (PkixCertPathValidatorException ex)
+ {
+ throw new PkixCertPathValidatorException(
+ "Policy qualifier info set could not be decoded.", ex, certPath,
+ index);
+ }
+ break;
+ }
+ }
+ bool ci = false;
+ ISet critExtOids = cert.GetCriticalExtensionOids();
+ if (critExtOids != null)
+ {
+ ci = critExtOids.Contains(X509Extensions.CertificatePolicies.Id);
+ }
+
+ PkixPolicyNode p_node = (PkixPolicyNode)node.Parent;
+ if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(p_node.ValidPolicy))
+ {
+ PkixPolicyNode c_node = new PkixPolicyNode(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(), i,
+ (ISet)m_idp[id_p], p_node, pq, id_p, ci);
+ p_node.AddChild(c_node);
+ policyNodes[i].Add(c_node);
+ }
+ break;
+ }
+ }
+ }
+
+ //
+ // (2)
+ //
+ }
+ else if (policyMapping <= 0)
+ {
+ foreach (PkixPolicyNode node in BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(policyNodes[i]))
+ {
+ if (node.ValidPolicy.Equals(id_p))
+ {
+ node.Parent.RemoveChild(node);
+
+ for (int k = i - 1; k >= 0; k--)
+ {
+ foreach (PkixPolicyNode node2 in BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(policyNodes[k]))
+ {
+ if (!node2.HasChildren)
+ {
+ _validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode(
+ _validPolicyTree, policyNodes, node2);
+
+ if (_validPolicyTree == null)
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ return _validPolicyTree;
+ }
+
+ internal static ISet[] ProcessCrlA1ii(
+ DateTime currentDate,
+ PkixParameters paramsPKIX,
+ X509Certificate cert,
+ X509Crl crl)
+ {
+ ISet deltaSet = new HashSet();
+ X509CrlStoreSelector crlselect = new X509CrlStoreSelector();
+ crlselect.CertificateChecking = cert;
+
+ try
+ {
+ IList issuer = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ issuer.Add(crl.IssuerDN);
+ crlselect.Issuers = issuer;
+ }
+ catch (IOException e)
+ {
+ throw new Exception("Cannot extract issuer from CRL." + e, e);
+ }
+
+ crlselect.CompleteCrlEnabled = true;
+ ISet completeSet = CrlUtilities.FindCrls(crlselect, paramsPKIX, currentDate);
+
+ if (paramsPKIX.IsUseDeltasEnabled)
+ {
+ // get delta CRL(s)
+ try
+ {
+ deltaSet.AddAll(PkixCertPathValidatorUtilities.GetDeltaCrls(currentDate, paramsPKIX, crl));
+ }
+ catch (Exception e)
+ {
+ throw new Exception("Exception obtaining delta CRLs.", e);
+ }
+ }
+
+ return new ISet[]{ completeSet, deltaSet };
+ }
+
+ internal static ISet ProcessCrlA1i(
+ DateTime currentDate,
+ PkixParameters paramsPKIX,
+ X509Certificate cert,
+ X509Crl crl)
+ {
+ ISet deltaSet = new HashSet();
+ if (paramsPKIX.IsUseDeltasEnabled)
+ {
+ CrlDistPoint freshestCRL = null;
+ try
+ {
+ freshestCRL = CrlDistPoint.GetInstance(
+ PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.FreshestCrl));
+ }
+ catch (Exception e)
+ {
+ throw new Exception("Freshest CRL extension could not be decoded from certificate.", e);
+ }
+
+ if (freshestCRL == null)
+ {
+ try
+ {
+ freshestCRL = CrlDistPoint.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(crl, X509Extensions.FreshestCrl));
+ }
+ catch (Exception e)
+ {
+ throw new Exception("Freshest CRL extension could not be decoded from CRL.", e);
+ }
+ }
+ if (freshestCRL != null)
+ {
+ try
+ {
+ PkixCertPathValidatorUtilities.AddAdditionalStoresFromCrlDistributionPoint(freshestCRL, paramsPKIX);
+ }
+ catch (Exception e)
+ {
+ throw new Exception(
+ "No new delta CRL locations could be added from Freshest CRL extension.", e);
+ }
+ // get delta CRL(s)
+ try
+ {
+ deltaSet.AddAll(PkixCertPathValidatorUtilities.GetDeltaCrls(currentDate, paramsPKIX, crl));
+ }
+ catch (Exception e)
+ {
+ throw new Exception("Exception obtaining delta CRLs.", e);
+ }
+ }
+ }
+ return deltaSet;
+ }
+
+ internal static void ProcessCertF(
+ PkixCertPath certPath,
+ int index,
+ PkixPolicyNode validPolicyTree,
+ int explicitPolicy)
+ {
+ //
+ // (f)
+ //
+ if (explicitPolicy <= 0 && validPolicyTree == null)
+ {
+ throw new PkixCertPathValidatorException(
+ "No valid policy tree found when one expected.", null, certPath, index);
+ }
+ }
+
+ internal static void ProcessCertA(
+ PkixCertPath certPath,
+ PkixParameters paramsPKIX,
+ int index,
+ AsymmetricKeyParameter workingPublicKey,
+ X509Name workingIssuerName,
+ X509Certificate sign)
+ {
+ IList certs = certPath.Certificates;
+ X509Certificate cert = (X509Certificate)certs[index];
+ //
+ // (a) verify
+ //
+ try
+ {
+ // (a) (1)
+ //
+ cert.Verify(workingPublicKey);
+ }
+ catch (GeneralSecurityException e)
+ {
+ throw new PkixCertPathValidatorException("Could not validate certificate signature.", e, certPath, index);
+ }
+
+ try
+ {
+ // (a) (2)
+ //
+ cert.CheckValidity(PkixCertPathValidatorUtilities
+ .GetValidCertDateFromValidityModel(paramsPKIX, certPath, index));
+ }
+ catch (CertificateExpiredException e)
+ {
+ throw new PkixCertPathValidatorException("Could not validate certificate: " + e.Message, e, certPath, index);
+ }
+ catch (CertificateNotYetValidException e)
+ {
+ throw new PkixCertPathValidatorException("Could not validate certificate: " + e.Message, e, certPath, index);
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathValidatorException("Could not validate time of certificate.", e, certPath, index);
+ }
+
+ //
+ // (a) (3)
+ //
+ if (paramsPKIX.IsRevocationEnabled)
+ {
+ try
+ {
+ CheckCrls(paramsPKIX, cert, PkixCertPathValidatorUtilities.GetValidCertDateFromValidityModel(paramsPKIX,
+ certPath, index), sign, workingPublicKey, certs);
+ }
+ catch (Exception e)
+ {
+ Exception cause = e.InnerException;
+ if (cause == null)
+ {
+ cause = e;
+ }
+ throw new PkixCertPathValidatorException(e.Message, cause, certPath, index);
+ }
+ }
+
+ //
+ // (a) (4) name chaining
+ //
+ X509Name issuer = PkixCertPathValidatorUtilities.GetIssuerPrincipal(cert);
+ if (!issuer.Equivalent(workingIssuerName, true))
+ {
+ throw new PkixCertPathValidatorException("IssuerName(" + issuer
+ + ") does not match SubjectName(" + workingIssuerName + ") of signing certificate.", null,
+ certPath, index);
+ }
+ }
+
+ internal static int PrepareNextCertI1(
+ PkixCertPath certPath,
+ int index,
+ int explicitPolicy)
+ {
+ IList certs = certPath.Certificates;
+ X509Certificate cert = (X509Certificate)certs[index];
+ //
+ // (i)
+ //
+ Asn1Sequence pc = null;
+ try
+ {
+ pc = DerSequence.GetInstance(
+ PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.PolicyConstraints));
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathValidatorException(
+ "Policy constraints extension cannot be decoded.", e, certPath, index);
+ }
+
+ int tmpInt;
+
+ if (pc != null)
+ {
+ IEnumerator policyConstraints = pc.GetEnumerator();
+
+ while (policyConstraints.MoveNext())
+ {
+ try
+ {
+ Asn1TaggedObject constraint = Asn1TaggedObject.GetInstance(policyConstraints.Current);
+ if (constraint.TagNo == 0)
+ {
+ tmpInt = DerInteger.GetInstance(constraint, false).Value.IntValue;
+ if (tmpInt < explicitPolicy)
+ {
+ return tmpInt;
+ }
+ break;
+ }
+ }
+ catch (ArgumentException e)
+ {
+ throw new PkixCertPathValidatorException(
+ "Policy constraints extension contents cannot be decoded.", e, certPath, index);
+ }
+ }
+ }
+ return explicitPolicy;
+ }
+
+ internal static int PrepareNextCertI2(
+ PkixCertPath certPath,
+ int index,
+ int policyMapping)
+ //throws CertPathValidatorException
+ {
+ IList certs = certPath.Certificates;
+ X509Certificate cert = (X509Certificate)certs[index];
+
+ //
+ // (i)
+ //
+ Asn1Sequence pc = null;
+ try
+ {
+ pc = DerSequence.GetInstance(
+ PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.PolicyConstraints));
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathValidatorException(
+ "Policy constraints extension cannot be decoded.", e, certPath, index);
+ }
+
+ int tmpInt;
+
+ if (pc != null)
+ {
+ IEnumerator policyConstraints = pc.GetEnumerator();
+
+ while (policyConstraints.MoveNext())
+ {
+ try
+ {
+ Asn1TaggedObject constraint = Asn1TaggedObject.GetInstance(policyConstraints.Current);
+ if (constraint.TagNo == 1)
+ {
+ tmpInt = DerInteger.GetInstance(constraint, false).Value.IntValue;
+ if (tmpInt < policyMapping)
+ {
+ return tmpInt;
+ }
+ break;
+ }
+ }
+ catch (ArgumentException e)
+ {
+ throw new PkixCertPathValidatorException(
+ "Policy constraints extension contents cannot be decoded.", e, certPath, index);
+ }
+ }
+ }
+ return policyMapping;
+ }
+
+ internal static void PrepareNextCertG(
+ PkixCertPath certPath,
+ int index,
+ PkixNameConstraintValidator nameConstraintValidator)
+ //throws CertPathValidatorException
+ {
+ IList certs = certPath.Certificates;
+ X509Certificate cert = (X509Certificate)certs[index];
+
+ //
+ // (g) handle the name constraints extension
+ //
+ NameConstraints nc = null;
+ try
+ {
+ Asn1Sequence ncSeq = DerSequence.GetInstance(
+ PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.NameConstraints));
+ if (ncSeq != null)
+ {
+ nc = new NameConstraints(ncSeq);
+ }
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathValidatorException(
+ "Name constraints extension could not be decoded.", e, certPath, index);
+ }
+ if (nc != null)
+ {
+ //
+ // (g) (1) permitted subtrees
+ //
+ Asn1Sequence permitted = nc.PermittedSubtrees;
+ if (permitted != null)
+ {
+ try
+ {
+ nameConstraintValidator.IntersectPermittedSubtree(permitted);
+ }
+ catch (Exception ex)
+ {
+ throw new PkixCertPathValidatorException(
+ "Permitted subtrees cannot be build from name constraints extension.", ex, certPath, index);
+ }
+ }
+
+ //
+ // (g) (2) excluded subtrees
+ //
+ Asn1Sequence excluded = nc.ExcludedSubtrees;
+ if (excluded != null)
+ {
+ IEnumerator e = excluded.GetEnumerator();
+ try
+ {
+ while (e.MoveNext())
+ {
+ GeneralSubtree subtree = GeneralSubtree.GetInstance(e.Current);
+ nameConstraintValidator.AddExcludedSubtree(subtree);
+ }
+ }
+ catch (Exception ex)
+ {
+ throw new PkixCertPathValidatorException(
+ "Excluded subtrees cannot be build from name constraints extension.", ex, certPath, index);
+ }
+ }
+ }
+ }
+
+ internal static int PrepareNextCertJ(
+ PkixCertPath certPath,
+ int index,
+ int inhibitAnyPolicy)
+ //throws CertPathValidatorException
+ {
+ IList certs = certPath.Certificates;
+ X509Certificate cert = (X509Certificate)certs[index];
+
+ //
+ // (j)
+ //
+ DerInteger iap = null;
+ try
+ {
+ iap = DerInteger.GetInstance(
+ PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.InhibitAnyPolicy));
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathValidatorException(
+ "Inhibit any-policy extension cannot be decoded.", e, certPath, index);
+ }
+
+ if (iap != null)
+ {
+ int _inhibitAnyPolicy = iap.Value.IntValue;
+
+ if (_inhibitAnyPolicy < inhibitAnyPolicy)
+ return _inhibitAnyPolicy;
+ }
+ return inhibitAnyPolicy;
+ }
+
+ internal static void PrepareNextCertK(
+ PkixCertPath certPath,
+ int index)
+ //throws CertPathValidatorException
+ {
+ IList certs = certPath.Certificates;
+ X509Certificate cert = (X509Certificate)certs[index];
+ //
+ // (k)
+ //
+ BasicConstraints bc = null;
+ try
+ {
+ bc = BasicConstraints.GetInstance(
+ PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.BasicConstraints));
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathValidatorException("Basic constraints extension cannot be decoded.", e, certPath,
+ index);
+ }
+ if (bc != null)
+ {
+ if (!(bc.IsCA()))
+ throw new PkixCertPathValidatorException("Not a CA certificate");
+ }
+ else
+ {
+ throw new PkixCertPathValidatorException("Intermediate certificate lacks BasicConstraints");
+ }
+ }
+
+ internal static int PrepareNextCertL(
+ PkixCertPath certPath,
+ int index,
+ int maxPathLength)
+ //throws CertPathValidatorException
+ {
+ IList certs = certPath.Certificates;
+ X509Certificate cert = (X509Certificate)certs[index];
+ //
+ // (l)
+ //
+ if (!PkixCertPathValidatorUtilities.IsSelfIssued(cert))
+ {
+ if (maxPathLength <= 0)
+ {
+ throw new PkixCertPathValidatorException("Max path length not greater than zero", null, certPath, index);
+ }
+
+ return maxPathLength - 1;
+ }
+ return maxPathLength;
+ }
+
+ internal static int PrepareNextCertM(
+ PkixCertPath certPath,
+ int index,
+ int maxPathLength)
+ //throws CertPathValidatorException
+ {
+ IList certs = certPath.Certificates;
+ X509Certificate cert = (X509Certificate)certs[index];
+
+ //
+ // (m)
+ //
+ BasicConstraints bc = null;
+ try
+ {
+ bc = BasicConstraints.GetInstance(
+ PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.BasicConstraints));
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathValidatorException("Basic constraints extension cannot be decoded.", e, certPath,
+ index);
+ }
+ if (bc != null)
+ {
+ BigInteger _pathLengthConstraint = bc.PathLenConstraint;
+
+ if (_pathLengthConstraint != null)
+ {
+ int _plc = _pathLengthConstraint.IntValue;
+
+ if (_plc < maxPathLength)
+ {
+ return _plc;
+ }
+ }
+ }
+ return maxPathLength;
+ }
+
+ internal static void PrepareNextCertN(
+ PkixCertPath certPath,
+ int index)
+ //throws CertPathValidatorException
+ {
+ IList certs = certPath.Certificates;
+ X509Certificate cert = (X509Certificate)certs[index];
+
+ //
+ // (n)
+ //
+ bool[] _usage = cert.GetKeyUsage();
+
+ if ((_usage != null) && !_usage[Rfc3280CertPathUtilities.KEY_CERT_SIGN])
+ {
+ throw new PkixCertPathValidatorException(
+ "Issuer certificate keyusage extension is critical and does not permit key signing.", null,
+ certPath, index);
+ }
+ }
+
+ internal static void PrepareNextCertO(
+ PkixCertPath certPath,
+ int index,
+ ISet criticalExtensions,
+ IList pathCheckers)
+ //throws CertPathValidatorException
+ {
+ IList certs = certPath.Certificates;
+ X509Certificate cert = (X509Certificate)certs[index];
+
+ //
+ // (o)
+ //
+ IEnumerator tmpIter = pathCheckers.GetEnumerator();
+ while (tmpIter.MoveNext())
+ {
+ try
+ {
+ ((PkixCertPathChecker)tmpIter.Current).Check(cert, criticalExtensions);
+ }
+ catch (PkixCertPathValidatorException e)
+ {
+ throw new PkixCertPathValidatorException(e.Message, e.InnerException, certPath, index);
+ }
+ }
+ if (!criticalExtensions.IsEmpty)
+ {
+ throw new PkixCertPathValidatorException("Certificate has unsupported critical extension.", null, certPath,
+ index);
+ }
+ }
+
+ internal static int PrepareNextCertH1(
+ PkixCertPath certPath,
+ int index,
+ int explicitPolicy)
+ {
+ IList certs = certPath.Certificates;
+ X509Certificate cert = (X509Certificate)certs[index];
+
+ //
+ // (h)
+ //
+ if (!PkixCertPathValidatorUtilities.IsSelfIssued(cert))
+ {
+ //
+ // (1)
+ //
+ if (explicitPolicy != 0)
+ return explicitPolicy - 1;
+ }
+ return explicitPolicy;
+ }
+
+ internal static int PrepareNextCertH2(
+ PkixCertPath certPath,
+ int index,
+ int policyMapping)
+ {
+ IList certs = certPath.Certificates;
+ X509Certificate cert = (X509Certificate)certs[index];
+
+ //
+ // (h)
+ //
+ if (!PkixCertPathValidatorUtilities.IsSelfIssued(cert))
+ {
+ //
+ // (2)
+ //
+ if (policyMapping != 0)
+ return policyMapping - 1;
+ }
+ return policyMapping;
+ }
+
+
+ internal static int PrepareNextCertH3(
+ PkixCertPath certPath,
+ int index,
+ int inhibitAnyPolicy)
+ {
+ IList certs = certPath.Certificates;
+ X509Certificate cert = (X509Certificate)certs[index];
+
+ //
+ // (h)
+ //
+ if (!PkixCertPathValidatorUtilities.IsSelfIssued(cert))
+ {
+ //
+ // (3)
+ //
+ if (inhibitAnyPolicy != 0)
+ return inhibitAnyPolicy - 1;
+ }
+ return inhibitAnyPolicy;
+ }
+
+ internal static int WrapupCertA(
+ int explicitPolicy,
+ X509Certificate cert)
+ {
+ //
+ // (a)
+ //
+ if (!PkixCertPathValidatorUtilities.IsSelfIssued(cert) && (explicitPolicy != 0))
+ {
+ explicitPolicy--;
+ }
+ return explicitPolicy;
+ }
+
+ internal static int WrapupCertB(
+ PkixCertPath certPath,
+ int index,
+ int explicitPolicy)
+ //throws CertPathValidatorException
+ {
+ IList certs = certPath.Certificates;
+ X509Certificate cert = (X509Certificate)certs[index];
+
+ //
+ // (b)
+ //
+ int tmpInt;
+ Asn1Sequence pc = null;
+ try
+ {
+ pc = DerSequence.GetInstance(
+ PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.PolicyConstraints));
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathValidatorException("Policy constraints could not be decoded.", e, certPath, index);
+ }
+
+ if (pc != null)
+ {
+ IEnumerator policyConstraints = pc.GetEnumerator();
+
+ while (policyConstraints.MoveNext())
+ {
+ Asn1TaggedObject constraint = (Asn1TaggedObject)policyConstraints.Current;
+ switch (constraint.TagNo)
+ {
+ case 0:
+ try
+ {
+ tmpInt = DerInteger.GetInstance(constraint, false).Value.IntValue;
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathValidatorException(
+ "Policy constraints requireExplicitPolicy field could not be decoded.", e, certPath,
+ index);
+ }
+ if (tmpInt == 0)
+ {
+ return 0;
+ }
+ break;
+ }
+ }
+ }
+ return explicitPolicy;
+ }
+
+ internal static void WrapupCertF(
+ PkixCertPath certPath,
+ int index,
+ IList pathCheckers,
+ ISet criticalExtensions)
+ //throws CertPathValidatorException
+ {
+ IList certs = certPath.Certificates;
+ X509Certificate cert = (X509Certificate)certs[index];
+ IEnumerator tmpIter = pathCheckers.GetEnumerator();
+
+ while (tmpIter.MoveNext())
+ {
+ try
+ {
+ ((PkixCertPathChecker)tmpIter.Current).Check(cert, criticalExtensions);
+ }
+ catch (PkixCertPathValidatorException e)
+ {
+ throw new PkixCertPathValidatorException("Additional certificate path checker failed.", e, certPath,
+ index);
+ }
+ }
+
+ if (!criticalExtensions.IsEmpty)
+ {
+ throw new PkixCertPathValidatorException("Certificate has unsupported critical extension",
+ null, certPath, index);
+ }
+ }
+
+ internal static PkixPolicyNode WrapupCertG(
+ PkixCertPath certPath,
+ PkixParameters paramsPKIX,
+ ISet userInitialPolicySet,
+ int index,
+ IList[] policyNodes,
+ PkixPolicyNode validPolicyTree,
+ ISet acceptablePolicies)
+ {
+ int n = certPath.Certificates.Count;
+
+ //
+ // (g)
+ //
+ PkixPolicyNode intersection;
+
+ //
+ // (g) (i)
+ //
+ if (validPolicyTree == null)
+ {
+ if (paramsPKIX.IsExplicitPolicyRequired)
+ {
+ throw new PkixCertPathValidatorException(
+ "Explicit policy requested but none available.", null, certPath, index);
+ }
+ intersection = null;
+ }
+ else if (PkixCertPathValidatorUtilities.IsAnyPolicy(userInitialPolicySet)) // (g)
+ // (ii)
+ {
+ if (paramsPKIX.IsExplicitPolicyRequired)
+ {
+ if (acceptablePolicies.IsEmpty)
+ {
+ throw new PkixCertPathValidatorException(
+ "Explicit policy requested but none available.", null, certPath, index);
+ }
+ else
+ {
+ ISet _validPolicyNodeSet = new HashSet();
+
+ for (int j = 0; j < policyNodes.Length; j++)
+ {
+ IList _nodeDepth = policyNodes[j];
+
+ for (int k = 0; k < _nodeDepth.Count; k++)
+ {
+ PkixPolicyNode _node = (PkixPolicyNode)_nodeDepth[k];
+
+ if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(_node.ValidPolicy))
+ {
+ foreach (object o in _node.Children)
+ {
+ _validPolicyNodeSet.Add(o);
+ }
+ }
+ }
+ }
+
+ foreach (PkixPolicyNode _node in _validPolicyNodeSet)
+ {
+ string _validPolicy = _node.ValidPolicy;
+
+ if (!acceptablePolicies.Contains(_validPolicy))
+ {
+ // TODO?
+ // validPolicyTree =
+ // removePolicyNode(validPolicyTree, policyNodes,
+ // _node);
+ }
+ }
+ if (validPolicyTree != null)
+ {
+ for (int j = (n - 1); j >= 0; j--)
+ {
+ IList nodes = policyNodes[j];
+
+ for (int k = 0; k < nodes.Count; k++)
+ {
+ PkixPolicyNode node = (PkixPolicyNode)nodes[k];
+ if (!node.HasChildren)
+ {
+ validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode(validPolicyTree,
+ policyNodes, node);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ intersection = validPolicyTree;
+ }
+ else
+ {
+ //
+ // (g) (iii)
+ //
+ // This implementation is not exactly same as the one described in
+ // RFC3280.
+ // However, as far as the validation result is concerned, both
+ // produce
+ // adequate result. The only difference is whether AnyPolicy is
+ // remain
+ // in the policy tree or not.
+ //
+ // (g) (iii) 1
+ //
+ ISet _validPolicyNodeSet = new HashSet();
+
+ for (int j = 0; j < policyNodes.Length; j++)
+ {
+ IList _nodeDepth = policyNodes[j];
+
+ for (int k = 0; k < _nodeDepth.Count; k++)
+ {
+ PkixPolicyNode _node = (PkixPolicyNode)_nodeDepth[k];
+
+ if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(_node.ValidPolicy))
+ {
+ foreach (PkixPolicyNode _c_node in _node.Children)
+ {
+ if (!Rfc3280CertPathUtilities.ANY_POLICY.Equals(_c_node.ValidPolicy))
+ {
+ _validPolicyNodeSet.Add(_c_node);
+ }
+ }
+ }
+ }
+ }
+
+ //
+ // (g) (iii) 2
+ //
+ IEnumerator _vpnsIter = _validPolicyNodeSet.GetEnumerator();
+ while (_vpnsIter.MoveNext())
+ {
+ PkixPolicyNode _node = (PkixPolicyNode)_vpnsIter.Current;
+ string _validPolicy = _node.ValidPolicy;
+
+ if (!userInitialPolicySet.Contains(_validPolicy))
+ {
+ validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode(validPolicyTree, policyNodes, _node);
+ }
+ }
+
+ //
+ // (g) (iii) 4
+ //
+ if (validPolicyTree != null)
+ {
+ for (int j = (n - 1); j >= 0; j--)
+ {
+ IList nodes = policyNodes[j];
+
+ for (int k = 0; k < nodes.Count; k++)
+ {
+ PkixPolicyNode node = (PkixPolicyNode)nodes[k];
+ if (!node.HasChildren)
+ {
+ validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode(validPolicyTree, policyNodes,
+ node);
+ }
+ }
+ }
+ }
+
+ intersection = validPolicyTree;
+ }
+ return intersection;
+ }
+
+ /**
+ * If use-deltas is set, verify the issuer and scope of the delta CRL.
+ *
+ * @param deltaCRL The delta CRL.
+ * @param completeCRL The complete CRL.
+ * @param pkixParams The PKIX paramaters.
+ * @throws AnnotatedException if an exception occurs.
+ */
+ internal static void ProcessCrlC(
+ X509Crl deltaCRL,
+ X509Crl completeCRL,
+ PkixParameters pkixParams)
+ {
+ if (deltaCRL == null)
+ return;
+
+ IssuingDistributionPoint completeidp = null;
+ try
+ {
+ completeidp = IssuingDistributionPoint.GetInstance(
+ PkixCertPathValidatorUtilities.GetExtensionValue(completeCRL, X509Extensions.IssuingDistributionPoint));
+ }
+ catch (Exception e)
+ {
+ throw new Exception("000 Issuing distribution point extension could not be decoded.", e);
+ }
+
+ if (pkixParams.IsUseDeltasEnabled)
+ {
+ // (c) (1)
+ if (!deltaCRL.IssuerDN.Equivalent(completeCRL.IssuerDN, true))
+ throw new Exception("Complete CRL issuer does not match delta CRL issuer.");
+
+ // (c) (2)
+ IssuingDistributionPoint deltaidp = null;
+ try
+ {
+ deltaidp = IssuingDistributionPoint.GetInstance(
+ PkixCertPathValidatorUtilities.GetExtensionValue(deltaCRL, X509Extensions.IssuingDistributionPoint));
+ }
+ catch (Exception e)
+ {
+ throw new Exception(
+ "Issuing distribution point extension from delta CRL could not be decoded.", e);
+ }
+
+ if (!BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(completeidp, deltaidp))
+ {
+ throw new Exception(
+ "Issuing distribution point extension from delta CRL and complete CRL does not match.");
+ }
+
+ // (c) (3)
+ Asn1Object completeKeyIdentifier = null;
+ try
+ {
+ completeKeyIdentifier = PkixCertPathValidatorUtilities.GetExtensionValue(
+ completeCRL, X509Extensions.AuthorityKeyIdentifier);
+ }
+ catch (Exception e)
+ {
+ throw new Exception(
+ "Authority key identifier extension could not be extracted from complete CRL.", e);
+ }
+
+ Asn1Object deltaKeyIdentifier = null;
+ try
+ {
+ deltaKeyIdentifier = PkixCertPathValidatorUtilities.GetExtensionValue(
+ deltaCRL, X509Extensions.AuthorityKeyIdentifier);
+ }
+ catch (Exception e)
+ {
+ throw new Exception(
+ "Authority key identifier extension could not be extracted from delta CRL.", e);
+ }
+
+ if (completeKeyIdentifier == null)
+ throw new Exception("CRL authority key identifier is null.");
+
+ if (deltaKeyIdentifier == null)
+ throw new Exception("Delta CRL authority key identifier is null.");
+
+ if (!completeKeyIdentifier.Equals(deltaKeyIdentifier))
+ {
+ throw new Exception(
+ "Delta CRL authority key identifier does not match complete CRL authority key identifier.");
+ }
+ }
+ }
+
+ internal static void ProcessCrlI(
+ DateTime validDate,
+ X509Crl deltacrl,
+ object cert,
+ CertStatus certStatus,
+ PkixParameters pkixParams)
+ {
+ if (pkixParams.IsUseDeltasEnabled && deltacrl != null)
+ {
+ PkixCertPathValidatorUtilities.GetCertStatus(validDate, deltacrl, cert, certStatus);
+ }
+ }
+
+ internal static void ProcessCrlJ(
+ DateTime validDate,
+ X509Crl completecrl,
+ object cert,
+ CertStatus certStatus)
+ {
+ if (certStatus.Status == CertStatus.Unrevoked)
+ {
+ PkixCertPathValidatorUtilities.GetCertStatus(validDate, completecrl, cert, certStatus);
+ }
+ }
+
+ internal static PkixPolicyNode ProcessCertE(
+ PkixCertPath certPath,
+ int index,
+ PkixPolicyNode validPolicyTree)
+ {
+ IList certs = certPath.Certificates;
+ X509Certificate cert = (X509Certificate)certs[index];
+
+ //
+ // (e)
+ //
+ Asn1Sequence certPolicies = null;
+ try
+ {
+ certPolicies = DerSequence.GetInstance(
+ PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.CertificatePolicies));
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathValidatorException("Could not read certificate policies extension from certificate.",
+ e, certPath, index);
+ }
+ if (certPolicies == null)
+ {
+ validPolicyTree = null;
+ }
+ return validPolicyTree;
+ }
+
+ internal static readonly string[] CrlReasons = new string[]
+ {
+ "unspecified",
+ "keyCompromise",
+ "cACompromise",
+ "affiliationChanged",
+ "superseded",
+ "cessationOfOperation",
+ "certificateHold",
+ "unknown",
+ "removeFromCRL",
+ "privilegeWithdrawn",
+ "aACompromise"
+ };
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/Rfc3280CertPathUtilities.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/Rfc3280CertPathUtilities.cs.meta
new file mode 100644
index 00000000..f55d9c9d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/Rfc3280CertPathUtilities.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 6b4b0eb500c7b0446b1ae401484cb0ac
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/Rfc3281CertPathUtilities.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/Rfc3281CertPathUtilities.cs
new file mode 100644
index 00000000..41ca1296
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/Rfc3281CertPathUtilities.cs
@@ -0,0 +1,612 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.Globalization;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix
+{
+ internal class Rfc3281CertPathUtilities
+ {
+ internal static void ProcessAttrCert7(
+ IX509AttributeCertificate attrCert,
+ PkixCertPath certPath,
+ PkixCertPath holderCertPath,
+ PkixParameters pkixParams)
+ {
+ // TODO:
+ // AA Controls
+ // Attribute encryption
+ // Proxy
+ ISet critExtOids = attrCert.GetCriticalExtensionOids();
+
+ // 7.1
+ // process extensions
+
+ // target information checked in step 6 / X509AttributeCertStoreSelector
+ if (critExtOids.Contains(X509Extensions.TargetInformation.Id))
+ {
+ try
+ {
+ TargetInformation.GetInstance(PkixCertPathValidatorUtilities
+ .GetExtensionValue(attrCert, X509Extensions.TargetInformation));
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathValidatorException(
+ "Target information extension could not be read.", e);
+ }
+ }
+ critExtOids.Remove(X509Extensions.TargetInformation.Id);
+ foreach (PkixAttrCertChecker checker in pkixParams.GetAttrCertCheckers())
+ {
+ checker.Check(attrCert, certPath, holderCertPath, critExtOids);
+ }
+ if (!critExtOids.IsEmpty)
+ {
+ throw new PkixCertPathValidatorException(
+ "Attribute certificate contains unsupported critical extensions: "
+ + critExtOids);
+ }
+ }
+
+ /**
+ * Checks if an attribute certificate is revoked.
+ *
+ * @param attrCert Attribute certificate to check if it is revoked.
+ * @param paramsPKIX PKIX parameters.
+ * @param issuerCert The issuer certificate of the attribute certificate
+ * attrCert.
+ * @param validDate The date when the certificate revocation status should
+ * be checked.
+ * @param certPathCerts The certificates of the certification path to be
+ * checked.
+ *
+ * @throws CertPathValidatorException if the certificate is revoked or the
+ * status cannot be checked or some error occurs.
+ */
+ internal static void CheckCrls(
+ IX509AttributeCertificate attrCert,
+ PkixParameters paramsPKIX,
+ X509Certificate issuerCert,
+ DateTime validDate,
+ IList certPathCerts)
+ {
+ if (paramsPKIX.IsRevocationEnabled)
+ {
+ // check if revocation is available
+ if (attrCert.GetExtensionValue(X509Extensions.NoRevAvail) == null)
+ {
+ CrlDistPoint crldp = null;
+ try
+ {
+ crldp = CrlDistPoint.GetInstance(
+ PkixCertPathValidatorUtilities.GetExtensionValue(
+ attrCert, X509Extensions.CrlDistributionPoints));
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathValidatorException(
+ "CRL distribution point extension could not be read.", e);
+ }
+ try
+ {
+ PkixCertPathValidatorUtilities
+ .AddAdditionalStoresFromCrlDistributionPoint(crldp, paramsPKIX);
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathValidatorException(
+ "No additional CRL locations could be decoded from CRL distribution point extension.", e);
+ }
+ CertStatus certStatus = new CertStatus();
+ ReasonsMask reasonsMask = new ReasonsMask();
+
+ Exception lastException = null;
+ bool validCrlFound = false;
+ // for each distribution point
+ if (crldp != null)
+ {
+ DistributionPoint[] dps = null;
+ try
+ {
+ dps = crldp.GetDistributionPoints();
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathValidatorException(
+ "Distribution points could not be read.", e);
+ }
+ try
+ {
+ for (int i = 0; i < dps.Length
+ && certStatus.Status == CertStatus.Unrevoked
+ && !reasonsMask.IsAllReasons; i++)
+ {
+ PkixParameters paramsPKIXClone = (PkixParameters) paramsPKIX
+ .Clone();
+ CheckCrl(dps[i], attrCert, paramsPKIXClone,
+ validDate, issuerCert, certStatus, reasonsMask,
+ certPathCerts);
+ validCrlFound = true;
+ }
+ }
+ catch (Exception e)
+ {
+ lastException = new Exception(
+ "No valid CRL for distribution point found.", e);
+ }
+ }
+
+ /*
+ * If the revocation status has not been determined, repeat the
+ * process above with any available CRLs not specified in a
+ * distribution point but issued by the certificate issuer.
+ */
+
+ if (certStatus.Status == CertStatus.Unrevoked
+ && !reasonsMask.IsAllReasons)
+ {
+ try
+ {
+ /*
+ * assume a DP with both the reasons and the cRLIssuer
+ * fields omitted and a distribution point name of the
+ * certificate issuer.
+ */
+ Asn1Object issuer = null;
+ try
+ {
+ issuer = new Asn1InputStream(
+ attrCert.Issuer.GetPrincipals()[0].GetEncoded()).ReadObject();
+ }
+ catch (Exception e)
+ {
+ throw new Exception(
+ "Issuer from certificate for CRL could not be reencoded.",
+ e);
+ }
+ DistributionPoint dp = new DistributionPoint(
+ new DistributionPointName(0, new GeneralNames(
+ new GeneralName(GeneralName.DirectoryName, issuer))), null, null);
+ PkixParameters paramsPKIXClone = (PkixParameters) paramsPKIX.Clone();
+ CheckCrl(dp, attrCert, paramsPKIXClone, validDate,
+ issuerCert, certStatus, reasonsMask, certPathCerts);
+ validCrlFound = true;
+ }
+ catch (Exception e)
+ {
+ lastException = new Exception(
+ "No valid CRL for distribution point found.", e);
+ }
+ }
+
+ if (!validCrlFound)
+ {
+ throw new PkixCertPathValidatorException(
+ "No valid CRL found.", lastException);
+ }
+ if (certStatus.Status != CertStatus.Unrevoked)
+ {
+ // This format is enforced by the NistCertPath tests
+ string formattedDate = certStatus.RevocationDate.Value.ToString(
+ "ddd MMM dd HH:mm:ss K yyyy");
+ string message = "Attribute certificate revocation after "
+ + formattedDate;
+ message += ", reason: "
+ + Rfc3280CertPathUtilities.CrlReasons[certStatus.Status];
+ throw new PkixCertPathValidatorException(message);
+ }
+ if (!reasonsMask.IsAllReasons
+ && certStatus.Status == CertStatus.Unrevoked)
+ {
+ certStatus.Status = CertStatus.Undetermined;
+ }
+ if (certStatus.Status == CertStatus.Undetermined)
+ {
+ throw new PkixCertPathValidatorException(
+ "Attribute certificate status could not be determined.");
+ }
+
+ }
+ else
+ {
+ if (attrCert.GetExtensionValue(X509Extensions.CrlDistributionPoints) != null
+ || attrCert.GetExtensionValue(X509Extensions.AuthorityInfoAccess) != null)
+ {
+ throw new PkixCertPathValidatorException(
+ "No rev avail extension is set, but also an AC revocation pointer.");
+ }
+ }
+ }
+ }
+
+ internal static void AdditionalChecks(
+ IX509AttributeCertificate attrCert,
+ PkixParameters pkixParams)
+ {
+ // 1
+ foreach (string oid in pkixParams.GetProhibitedACAttributes())
+ {
+ if (attrCert.GetAttributes(oid) != null)
+ {
+ throw new PkixCertPathValidatorException(
+ "Attribute certificate contains prohibited attribute: "
+ + oid + ".");
+ }
+ }
+ foreach (string oid in pkixParams.GetNecessaryACAttributes())
+ {
+ if (attrCert.GetAttributes(oid) == null)
+ {
+ throw new PkixCertPathValidatorException(
+ "Attribute certificate does not contain necessary attribute: "
+ + oid + ".");
+ }
+ }
+ }
+
+ internal static void ProcessAttrCert5(
+ IX509AttributeCertificate attrCert,
+ PkixParameters pkixParams)
+ {
+ try
+ {
+ attrCert.CheckValidity(PkixCertPathValidatorUtilities.GetValidDate(pkixParams));
+ }
+ catch (CertificateExpiredException e)
+ {
+ throw new PkixCertPathValidatorException(
+ "Attribute certificate is not valid.", e);
+ }
+ catch (CertificateNotYetValidException e)
+ {
+ throw new PkixCertPathValidatorException(
+ "Attribute certificate is not valid.", e);
+ }
+ }
+
+ internal static void ProcessAttrCert4(
+ X509Certificate acIssuerCert,
+ PkixParameters pkixParams)
+ {
+ ISet set = pkixParams.GetTrustedACIssuers();
+ bool trusted = false;
+ foreach (TrustAnchor anchor in set)
+ {
+ IDictionary symbols = X509Name.RFC2253Symbols;
+ if (acIssuerCert.SubjectDN.ToString(false, symbols).Equals(anchor.CAName)
+ || acIssuerCert.Equals(anchor.TrustedCert))
+ {
+ trusted = true;
+ }
+ }
+ if (!trusted)
+ {
+ throw new PkixCertPathValidatorException(
+ "Attribute certificate issuer is not directly trusted.");
+ }
+ }
+
+ internal static void ProcessAttrCert3(
+ X509Certificate acIssuerCert,
+ PkixParameters pkixParams)
+ {
+ if (acIssuerCert.GetKeyUsage() != null
+ && (!acIssuerCert.GetKeyUsage()[0] && !acIssuerCert.GetKeyUsage()[1]))
+ {
+ throw new PkixCertPathValidatorException(
+ "Attribute certificate issuer public key cannot be used to validate digital signatures.");
+ }
+ if (acIssuerCert.GetBasicConstraints() != -1)
+ {
+ throw new PkixCertPathValidatorException(
+ "Attribute certificate issuer is also a public key certificate issuer.");
+ }
+ }
+
+ internal static PkixCertPathValidatorResult ProcessAttrCert2(
+ PkixCertPath certPath,
+ PkixParameters pkixParams)
+ {
+ PkixCertPathValidator validator = new PkixCertPathValidator();
+
+ try
+ {
+ return validator.Validate(certPath, pkixParams);
+ }
+ catch (PkixCertPathValidatorException e)
+ {
+ throw new PkixCertPathValidatorException(
+ "Certification path for issuer certificate of attribute certificate could not be validated.",
+ e);
+ }
+ }
+
+ /**
+ * Searches for a holder public key certificate and verifies its
+ * certification path.
+ *
+ * @param attrCert the attribute certificate.
+ * @param pkixParams The PKIX parameters.
+ * @return The certificate path of the holder certificate.
+ * @throws Exception if
+ *
+ *
no public key certificate can be found although holder
+ * information is given by an entity name or a base certificate
+ * ID
+ *
support classes cannot be created
+ *
no certification path for the public key certificate can
+ * be built
+ *
+ */
+ internal static PkixCertPath ProcessAttrCert1(
+ IX509AttributeCertificate attrCert,
+ PkixParameters pkixParams)
+ {
+ PkixCertPathBuilderResult result = null;
+ // find holder PKCs
+ ISet holderPKCs = new HashSet();
+ if (attrCert.Holder.GetIssuer() != null)
+ {
+ X509CertStoreSelector selector = new X509CertStoreSelector();
+ selector.SerialNumber = attrCert.Holder.SerialNumber;
+ X509Name[] principals = attrCert.Holder.GetIssuer();
+ for (int i = 0; i < principals.Length; i++)
+ {
+ try
+ {
+// if (principals[i] is X500Principal)
+ {
+ selector.Issuer = principals[i];
+ }
+ holderPKCs.AddAll(PkixCertPathValidatorUtilities
+ .FindCertificates(selector, pkixParams.GetStores()));
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathValidatorException(
+ "Public key certificate for attribute certificate cannot be searched.",
+ e);
+ }
+ }
+ if (holderPKCs.IsEmpty)
+ {
+ throw new PkixCertPathValidatorException(
+ "Public key certificate specified in base certificate ID for attribute certificate cannot be found.");
+ }
+ }
+ if (attrCert.Holder.GetEntityNames() != null)
+ {
+ X509CertStoreSelector selector = new X509CertStoreSelector();
+ X509Name[] principals = attrCert.Holder.GetEntityNames();
+ for (int i = 0; i < principals.Length; i++)
+ {
+ try
+ {
+// if (principals[i] is X500Principal)
+ {
+ selector.Issuer = principals[i];
+ }
+ holderPKCs.AddAll(PkixCertPathValidatorUtilities
+ .FindCertificates(selector, pkixParams.GetStores()));
+ }
+ catch (Exception e)
+ {
+ throw new PkixCertPathValidatorException(
+ "Public key certificate for attribute certificate cannot be searched.",
+ e);
+ }
+ }
+ if (holderPKCs.IsEmpty)
+ {
+ throw new PkixCertPathValidatorException(
+ "Public key certificate specified in entity name for attribute certificate cannot be found.");
+ }
+ }
+
+ // verify cert paths for PKCs
+ PkixBuilderParameters parameters = (PkixBuilderParameters)
+ PkixBuilderParameters.GetInstance(pkixParams);
+
+ PkixCertPathValidatorException lastException = null;
+ foreach (X509Certificate cert in holderPKCs)
+ {
+ X509CertStoreSelector selector = new X509CertStoreSelector();
+ selector.Certificate = cert;
+ parameters.SetTargetConstraints(selector);
+
+ PkixCertPathBuilder builder = new PkixCertPathBuilder();
+
+ try
+ {
+ result = builder.Build(PkixBuilderParameters.GetInstance(parameters));
+ }
+ catch (PkixCertPathBuilderException e)
+ {
+ lastException = new PkixCertPathValidatorException(
+ "Certification path for public key certificate of attribute certificate could not be build.",
+ e);
+ }
+ }
+ if (lastException != null)
+ {
+ throw lastException;
+ }
+ return result.CertPath;
+ }
+
+ /**
+ *
+ * Checks a distribution point for revocation information for the
+ * certificate attrCert.
+ *
+ * @param dp The distribution point to consider.
+ * @param attrCert The attribute certificate which should be checked.
+ * @param paramsPKIX PKIX parameters.
+ * @param validDate The date when the certificate revocation status should
+ * be checked.
+ * @param issuerCert Certificate to check if it is revoked.
+ * @param reasonMask The reasons mask which is already checked.
+ * @param certPathCerts The certificates of the certification path to be
+ * checked.
+ * @throws Exception if the certificate is revoked or the status
+ * cannot be checked or some error occurs.
+ */
+ private static void CheckCrl(
+ DistributionPoint dp,
+ IX509AttributeCertificate attrCert,
+ PkixParameters paramsPKIX,
+ DateTime validDate,
+ X509Certificate issuerCert,
+ CertStatus certStatus,
+ ReasonsMask reasonMask,
+ IList certPathCerts)
+ {
+ /*
+ * 4.3.6 No Revocation Available
+ *
+ * The noRevAvail extension, defined in [X.509-2000], allows an AC
+ * issuer to indicate that no revocation information will be made
+ * available for this AC.
+ */
+ if (attrCert.GetExtensionValue(X509Extensions.NoRevAvail) != null)
+ {
+ return;
+ }
+
+ DateTime currentDate = DateTime.UtcNow;
+ if (validDate.CompareTo(currentDate) > 0)
+ {
+ throw new Exception("Validation time is in future.");
+ }
+
+ // (a)
+ /*
+ * We always get timely valid CRLs, so there is no step (a) (1).
+ * "locally cached" CRLs are assumed to be in getStore(), additional
+ * CRLs must be enabled in the ExtendedPkixParameters and are in
+ * getAdditionalStore()
+ */
+ ISet crls = PkixCertPathValidatorUtilities.GetCompleteCrls(dp, attrCert,
+ currentDate, paramsPKIX);
+ bool validCrlFound = false;
+ Exception lastException = null;
+
+ IEnumerator crl_iter = crls.GetEnumerator();
+
+ while (crl_iter.MoveNext()
+ && certStatus.Status == CertStatus.Unrevoked
+ && !reasonMask.IsAllReasons)
+ {
+ try
+ {
+ X509Crl crl = (X509Crl) crl_iter.Current;
+
+ // (d)
+ ReasonsMask interimReasonsMask = Rfc3280CertPathUtilities.ProcessCrlD(crl, dp);
+
+ // (e)
+ /*
+ * The reasons mask is updated at the end, so only valid CRLs
+ * can update it. If this CRL does not contain new reasons it
+ * must be ignored.
+ */
+ if (!interimReasonsMask.HasNewReasons(reasonMask))
+ {
+ continue;
+ }
+
+ // (f)
+ ISet keys = Rfc3280CertPathUtilities.ProcessCrlF(crl, attrCert,
+ null, null, paramsPKIX, certPathCerts);
+ // (g)
+ AsymmetricKeyParameter pubKey = Rfc3280CertPathUtilities.ProcessCrlG(crl, keys);
+
+ X509Crl deltaCRL = null;
+
+ if (paramsPKIX.IsUseDeltasEnabled)
+ {
+ // get delta CRLs
+ ISet deltaCRLs = PkixCertPathValidatorUtilities.GetDeltaCrls(
+ currentDate, paramsPKIX, crl);
+ // we only want one valid delta CRL
+ // (h)
+ deltaCRL = Rfc3280CertPathUtilities.ProcessCrlH(deltaCRLs, pubKey);
+ }
+
+ /*
+ * CRL must be be valid at the current time, not the validation
+ * time. If a certificate is revoked with reason keyCompromise,
+ * cACompromise, it can be used for forgery, also for the past.
+ * This reason may not be contained in older CRLs.
+ */
+
+ /*
+ * in the chain model signatures stay valid also after the
+ * certificate has been expired, so they do not have to be in
+ * the CRL vality time
+ */
+ if (paramsPKIX.ValidityModel != PkixParameters.ChainValidityModel)
+ {
+ /*
+ * if a certificate has expired, but was revoked, it is not
+ * more in the CRL, so it would be regarded as valid if the
+ * first check is not done
+ */
+ if (attrCert.NotAfter.CompareTo(crl.ThisUpdate) < 0)
+ {
+ throw new Exception(
+ "No valid CRL for current time found.");
+ }
+ }
+
+ Rfc3280CertPathUtilities.ProcessCrlB1(dp, attrCert, crl);
+
+ // (b) (2)
+ Rfc3280CertPathUtilities.ProcessCrlB2(dp, attrCert, crl);
+
+ // (c)
+ Rfc3280CertPathUtilities.ProcessCrlC(deltaCRL, crl, paramsPKIX);
+
+ // (i)
+ Rfc3280CertPathUtilities.ProcessCrlI(validDate, deltaCRL,
+ attrCert, certStatus, paramsPKIX);
+
+ // (j)
+ Rfc3280CertPathUtilities.ProcessCrlJ(validDate, crl, attrCert,
+ certStatus);
+
+ // (k)
+ if (certStatus.Status == CrlReason.RemoveFromCrl)
+ {
+ certStatus.Status = CertStatus.Unrevoked;
+ }
+
+ // update reasons mask
+ reasonMask.AddReasons(interimReasonsMask);
+ validCrlFound = true;
+ }
+ catch (Exception e)
+ {
+ lastException = e;
+ }
+ }
+ if (!validCrlFound)
+ {
+ throw lastException;
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/Rfc3281CertPathUtilities.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/Rfc3281CertPathUtilities.cs.meta
new file mode 100644
index 00000000..430c5cf4
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/Rfc3281CertPathUtilities.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: d710687c541762b48abd98c0e1a2246c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/TrustAnchor.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/TrustAnchor.cs
new file mode 100644
index 00000000..acc654a0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/TrustAnchor.cs
@@ -0,0 +1,263 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix
+{
+ ///
+ /// A trust anchor or most-trusted Certification Authority (CA).
+ ///
+ /// This class represents a "most-trusted CA", which is used as a trust anchor
+ /// for validating X.509 certification paths. A most-trusted CA includes the
+ /// public key of the CA, the CA's name, and any constraints upon the set of
+ /// paths which may be validated using this key. These parameters can be
+ /// specified in the form of a trusted X509Certificate or as individual
+ /// parameters.
+ ///
+ public class TrustAnchor
+ {
+ private readonly AsymmetricKeyParameter pubKey;
+ private readonly string caName;
+ private readonly X509Name caPrincipal;
+ private readonly X509Certificate trustedCert;
+ private byte[] ncBytes;
+ private NameConstraints nc;
+
+ ///
+ /// Creates an instance of TrustAnchor with the specified X509Certificate and
+ /// optional name constraints, which are intended to be used as additional
+ /// constraints when validating an X.509 certification path.
+ /// The name constraints are specified as a byte array. This byte array
+ /// should contain the DER encoded form of the name constraints, as they
+ /// would appear in the NameConstraints structure defined in RFC 2459 and
+ /// X.509. The ASN.1 definition of this structure appears below.
+ ///
+ ///
+ ///
+ /// Note that the name constraints byte array supplied is cloned to protect
+ /// against subsequent modifications.
+ ///
+ /// a trusted X509Certificate
+ /// a byte array containing the ASN.1 DER encoding of a
+ /// NameConstraints extension to be used for checking name
+ /// constraints. Only the value of the extension is included, not
+ /// the OID or criticality flag. Specify null to omit the
+ /// parameter.
+ /// if the specified X509Certificate is null
+ public TrustAnchor(
+ X509Certificate trustedCert,
+ byte[] nameConstraints)
+ {
+ if (trustedCert == null)
+ throw new ArgumentNullException("trustedCert");
+
+ this.trustedCert = trustedCert;
+ this.pubKey = null;
+ this.caName = null;
+ this.caPrincipal = null;
+ setNameConstraints(nameConstraints);
+ }
+
+ ///
+ /// Creates an instance of TrustAnchor where the
+ /// most-trusted CA is specified as an X500Principal and public key.
+ ///
+ ///
+ ///
+ /// Name constraints are an optional parameter, and are intended to be used
+ /// as additional constraints when validating an X.509 certification path.
+ ///
+ /// The name constraints are specified as a byte array. This byte array
+ /// contains the DER encoded form of the name constraints, as they
+ /// would appear in the NameConstraints structure defined in RFC 2459
+ /// and X.509. The ASN.1 notation for this structure is supplied in the
+ /// documentation for the other constructors.
+ ///
+ /// Note that the name constraints byte array supplied here is cloned to
+ /// protect against subsequent modifications.
+ ///
+ ///
+ /// the name of the most-trusted CA as X509Name
+ /// the public key of the most-trusted CA
+ ///
+ /// a byte array containing the ASN.1 DER encoding of a NameConstraints extension to
+ /// be used for checking name constraints. Only the value of the extension is included,
+ /// not the OID or criticality flag. Specify null to omit the parameter.
+ ///
+ ///
+ /// if caPrincipal or pubKey is null
+ ///
+ public TrustAnchor(
+ X509Name caPrincipal,
+ AsymmetricKeyParameter pubKey,
+ byte[] nameConstraints)
+ {
+ if (caPrincipal == null)
+ throw new ArgumentNullException("caPrincipal");
+ if (pubKey == null)
+ throw new ArgumentNullException("pubKey");
+
+ this.trustedCert = null;
+ this.caPrincipal = caPrincipal;
+ this.caName = caPrincipal.ToString();
+ this.pubKey = pubKey;
+ setNameConstraints(nameConstraints);
+ }
+
+ ///
+ /// Creates an instance of TrustAnchor where the most-trusted
+ /// CA is specified as a distinguished name and public key. Name constraints
+ /// are an optional parameter, and are intended to be used as additional
+ /// constraints when validating an X.509 certification path.
+ ///
+ /// The name constraints are specified as a byte array. This byte array
+ /// contains the DER encoded form of the name constraints, as they would
+ /// appear in the NameConstraints structure defined in RFC 2459 and X.509.
+ ///
+ /// the X.500 distinguished name of the most-trusted CA in RFC
+ /// 2253 string format
+ /// the public key of the most-trusted CA
+ /// a byte array containing the ASN.1 DER encoding of a
+ /// NameConstraints extension to be used for checking name
+ /// constraints. Only the value of the extension is included, not
+ /// the OID or criticality flag. Specify null to omit the
+ /// parameter.
+ /// throws NullPointerException, IllegalArgumentException
+ public TrustAnchor(
+ string caName,
+ AsymmetricKeyParameter pubKey,
+ byte[] nameConstraints)
+ {
+ if (caName == null)
+ throw new ArgumentNullException("caName");
+ if (pubKey == null)
+ throw new ArgumentNullException("pubKey");
+ if (caName.Length == 0)
+ throw new ArgumentException("caName can not be an empty string");
+
+ this.caPrincipal = new X509Name(caName);
+ this.pubKey = pubKey;
+ this.caName = caName;
+ this.trustedCert = null;
+ setNameConstraints(nameConstraints);
+ }
+
+ ///
+ /// Returns the most-trusted CA certificate.
+ ///
+ public X509Certificate TrustedCert
+ {
+ get { return this.trustedCert; }
+ }
+
+ ///
+ /// Returns the name of the most-trusted CA as an X509Name.
+ ///
+ public X509Name CA
+ {
+ get { return this.caPrincipal; }
+ }
+
+ ///
+ /// Returns the name of the most-trusted CA in RFC 2253 string format.
+ ///
+ public string CAName
+ {
+ get { return this.caName; }
+ }
+
+ ///
+ /// Returns the public key of the most-trusted CA.
+ ///
+ public AsymmetricKeyParameter CAPublicKey
+ {
+ get { return this.pubKey; }
+ }
+
+ ///
+ /// Decode the name constraints and clone them if not null.
+ ///
+ private void setNameConstraints(
+ byte[] bytes)
+ {
+ if (bytes == null)
+ {
+ ncBytes = null;
+ nc = null;
+ }
+ else
+ {
+ ncBytes = (byte[]) bytes.Clone();
+ // validate DER encoding
+ //nc = new NameConstraintsExtension(Boolean.FALSE, bytes);
+ nc = NameConstraints.GetInstance(Asn1Object.FromByteArray(bytes));
+ }
+ }
+
+ public byte[] GetNameConstraints
+ {
+ get { return Arrays.Clone(ncBytes); }
+ }
+
+ ///
+ /// Returns a formatted string describing the TrustAnchor.
+ ///
+ /// a formatted string describing the TrustAnchor
+ public override string ToString()
+ {
+ // TODO Some of the sub-objects might not implement ToString() properly
+ string nl = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.NewLine;
+ StringBuilder sb = new StringBuilder();
+ sb.Append("[");
+ sb.Append(nl);
+ if (this.pubKey != null)
+ {
+ sb.Append(" Trusted CA Public Key: ").Append(this.pubKey).Append(nl);
+ sb.Append(" Trusted CA Issuer Name: ").Append(this.caName).Append(nl);
+ }
+ else
+ {
+ sb.Append(" Trusted CA cert: ").Append(this.TrustedCert).Append(nl);
+ }
+ if (nc != null)
+ {
+ sb.Append(" Name Constraints: ").Append(nc).Append(nl);
+ }
+ return sb.ToString();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/TrustAnchor.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/TrustAnchor.cs.meta
new file mode 100644
index 00000000..7d545c99
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/pkix/TrustAnchor.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 4d36de1eed444fb4faa2bdef5ce1d96c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security.meta
new file mode 100644
index 00000000..959f2742
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 2c421ef18ca1f844c8134a15061c4605
+folderAsset: yes
+DefaultImporter:
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/AgreementUtilities.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/AgreementUtilities.cs
new file mode 100644
index 00000000..792f34be
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/AgreementUtilities.cs
@@ -0,0 +1,128 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.EdEC;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement.Kdf;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security
+{
+ ///
+ /// Utility class for creating IBasicAgreement objects from their names/Oids
+ ///
+ public sealed class AgreementUtilities
+ {
+ private AgreementUtilities()
+ {
+ }
+
+ private static readonly IDictionary algorithms = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ //private static readonly IDictionary oids = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+
+ static AgreementUtilities()
+ {
+ algorithms[X9ObjectIdentifiers.DHSinglePassCofactorDHSha1KdfScheme.Id] = "ECCDHWITHSHA1KDF";
+ algorithms[X9ObjectIdentifiers.DHSinglePassStdDHSha1KdfScheme.Id] = "ECDHWITHSHA1KDF";
+ algorithms[X9ObjectIdentifiers.MqvSinglePassSha1KdfScheme.Id] = "ECMQVWITHSHA1KDF";
+
+ algorithms[EdECObjectIdentifiers.id_X25519.Id] = "X25519";
+ algorithms[EdECObjectIdentifiers.id_X448.Id] = "X448";
+ }
+
+ public static IBasicAgreement GetBasicAgreement(
+ DerObjectIdentifier oid)
+ {
+ return GetBasicAgreement(oid.Id);
+ }
+
+ public static IBasicAgreement GetBasicAgreement(
+ string algorithm)
+ {
+ string mechanism = GetMechanism(algorithm);
+
+ if (mechanism == "DH" || mechanism == "DIFFIEHELLMAN")
+ return new DHBasicAgreement();
+
+ if (mechanism == "ECDH")
+ return new ECDHBasicAgreement();
+
+ if (mechanism == "ECDHC" || mechanism == "ECCDH")
+ return new ECDHCBasicAgreement();
+
+ if (mechanism == "ECMQV")
+ return new ECMqvBasicAgreement();
+
+ throw new SecurityUtilityException("Basic Agreement " + algorithm + " not recognised.");
+ }
+
+ public static IBasicAgreement GetBasicAgreementWithKdf(
+ DerObjectIdentifier oid,
+ string wrapAlgorithm)
+ {
+ return GetBasicAgreementWithKdf(oid.Id, wrapAlgorithm);
+ }
+
+ public static IBasicAgreement GetBasicAgreementWithKdf(
+ string agreeAlgorithm,
+ string wrapAlgorithm)
+ {
+ string mechanism = GetMechanism(agreeAlgorithm);
+
+ // 'DHWITHSHA1KDF' retained for backward compatibility
+ if (mechanism == "DHWITHSHA1KDF" || mechanism == "ECDHWITHSHA1KDF")
+ return new ECDHWithKdfBasicAgreement(
+ wrapAlgorithm,
+ new ECDHKekGenerator(
+ new Sha1Digest()));
+
+ if (mechanism == "ECMQVWITHSHA1KDF")
+ return new ECMqvWithKdfBasicAgreement(
+ wrapAlgorithm,
+ new ECDHKekGenerator(
+ new Sha1Digest()));
+
+ throw new SecurityUtilityException("Basic Agreement (with KDF) " + agreeAlgorithm + " not recognised.");
+ }
+
+ public static IRawAgreement GetRawAgreement(
+ DerObjectIdentifier oid)
+ {
+ return GetRawAgreement(oid.Id);
+ }
+
+ public static IRawAgreement GetRawAgreement(
+ string algorithm)
+ {
+ string mechanism = GetMechanism(algorithm);
+
+ if (mechanism == "X25519")
+ return new X25519Agreement();
+
+ if (mechanism == "X448")
+ return new X448Agreement();
+
+ throw new SecurityUtilityException("Raw Agreement " + algorithm + " not recognised.");
+ }
+
+ public static string GetAlgorithmName(
+ DerObjectIdentifier oid)
+ {
+ return (string)algorithms[oid.Id];
+ }
+
+ private static string GetMechanism(string algorithm)
+ {
+ string upper = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm);
+ string mechanism = (string)algorithms[upper];
+ return mechanism == null ? upper : mechanism;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/AgreementUtilities.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/AgreementUtilities.cs.meta
new file mode 100644
index 00000000..ef3db30d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/AgreementUtilities.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0cbde65561e82da43be786150b90a32b
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/CipherUtilities.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/CipherUtilities.cs
new file mode 100644
index 00000000..f26fe829
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/CipherUtilities.cs
@@ -0,0 +1,764 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Kisa;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Ntt;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Oiw;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Encodings;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Paddings;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security
+{
+ ///
+ /// Cipher Utility class contains methods that can not be specifically grouped into other classes.
+ ///
+ public sealed class CipherUtilities
+ {
+ private enum CipherAlgorithm {
+ AES,
+ ARC4,
+ BLOWFISH,
+ CAMELLIA,
+ CAST5,
+ CAST6,
+ DES,
+ DESEDE,
+ ELGAMAL,
+ GOST28147,
+ HC128,
+ HC256,
+ IDEA,
+ NOEKEON,
+ PBEWITHSHAAND128BITRC4,
+ PBEWITHSHAAND40BITRC4,
+ RC2,
+ RC5,
+ RC5_64,
+ RC6,
+ RIJNDAEL,
+ RSA,
+ SALSA20,
+ SEED,
+ SERPENT,
+ SKIPJACK,
+ SM4,
+ TEA,
+ THREEFISH_256,
+ THREEFISH_512,
+ THREEFISH_1024,
+ TNEPRES,
+ TWOFISH,
+ VMPC,
+ VMPC_KSA3,
+ XTEA,
+ };
+
+ private enum CipherMode { ECB, NONE, CBC, CCM, CFB, CTR, CTS, EAX, GCM, GOFB, OCB, OFB, OPENPGPCFB, SIC };
+ private enum CipherPadding
+ {
+ NOPADDING,
+ RAW,
+ ISO10126PADDING,
+ ISO10126D2PADDING,
+ ISO10126_2PADDING,
+ ISO7816_4PADDING,
+ ISO9797_1PADDING,
+ ISO9796_1,
+ ISO9796_1PADDING,
+ OAEP,
+ OAEPPADDING,
+ OAEPWITHMD5ANDMGF1PADDING,
+ OAEPWITHSHA1ANDMGF1PADDING,
+ OAEPWITHSHA_1ANDMGF1PADDING,
+ OAEPWITHSHA224ANDMGF1PADDING,
+ OAEPWITHSHA_224ANDMGF1PADDING,
+ OAEPWITHSHA256ANDMGF1PADDING,
+ OAEPWITHSHA_256ANDMGF1PADDING,
+ OAEPWITHSHA384ANDMGF1PADDING,
+ OAEPWITHSHA_384ANDMGF1PADDING,
+ OAEPWITHSHA512ANDMGF1PADDING,
+ OAEPWITHSHA_512ANDMGF1PADDING,
+ PKCS1,
+ PKCS1PADDING,
+ PKCS5,
+ PKCS5PADDING,
+ PKCS7,
+ PKCS7PADDING,
+ TBCPADDING,
+ WITHCTS,
+ X923PADDING,
+ ZEROBYTEPADDING,
+ };
+
+ private static readonly IDictionary algorithms = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ private static readonly IDictionary oids = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+
+ static CipherUtilities()
+ {
+ // Signal to obfuscation tools not to change enum constants
+ ((CipherAlgorithm)Enums.GetArbitraryValue(typeof(CipherAlgorithm))).ToString();
+ ((CipherMode)Enums.GetArbitraryValue(typeof(CipherMode))).ToString();
+ ((CipherPadding)Enums.GetArbitraryValue(typeof(CipherPadding))).ToString();
+
+ // TODO Flesh out the list of aliases
+
+ algorithms[NistObjectIdentifiers.IdAes128Ecb.Id] = "AES/ECB/PKCS7PADDING";
+ algorithms[NistObjectIdentifiers.IdAes192Ecb.Id] = "AES/ECB/PKCS7PADDING";
+ algorithms[NistObjectIdentifiers.IdAes256Ecb.Id] = "AES/ECB/PKCS7PADDING";
+ algorithms["AES//PKCS7"] = "AES/ECB/PKCS7PADDING";
+ algorithms["AES//PKCS7PADDING"] = "AES/ECB/PKCS7PADDING";
+ algorithms["AES//PKCS5"] = "AES/ECB/PKCS7PADDING";
+ algorithms["AES//PKCS5PADDING"] = "AES/ECB/PKCS7PADDING";
+
+ algorithms[NistObjectIdentifiers.IdAes128Cbc.Id] = "AES/CBC/PKCS7PADDING";
+ algorithms[NistObjectIdentifiers.IdAes192Cbc.Id] = "AES/CBC/PKCS7PADDING";
+ algorithms[NistObjectIdentifiers.IdAes256Cbc.Id] = "AES/CBC/PKCS7PADDING";
+
+ algorithms[NistObjectIdentifiers.IdAes128Ofb.Id] = "AES/OFB/NOPADDING";
+ algorithms[NistObjectIdentifiers.IdAes192Ofb.Id] = "AES/OFB/NOPADDING";
+ algorithms[NistObjectIdentifiers.IdAes256Ofb.Id] = "AES/OFB/NOPADDING";
+
+ algorithms[NistObjectIdentifiers.IdAes128Cfb.Id] = "AES/CFB/NOPADDING";
+ algorithms[NistObjectIdentifiers.IdAes192Cfb.Id] = "AES/CFB/NOPADDING";
+ algorithms[NistObjectIdentifiers.IdAes256Cfb.Id] = "AES/CFB/NOPADDING";
+
+ algorithms["RSA/ECB/PKCS1"] = "RSA//PKCS1PADDING";
+ algorithms["RSA/ECB/PKCS1PADDING"] = "RSA//PKCS1PADDING";
+ algorithms[PkcsObjectIdentifiers.RsaEncryption.Id] = "RSA//PKCS1PADDING";
+ algorithms[PkcsObjectIdentifiers.IdRsaesOaep.Id] = "RSA//OAEPPADDING";
+
+ algorithms[OiwObjectIdentifiers.DesCbc.Id] = "DES/CBC";
+ algorithms[OiwObjectIdentifiers.DesCfb.Id] = "DES/CFB";
+ algorithms[OiwObjectIdentifiers.DesEcb.Id] = "DES/ECB";
+ algorithms[OiwObjectIdentifiers.DesOfb.Id] = "DES/OFB";
+ algorithms[OiwObjectIdentifiers.DesEde.Id] = "DESEDE";
+ algorithms["TDEA"] = "DESEDE";
+ algorithms[PkcsObjectIdentifiers.DesEde3Cbc.Id] = "DESEDE/CBC";
+ algorithms[PkcsObjectIdentifiers.RC2Cbc.Id] = "RC2/CBC";
+ algorithms["1.3.6.1.4.1.188.7.1.1.2"] = "IDEA/CBC";
+ algorithms["1.2.840.113533.7.66.10"] = "CAST5/CBC";
+
+ algorithms["RC4"] = "ARC4";
+ algorithms["ARCFOUR"] = "ARC4";
+ algorithms["1.2.840.113549.3.4"] = "ARC4";
+
+
+
+ algorithms["PBEWITHSHA1AND128BITRC4"] = "PBEWITHSHAAND128BITRC4";
+ algorithms[PkcsObjectIdentifiers.PbeWithShaAnd128BitRC4.Id] = "PBEWITHSHAAND128BITRC4";
+ algorithms["PBEWITHSHA1AND40BITRC4"] = "PBEWITHSHAAND40BITRC4";
+ algorithms[PkcsObjectIdentifiers.PbeWithShaAnd40BitRC4.Id] = "PBEWITHSHAAND40BITRC4";
+
+ algorithms["PBEWITHSHA1ANDDES"] = "PBEWITHSHA1ANDDES-CBC";
+ algorithms[PkcsObjectIdentifiers.PbeWithSha1AndDesCbc.Id] = "PBEWITHSHA1ANDDES-CBC";
+ algorithms["PBEWITHSHA1ANDRC2"] = "PBEWITHSHA1ANDRC2-CBC";
+ algorithms[PkcsObjectIdentifiers.PbeWithSha1AndRC2Cbc.Id] = "PBEWITHSHA1ANDRC2-CBC";
+
+ algorithms["PBEWITHSHA1AND3-KEYTRIPLEDES-CBC"] = "PBEWITHSHAAND3-KEYTRIPLEDES-CBC";
+ algorithms["PBEWITHSHAAND3KEYTRIPLEDES"] = "PBEWITHSHAAND3-KEYTRIPLEDES-CBC";
+ algorithms[PkcsObjectIdentifiers.PbeWithShaAnd3KeyTripleDesCbc.Id] = "PBEWITHSHAAND3-KEYTRIPLEDES-CBC";
+ algorithms["PBEWITHSHA1ANDDESEDE"] = "PBEWITHSHAAND3-KEYTRIPLEDES-CBC";
+
+ algorithms["PBEWITHSHA1AND2-KEYTRIPLEDES-CBC"] = "PBEWITHSHAAND2-KEYTRIPLEDES-CBC";
+ algorithms[PkcsObjectIdentifiers.PbeWithShaAnd2KeyTripleDesCbc.Id] = "PBEWITHSHAAND2-KEYTRIPLEDES-CBC";
+
+ algorithms["PBEWITHSHA1AND128BITRC2-CBC"] = "PBEWITHSHAAND128BITRC2-CBC";
+ algorithms[PkcsObjectIdentifiers.PbeWithShaAnd128BitRC2Cbc.Id] = "PBEWITHSHAAND128BITRC2-CBC";
+
+ algorithms["PBEWITHSHA1AND40BITRC2-CBC"] = "PBEWITHSHAAND40BITRC2-CBC";
+ algorithms[PkcsObjectIdentifiers.PbewithShaAnd40BitRC2Cbc.Id] = "PBEWITHSHAAND40BITRC2-CBC";
+
+ algorithms["PBEWITHSHA1AND128BITAES-CBC-BC"] = "PBEWITHSHAAND128BITAES-CBC-BC";
+ algorithms["PBEWITHSHA-1AND128BITAES-CBC-BC"] = "PBEWITHSHAAND128BITAES-CBC-BC";
+
+ algorithms["PBEWITHSHA1AND192BITAES-CBC-BC"] = "PBEWITHSHAAND192BITAES-CBC-BC";
+ algorithms["PBEWITHSHA-1AND192BITAES-CBC-BC"] = "PBEWITHSHAAND192BITAES-CBC-BC";
+
+ algorithms["PBEWITHSHA1AND256BITAES-CBC-BC"] = "PBEWITHSHAAND256BITAES-CBC-BC";
+ algorithms["PBEWITHSHA-1AND256BITAES-CBC-BC"] = "PBEWITHSHAAND256BITAES-CBC-BC";
+
+ algorithms["PBEWITHSHA-256AND128BITAES-CBC-BC"] = "PBEWITHSHA256AND128BITAES-CBC-BC";
+ algorithms["PBEWITHSHA-256AND192BITAES-CBC-BC"] = "PBEWITHSHA256AND192BITAES-CBC-BC";
+ algorithms["PBEWITHSHA-256AND256BITAES-CBC-BC"] = "PBEWITHSHA256AND256BITAES-CBC-BC";
+
+
+ algorithms["GOST"] = "GOST28147";
+ algorithms["GOST-28147"] = "GOST28147";
+ algorithms[CryptoProObjectIdentifiers.GostR28147Cbc.Id] = "GOST28147/CBC/PKCS7PADDING";
+
+ algorithms["RC5-32"] = "RC5";
+
+ algorithms[NttObjectIdentifiers.IdCamellia128Cbc.Id] = "CAMELLIA/CBC/PKCS7PADDING";
+ algorithms[NttObjectIdentifiers.IdCamellia192Cbc.Id] = "CAMELLIA/CBC/PKCS7PADDING";
+ algorithms[NttObjectIdentifiers.IdCamellia256Cbc.Id] = "CAMELLIA/CBC/PKCS7PADDING";
+
+ algorithms[KisaObjectIdentifiers.IdSeedCbc.Id] = "SEED/CBC/PKCS7PADDING";
+
+ algorithms["1.3.6.1.4.1.3029.1.2"] = "BLOWFISH/CBC";
+ }
+
+ private CipherUtilities()
+ {
+ }
+
+ ///
+ /// Returns a ObjectIdentifier for a give encoding.
+ ///
+ /// A string representation of the encoding.
+ /// A DerObjectIdentifier, null if the Oid is not available.
+ // TODO Don't really want to support this
+ public static DerObjectIdentifier GetObjectIdentifier(
+ string mechanism)
+ {
+ if (mechanism == null)
+ throw new ArgumentNullException("mechanism");
+
+ mechanism = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(mechanism);
+ string aliased = (string) algorithms[mechanism];
+
+ if (aliased != null)
+ mechanism = aliased;
+
+ return (DerObjectIdentifier) oids[mechanism];
+ }
+
+ public static ICollection Algorithms
+ {
+ get { return oids.Keys; }
+ }
+
+ public static IBufferedCipher GetCipher(
+ DerObjectIdentifier oid)
+ {
+ return GetCipher(oid.Id);
+ }
+
+ public static IBufferedCipher GetCipher(
+ string algorithm)
+ {
+ if (algorithm == null)
+ throw new ArgumentNullException("algorithm");
+
+ algorithm = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm);
+
+ {
+ string aliased = (string) algorithms[algorithm];
+
+ if (aliased != null)
+ algorithm = aliased;
+ }
+
+ IBasicAgreement iesAgreement = null;
+ if (algorithm == "IES")
+ {
+ iesAgreement = new DHBasicAgreement();
+ }
+ else if (algorithm == "ECIES")
+ {
+ iesAgreement = new ECDHBasicAgreement();
+ }
+
+ if (iesAgreement != null)
+ {
+ return new BufferedIesCipher(
+ new IesEngine(
+ iesAgreement,
+ new Kdf2BytesGenerator(
+ new Sha1Digest()),
+ new HMac(
+ new Sha1Digest())));
+ }
+
+
+
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(algorithm, "PBE"))
+ {
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(algorithm, "-CBC"))
+ {
+ if (algorithm == "PBEWITHSHA1ANDDES-CBC")
+ {
+ return new PaddedBufferedBlockCipher(
+ new CbcBlockCipher(new DesEngine()));
+ }
+ else if (algorithm == "PBEWITHSHA1ANDRC2-CBC")
+ {
+ return new PaddedBufferedBlockCipher(
+ new CbcBlockCipher(new RC2Engine()));
+ }
+ else if (Strings.IsOneOf(algorithm,
+ "PBEWITHSHAAND2-KEYTRIPLEDES-CBC", "PBEWITHSHAAND3-KEYTRIPLEDES-CBC"))
+ {
+ return new PaddedBufferedBlockCipher(
+ new CbcBlockCipher(new DesEdeEngine()));
+ }
+ else if (Strings.IsOneOf(algorithm,
+ "PBEWITHSHAAND128BITRC2-CBC", "PBEWITHSHAAND40BITRC2-CBC"))
+ {
+ return new PaddedBufferedBlockCipher(
+ new CbcBlockCipher(new RC2Engine()));
+ }
+ }
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(algorithm, "-BC") || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(algorithm, "-OPENSSL"))
+ {
+ if (Strings.IsOneOf(algorithm,
+ "PBEWITHSHAAND128BITAES-CBC-BC",
+ "PBEWITHSHAAND192BITAES-CBC-BC",
+ "PBEWITHSHAAND256BITAES-CBC-BC",
+ "PBEWITHSHA256AND128BITAES-CBC-BC",
+ "PBEWITHSHA256AND192BITAES-CBC-BC",
+ "PBEWITHSHA256AND256BITAES-CBC-BC",
+ "PBEWITHMD5AND128BITAES-CBC-OPENSSL",
+ "PBEWITHMD5AND192BITAES-CBC-OPENSSL",
+ "PBEWITHMD5AND256BITAES-CBC-OPENSSL"))
+ {
+ return new PaddedBufferedBlockCipher(
+ new CbcBlockCipher(new AesEngine()));
+ }
+ }
+ }
+
+
+
+ string[] parts = algorithm.Split('/');
+
+ IBlockCipher blockCipher = null;
+ IAsymmetricBlockCipher asymBlockCipher = null;
+ IStreamCipher streamCipher = null;
+
+ string algorithmName = parts[0];
+
+ {
+ string aliased = (string)algorithms[algorithmName];
+
+ if (aliased != null)
+ algorithmName = aliased;
+ }
+
+ CipherAlgorithm cipherAlgorithm;
+ try
+ {
+ cipherAlgorithm = (CipherAlgorithm)Enums.GetEnumValue(typeof(CipherAlgorithm), algorithmName);
+ }
+ catch (ArgumentException)
+ {
+ throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
+ }
+
+ switch (cipherAlgorithm)
+ {
+ case CipherAlgorithm.AES:
+ blockCipher = new AesEngine();
+ break;
+ case CipherAlgorithm.ARC4:
+ streamCipher = new RC4Engine();
+ break;
+ case CipherAlgorithm.BLOWFISH:
+ blockCipher = new BlowfishEngine();
+ break;
+ case CipherAlgorithm.CAMELLIA:
+ blockCipher = new CamelliaEngine();
+ break;
+ case CipherAlgorithm.CAST5:
+ blockCipher = new Cast5Engine();
+ break;
+ case CipherAlgorithm.CAST6:
+ blockCipher = new Cast6Engine();
+ break;
+ case CipherAlgorithm.DES:
+ blockCipher = new DesEngine();
+ break;
+ case CipherAlgorithm.DESEDE:
+ blockCipher = new DesEdeEngine();
+ break;
+ case CipherAlgorithm.ELGAMAL:
+ asymBlockCipher = new ElGamalEngine();
+ break;
+ case CipherAlgorithm.GOST28147:
+ blockCipher = new Gost28147Engine();
+ break;
+ case CipherAlgorithm.HC128:
+ streamCipher = new HC128Engine();
+ break;
+ case CipherAlgorithm.HC256:
+ streamCipher = new HC256Engine();
+ break;
+ case CipherAlgorithm.IDEA:
+ blockCipher = new IdeaEngine();
+ break;
+ case CipherAlgorithm.NOEKEON:
+ blockCipher = new NoekeonEngine();
+ break;
+ case CipherAlgorithm.PBEWITHSHAAND128BITRC4:
+ case CipherAlgorithm.PBEWITHSHAAND40BITRC4:
+ streamCipher = new RC4Engine();
+ break;
+ case CipherAlgorithm.RC2:
+ blockCipher = new RC2Engine();
+ break;
+ case CipherAlgorithm.RC5:
+ blockCipher = new RC532Engine();
+ break;
+ case CipherAlgorithm.RC5_64:
+ blockCipher = new RC564Engine();
+ break;
+ case CipherAlgorithm.RC6:
+ blockCipher = new RC6Engine();
+ break;
+ case CipherAlgorithm.RIJNDAEL:
+ blockCipher = new RijndaelEngine();
+ break;
+ case CipherAlgorithm.RSA:
+ asymBlockCipher = new RsaBlindedEngine();
+ break;
+ case CipherAlgorithm.SALSA20:
+ streamCipher = new Salsa20Engine();
+ break;
+ case CipherAlgorithm.SEED:
+ blockCipher = new SeedEngine();
+ break;
+ case CipherAlgorithm.SERPENT:
+ blockCipher = new SerpentEngine();
+ break;
+ case CipherAlgorithm.SKIPJACK:
+ blockCipher = new SkipjackEngine();
+ break;
+ case CipherAlgorithm.SM4:
+ blockCipher = new SM4Engine();
+ break;
+ case CipherAlgorithm.TEA:
+ blockCipher = new TeaEngine();
+ break;
+ case CipherAlgorithm.THREEFISH_256:
+ blockCipher = new ThreefishEngine(ThreefishEngine.BLOCKSIZE_256);
+ break;
+ case CipherAlgorithm.THREEFISH_512:
+ blockCipher = new ThreefishEngine(ThreefishEngine.BLOCKSIZE_512);
+ break;
+ case CipherAlgorithm.THREEFISH_1024:
+ blockCipher = new ThreefishEngine(ThreefishEngine.BLOCKSIZE_1024);
+ break;
+ case CipherAlgorithm.TNEPRES:
+ blockCipher = new TnepresEngine();
+ break;
+ case CipherAlgorithm.TWOFISH:
+ blockCipher = new TwofishEngine();
+ break;
+ case CipherAlgorithm.VMPC:
+ streamCipher = new VmpcEngine();
+ break;
+ case CipherAlgorithm.VMPC_KSA3:
+ streamCipher = new VmpcKsa3Engine();
+ break;
+ case CipherAlgorithm.XTEA:
+ blockCipher = new XteaEngine();
+ break;
+ default:
+ throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
+ }
+
+ if (streamCipher != null)
+ {
+ if (parts.Length > 1)
+ throw new ArgumentException("Modes and paddings not used for stream ciphers");
+
+ return new BufferedStreamCipher(streamCipher);
+ }
+
+
+ bool cts = false;
+ bool padded = true;
+ IBlockCipherPadding padding = null;
+ IAeadBlockCipher aeadBlockCipher = null;
+
+ if (parts.Length > 2)
+ {
+ if (streamCipher != null)
+ throw new ArgumentException("Paddings not used for stream ciphers");
+
+ string paddingName = parts[2];
+
+ CipherPadding cipherPadding;
+ if (paddingName == "")
+ {
+ cipherPadding = CipherPadding.RAW;
+ }
+ else if (paddingName == "X9.23PADDING")
+ {
+ cipherPadding = CipherPadding.X923PADDING;
+ }
+ else
+ {
+ try
+ {
+ cipherPadding = (CipherPadding)Enums.GetEnumValue(typeof(CipherPadding), paddingName);
+ }
+ catch (ArgumentException)
+ {
+ throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
+ }
+ }
+
+ switch (cipherPadding)
+ {
+ case CipherPadding.NOPADDING:
+ padded = false;
+ break;
+ case CipherPadding.RAW:
+ break;
+ case CipherPadding.ISO10126PADDING:
+ case CipherPadding.ISO10126D2PADDING:
+ case CipherPadding.ISO10126_2PADDING:
+ padding = new ISO10126d2Padding();
+ break;
+ case CipherPadding.ISO7816_4PADDING:
+ case CipherPadding.ISO9797_1PADDING:
+ padding = new ISO7816d4Padding();
+ break;
+ case CipherPadding.ISO9796_1:
+ case CipherPadding.ISO9796_1PADDING:
+ asymBlockCipher = new ISO9796d1Encoding(asymBlockCipher);
+ break;
+ case CipherPadding.OAEP:
+ case CipherPadding.OAEPPADDING:
+ asymBlockCipher = new OaepEncoding(asymBlockCipher);
+ break;
+ case CipherPadding.OAEPWITHMD5ANDMGF1PADDING:
+ asymBlockCipher = new OaepEncoding(asymBlockCipher, new MD5Digest());
+ break;
+ case CipherPadding.OAEPWITHSHA1ANDMGF1PADDING:
+ case CipherPadding.OAEPWITHSHA_1ANDMGF1PADDING:
+ asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha1Digest());
+ break;
+ case CipherPadding.OAEPWITHSHA224ANDMGF1PADDING:
+ case CipherPadding.OAEPWITHSHA_224ANDMGF1PADDING:
+ asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha224Digest());
+ break;
+ case CipherPadding.OAEPWITHSHA256ANDMGF1PADDING:
+ case CipherPadding.OAEPWITHSHA_256ANDMGF1PADDING:
+ asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha256Digest());
+ break;
+ case CipherPadding.OAEPWITHSHA384ANDMGF1PADDING:
+ case CipherPadding.OAEPWITHSHA_384ANDMGF1PADDING:
+ asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha384Digest());
+ break;
+ case CipherPadding.OAEPWITHSHA512ANDMGF1PADDING:
+ case CipherPadding.OAEPWITHSHA_512ANDMGF1PADDING:
+ asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha512Digest());
+ break;
+ case CipherPadding.PKCS1:
+ case CipherPadding.PKCS1PADDING:
+ asymBlockCipher = new Pkcs1Encoding(asymBlockCipher);
+ break;
+ case CipherPadding.PKCS5:
+ case CipherPadding.PKCS5PADDING:
+ case CipherPadding.PKCS7:
+ case CipherPadding.PKCS7PADDING:
+ padding = new Pkcs7Padding();
+ break;
+ case CipherPadding.TBCPADDING:
+ padding = new TbcPadding();
+ break;
+ case CipherPadding.WITHCTS:
+ cts = true;
+ break;
+ case CipherPadding.X923PADDING:
+ padding = new X923Padding();
+ break;
+ case CipherPadding.ZEROBYTEPADDING:
+ padding = new ZeroBytePadding();
+ break;
+ default:
+ throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
+ }
+ }
+
+ string mode = "";
+ if (parts.Length > 1)
+ {
+ mode = parts[1];
+
+ int di = GetDigitIndex(mode);
+ string modeName = di >= 0 ? mode.Substring(0, di) : mode;
+
+ try
+ {
+ CipherMode cipherMode = modeName == ""
+ ? CipherMode.NONE
+ : (CipherMode)Enums.GetEnumValue(typeof(CipherMode), modeName);
+
+ switch (cipherMode)
+ {
+ case CipherMode.ECB:
+ case CipherMode.NONE:
+ break;
+ case CipherMode.CBC:
+ blockCipher = new CbcBlockCipher(blockCipher);
+ break;
+ case CipherMode.CCM:
+ aeadBlockCipher = new CcmBlockCipher(blockCipher);
+ break;
+ case CipherMode.CFB:
+ {
+ int bits = (di < 0)
+ ? 8 * blockCipher.GetBlockSize()
+ : int.Parse(mode.Substring(di));
+
+ blockCipher = new CfbBlockCipher(blockCipher, bits);
+ break;
+ }
+ case CipherMode.CTR:
+ blockCipher = new SicBlockCipher(blockCipher);
+ break;
+ case CipherMode.CTS:
+ cts = true;
+ blockCipher = new CbcBlockCipher(blockCipher);
+ break;
+ case CipherMode.EAX:
+ aeadBlockCipher = new EaxBlockCipher(blockCipher);
+ break;
+ case CipherMode.GCM:
+ aeadBlockCipher = new GcmBlockCipher(blockCipher);
+ break;
+ case CipherMode.GOFB:
+ blockCipher = new GOfbBlockCipher(blockCipher);
+ break;
+ case CipherMode.OCB:
+ aeadBlockCipher = new OcbBlockCipher(blockCipher, CreateBlockCipher(cipherAlgorithm));
+ break;
+ case CipherMode.OFB:
+ {
+ int bits = (di < 0)
+ ? 8 * blockCipher.GetBlockSize()
+ : int.Parse(mode.Substring(di));
+
+ blockCipher = new OfbBlockCipher(blockCipher, bits);
+ break;
+ }
+ case CipherMode.OPENPGPCFB:
+ blockCipher = new OpenPgpCfbBlockCipher(blockCipher);
+ break;
+ case CipherMode.SIC:
+ if (blockCipher.GetBlockSize() < 16)
+ {
+ throw new ArgumentException("Warning: SIC-Mode can become a twotime-pad if the blocksize of the cipher is too small. Use a cipher with a block size of at least 128 bits (e.g. AES)");
+ }
+ blockCipher = new SicBlockCipher(blockCipher);
+ break;
+ default:
+ throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
+ }
+ }
+ catch (ArgumentException)
+ {
+ throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
+ }
+ }
+
+ if (aeadBlockCipher != null)
+ {
+ if (cts)
+ throw new SecurityUtilityException("CTS mode not valid for AEAD ciphers.");
+ if (padded && parts.Length > 2 && parts[2] != "")
+ throw new SecurityUtilityException("Bad padding specified for AEAD cipher.");
+
+ return new BufferedAeadBlockCipher(aeadBlockCipher);
+ }
+
+ if (blockCipher != null)
+ {
+ if (cts)
+ {
+ return new CtsBlockCipher(blockCipher);
+ }
+
+ if (padding != null)
+ {
+ return new PaddedBufferedBlockCipher(blockCipher, padding);
+ }
+
+ if (!padded || blockCipher.IsPartialBlockOkay)
+ {
+ return new BufferedBlockCipher(blockCipher);
+ }
+
+ return new PaddedBufferedBlockCipher(blockCipher);
+ }
+
+ if (asymBlockCipher != null)
+ {
+ return new BufferedAsymmetricBlockCipher(asymBlockCipher);
+ }
+
+ throw new SecurityUtilityException("Cipher " + algorithm + " not recognised.");
+ }
+
+ public static string GetAlgorithmName(
+ DerObjectIdentifier oid)
+ {
+ return (string) algorithms[oid.Id];
+ }
+
+ private static int GetDigitIndex(
+ string s)
+ {
+ for (int i = 0; i < s.Length; ++i)
+ {
+ if (char.IsDigit(s[i]))
+ return i;
+ }
+
+ return -1;
+ }
+
+ private static IBlockCipher CreateBlockCipher(CipherAlgorithm cipherAlgorithm)
+ {
+ switch (cipherAlgorithm)
+ {
+ case CipherAlgorithm.AES: return new AesEngine();
+ case CipherAlgorithm.BLOWFISH: return new BlowfishEngine();
+ case CipherAlgorithm.CAMELLIA: return new CamelliaEngine();
+ case CipherAlgorithm.CAST5: return new Cast5Engine();
+ case CipherAlgorithm.CAST6: return new Cast6Engine();
+ case CipherAlgorithm.DES: return new DesEngine();
+ case CipherAlgorithm.DESEDE: return new DesEdeEngine();
+ case CipherAlgorithm.GOST28147: return new Gost28147Engine();
+ case CipherAlgorithm.IDEA: return new IdeaEngine();
+ case CipherAlgorithm.NOEKEON: return new NoekeonEngine();
+ case CipherAlgorithm.RC2: return new RC2Engine();
+ case CipherAlgorithm.RC5: return new RC532Engine();
+ case CipherAlgorithm.RC5_64: return new RC564Engine();
+ case CipherAlgorithm.RC6: return new RC6Engine();
+ case CipherAlgorithm.RIJNDAEL: return new RijndaelEngine();
+ case CipherAlgorithm.SEED: return new SeedEngine();
+ case CipherAlgorithm.SERPENT: return new SerpentEngine();
+ case CipherAlgorithm.SKIPJACK: return new SkipjackEngine();
+ case CipherAlgorithm.SM4: return new SM4Engine();
+ case CipherAlgorithm.TEA: return new TeaEngine();
+ case CipherAlgorithm.THREEFISH_256: return new ThreefishEngine(ThreefishEngine.BLOCKSIZE_256);
+ case CipherAlgorithm.THREEFISH_512: return new ThreefishEngine(ThreefishEngine.BLOCKSIZE_512);
+ case CipherAlgorithm.THREEFISH_1024: return new ThreefishEngine(ThreefishEngine.BLOCKSIZE_1024);
+ case CipherAlgorithm.TNEPRES: return new TnepresEngine();
+ case CipherAlgorithm.TWOFISH: return new TwofishEngine();
+ case CipherAlgorithm.XTEA: return new XteaEngine();
+ default:
+ throw new SecurityUtilityException("Cipher " + cipherAlgorithm + " not recognised or not a block cipher");
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/CipherUtilities.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/CipherUtilities.cs.meta
new file mode 100644
index 00000000..8c41f894
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/CipherUtilities.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 3576aacdad56d6a45a71b7f377ae1fcc
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/DigestUtilities.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/DigestUtilities.cs
new file mode 100644
index 00000000..17496326
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/DigestUtilities.cs
@@ -0,0 +1,289 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.GM;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Misc;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Oiw;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Rosstandart;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.TeleTrust;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.UA;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security
+{
+ ///
+ /// Utility class for creating IDigest objects from their names/Oids
+ ///
+ public sealed class DigestUtilities
+ {
+ private enum DigestAlgorithm {
+ BLAKE2B_160, BLAKE2B_256, BLAKE2B_384, BLAKE2B_512,
+ BLAKE2S_128, BLAKE2S_160, BLAKE2S_224, BLAKE2S_256,
+ DSTU7564_256, DSTU7564_384, DSTU7564_512,
+ GOST3411,
+ GOST3411_2012_256, GOST3411_2012_512,
+ KECCAK_224, KECCAK_256, KECCAK_288, KECCAK_384, KECCAK_512,
+ MD2, MD4, MD5,
+ NONE,
+ RIPEMD128, RIPEMD160, RIPEMD256, RIPEMD320,
+ SHA_1, SHA_224, SHA_256, SHA_384, SHA_512,
+ SHA_512_224, SHA_512_256,
+ SHA3_224, SHA3_256, SHA3_384, SHA3_512,
+ SHAKE128, SHAKE256,
+ SM3,
+ TIGER,
+ WHIRLPOOL,
+ };
+
+ private DigestUtilities()
+ {
+ }
+
+ private static readonly IDictionary algorithms = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ private static readonly IDictionary oids = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+
+ static DigestUtilities()
+ {
+ // Signal to obfuscation tools not to change enum constants
+ ((DigestAlgorithm)Enums.GetArbitraryValue(typeof(DigestAlgorithm))).ToString();
+
+ algorithms[PkcsObjectIdentifiers.MD2.Id] = "MD2";
+ algorithms[PkcsObjectIdentifiers.MD4.Id] = "MD4";
+ algorithms[PkcsObjectIdentifiers.MD5.Id] = "MD5";
+
+ algorithms["SHA1"] = "SHA-1";
+ algorithms[OiwObjectIdentifiers.IdSha1.Id] = "SHA-1";
+ algorithms["SHA224"] = "SHA-224";
+ algorithms[NistObjectIdentifiers.IdSha224.Id] = "SHA-224";
+ algorithms["SHA256"] = "SHA-256";
+ algorithms[NistObjectIdentifiers.IdSha256.Id] = "SHA-256";
+ algorithms["SHA384"] = "SHA-384";
+ algorithms[NistObjectIdentifiers.IdSha384.Id] = "SHA-384";
+ algorithms["SHA512"] = "SHA-512";
+ algorithms[NistObjectIdentifiers.IdSha512.Id] = "SHA-512";
+ algorithms["SHA512/224"] = "SHA-512/224";
+ algorithms[NistObjectIdentifiers.IdSha512_224.Id] = "SHA-512/224";
+ algorithms["SHA512/256"] = "SHA-512/256";
+ algorithms[NistObjectIdentifiers.IdSha512_256.Id] = "SHA-512/256";
+
+ algorithms["RIPEMD-128"] = "RIPEMD128";
+ algorithms[TeleTrusTObjectIdentifiers.RipeMD128.Id] = "RIPEMD128";
+ algorithms["RIPEMD-160"] = "RIPEMD160";
+ algorithms[TeleTrusTObjectIdentifiers.RipeMD160.Id] = "RIPEMD160";
+ algorithms["RIPEMD-256"] = "RIPEMD256";
+ algorithms[TeleTrusTObjectIdentifiers.RipeMD256.Id] = "RIPEMD256";
+ algorithms["RIPEMD-320"] = "RIPEMD320";
+// algorithms[TeleTrusTObjectIdentifiers.RipeMD320.Id] = "RIPEMD320";
+
+ algorithms[CryptoProObjectIdentifiers.GostR3411.Id] = "GOST3411";
+
+ algorithms["KECCAK224"] = "KECCAK-224";
+ algorithms["KECCAK256"] = "KECCAK-256";
+ algorithms["KECCAK288"] = "KECCAK-288";
+ algorithms["KECCAK384"] = "KECCAK-384";
+ algorithms["KECCAK512"] = "KECCAK-512";
+
+ algorithms[NistObjectIdentifiers.IdSha3_224.Id] = "SHA3-224";
+ algorithms[NistObjectIdentifiers.IdSha3_256.Id] = "SHA3-256";
+ algorithms[NistObjectIdentifiers.IdSha3_384.Id] = "SHA3-384";
+ algorithms[NistObjectIdentifiers.IdSha3_512.Id] = "SHA3-512";
+ algorithms[NistObjectIdentifiers.IdShake128.Id] = "SHAKE128";
+ algorithms[NistObjectIdentifiers.IdShake256.Id] = "SHAKE256";
+
+ algorithms[GMObjectIdentifiers.sm3.Id] = "SM3";
+
+ algorithms[MiscObjectIdentifiers.id_blake2b160.Id] = "BLAKE2B-160";
+ algorithms[MiscObjectIdentifiers.id_blake2b256.Id] = "BLAKE2B-256";
+ algorithms[MiscObjectIdentifiers.id_blake2b384.Id] = "BLAKE2B-384";
+ algorithms[MiscObjectIdentifiers.id_blake2b512.Id] = "BLAKE2B-512";
+ algorithms[MiscObjectIdentifiers.id_blake2s128.Id] = "BLAKE2S-128";
+ algorithms[MiscObjectIdentifiers.id_blake2s160.Id] = "BLAKE2S-160";
+ algorithms[MiscObjectIdentifiers.id_blake2s224.Id] = "BLAKE2S-224";
+ algorithms[MiscObjectIdentifiers.id_blake2s256.Id] = "BLAKE2S-256";
+
+ algorithms[RosstandartObjectIdentifiers.id_tc26_gost_3411_12_256.Id] = "GOST3411-2012-256";
+ algorithms[RosstandartObjectIdentifiers.id_tc26_gost_3411_12_512.Id] = "GOST3411-2012-512";
+
+ algorithms[UAObjectIdentifiers.dstu7564digest_256.Id] = "DSTU7564-256";
+ algorithms[UAObjectIdentifiers.dstu7564digest_384.Id] = "DSTU7564-384";
+ algorithms[UAObjectIdentifiers.dstu7564digest_512.Id] = "DSTU7564-512";
+
+ oids["MD2"] = PkcsObjectIdentifiers.MD2;
+ oids["MD4"] = PkcsObjectIdentifiers.MD4;
+ oids["MD5"] = PkcsObjectIdentifiers.MD5;
+ oids["SHA-1"] = OiwObjectIdentifiers.IdSha1;
+ oids["SHA-224"] = NistObjectIdentifiers.IdSha224;
+ oids["SHA-256"] = NistObjectIdentifiers.IdSha256;
+ oids["SHA-384"] = NistObjectIdentifiers.IdSha384;
+ oids["SHA-512"] = NistObjectIdentifiers.IdSha512;
+ oids["SHA-512/224"] = NistObjectIdentifiers.IdSha512_224;
+ oids["SHA-512/256"] = NistObjectIdentifiers.IdSha512_256;
+ oids["SHA3-224"] = NistObjectIdentifiers.IdSha3_224;
+ oids["SHA3-256"] = NistObjectIdentifiers.IdSha3_256;
+ oids["SHA3-384"] = NistObjectIdentifiers.IdSha3_384;
+ oids["SHA3-512"] = NistObjectIdentifiers.IdSha3_512;
+ oids["SHAKE128"] = NistObjectIdentifiers.IdShake128;
+ oids["SHAKE256"] = NistObjectIdentifiers.IdShake256;
+ oids["RIPEMD128"] = TeleTrusTObjectIdentifiers.RipeMD128;
+ oids["RIPEMD160"] = TeleTrusTObjectIdentifiers.RipeMD160;
+ oids["RIPEMD256"] = TeleTrusTObjectIdentifiers.RipeMD256;
+ oids["GOST3411"] = CryptoProObjectIdentifiers.GostR3411;
+ oids["SM3"] = GMObjectIdentifiers.sm3;
+ oids["BLAKE2B-160"] = MiscObjectIdentifiers.id_blake2b160;
+ oids["BLAKE2B-256"] = MiscObjectIdentifiers.id_blake2b256;
+ oids["BLAKE2B-384"] = MiscObjectIdentifiers.id_blake2b384;
+ oids["BLAKE2B-512"] = MiscObjectIdentifiers.id_blake2b512;
+ oids["BLAKE2S-128"] = MiscObjectIdentifiers.id_blake2s128;
+ oids["BLAKE2S-160"] = MiscObjectIdentifiers.id_blake2s160;
+ oids["BLAKE2S-224"] = MiscObjectIdentifiers.id_blake2s224;
+ oids["BLAKE2S-256"] = MiscObjectIdentifiers.id_blake2s256;
+ oids["GOST3411-2012-256"] = RosstandartObjectIdentifiers.id_tc26_gost_3411_12_256;
+ oids["GOST3411-2012-512"] = RosstandartObjectIdentifiers.id_tc26_gost_3411_12_512;
+ oids["DSTU7564-256"] = UAObjectIdentifiers.dstu7564digest_256;
+ oids["DSTU7564-384"] = UAObjectIdentifiers.dstu7564digest_384;
+ oids["DSTU7564-512"] = UAObjectIdentifiers.dstu7564digest_512;
+ }
+
+ ///
+ /// Returns a ObjectIdentifier for a given digest mechanism.
+ ///
+ /// A string representation of the digest meanism.
+ /// A DerObjectIdentifier, null if the Oid is not available.
+
+ public static DerObjectIdentifier GetObjectIdentifier(
+ string mechanism)
+ {
+ if (mechanism == null)
+ throw new System.ArgumentNullException("mechanism");
+
+ mechanism = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(mechanism);
+ string aliased = (string) algorithms[mechanism];
+
+ if (aliased != null)
+ mechanism = aliased;
+
+ return (DerObjectIdentifier) oids[mechanism];
+ }
+
+ public static ICollection Algorithms
+ {
+ get { return oids.Keys; }
+ }
+
+ public static IDigest GetDigest(
+ DerObjectIdentifier id)
+ {
+ return GetDigest(id.Id);
+ }
+
+ public static IDigest GetDigest(
+ string algorithm)
+ {
+ string upper = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm);
+ string mechanism = (string) algorithms[upper];
+
+ if (mechanism == null)
+ {
+ mechanism = upper;
+ }
+
+ try
+ {
+ DigestAlgorithm digestAlgorithm = (DigestAlgorithm)Enums.GetEnumValue(
+ typeof(DigestAlgorithm), mechanism);
+
+ switch (digestAlgorithm)
+ {
+ case DigestAlgorithm.BLAKE2B_160: return new Blake2bDigest(160);
+ case DigestAlgorithm.BLAKE2B_256: return new Blake2bDigest(256);
+ case DigestAlgorithm.BLAKE2B_384: return new Blake2bDigest(384);
+ case DigestAlgorithm.BLAKE2B_512: return new Blake2bDigest(512);
+ case DigestAlgorithm.BLAKE2S_128: return new Blake2sDigest(128);
+ case DigestAlgorithm.BLAKE2S_160: return new Blake2sDigest(160);
+ case DigestAlgorithm.BLAKE2S_224: return new Blake2sDigest(224);
+ case DigestAlgorithm.BLAKE2S_256: return new Blake2sDigest(256);
+ case DigestAlgorithm.DSTU7564_256: return new Dstu7564Digest(256);
+ case DigestAlgorithm.DSTU7564_384: return new Dstu7564Digest(384);
+ case DigestAlgorithm.DSTU7564_512: return new Dstu7564Digest(512);
+ case DigestAlgorithm.GOST3411: return new Gost3411Digest();
+ case DigestAlgorithm.GOST3411_2012_256: return new GOST3411_2012_256Digest();
+ case DigestAlgorithm.GOST3411_2012_512: return new GOST3411_2012_512Digest();
+ case DigestAlgorithm.KECCAK_224: return new KeccakDigest(224);
+ case DigestAlgorithm.KECCAK_256: return new KeccakDigest(256);
+ case DigestAlgorithm.KECCAK_288: return new KeccakDigest(288);
+ case DigestAlgorithm.KECCAK_384: return new KeccakDigest(384);
+ case DigestAlgorithm.KECCAK_512: return new KeccakDigest(512);
+ case DigestAlgorithm.MD2: return new MD2Digest();
+ case DigestAlgorithm.MD4: return new MD4Digest();
+ case DigestAlgorithm.MD5: return new MD5Digest();
+ case DigestAlgorithm.NONE: return new NullDigest();
+ case DigestAlgorithm.RIPEMD128: return new RipeMD128Digest();
+ case DigestAlgorithm.RIPEMD160: return new RipeMD160Digest();
+ case DigestAlgorithm.RIPEMD256: return new RipeMD256Digest();
+ case DigestAlgorithm.RIPEMD320: return new RipeMD320Digest();
+ case DigestAlgorithm.SHA_1: return new Sha1Digest();
+ case DigestAlgorithm.SHA_224: return new Sha224Digest();
+ case DigestAlgorithm.SHA_256: return new Sha256Digest();
+ case DigestAlgorithm.SHA_384: return new Sha384Digest();
+ case DigestAlgorithm.SHA_512: return new Sha512Digest();
+ case DigestAlgorithm.SHA_512_224: return new Sha512tDigest(224);
+ case DigestAlgorithm.SHA_512_256: return new Sha512tDigest(256);
+ case DigestAlgorithm.SHA3_224: return new Sha3Digest(224);
+ case DigestAlgorithm.SHA3_256: return new Sha3Digest(256);
+ case DigestAlgorithm.SHA3_384: return new Sha3Digest(384);
+ case DigestAlgorithm.SHA3_512: return new Sha3Digest(512);
+ case DigestAlgorithm.SHAKE128: return new ShakeDigest(128);
+ case DigestAlgorithm.SHAKE256: return new ShakeDigest(256);
+ case DigestAlgorithm.SM3: return new SM3Digest();
+ case DigestAlgorithm.TIGER: return new TigerDigest();
+ case DigestAlgorithm.WHIRLPOOL: return new WhirlpoolDigest();
+ }
+ }
+ catch (ArgumentException)
+ {
+ }
+
+ throw new SecurityUtilityException("Digest " + mechanism + " not recognised.");
+ }
+
+ public static string GetAlgorithmName(
+ DerObjectIdentifier oid)
+ {
+ return (string) algorithms[oid.Id];
+ }
+
+ public static byte[] CalculateDigest(string algorithm, byte[] input)
+ {
+ IDigest digest = GetDigest(algorithm);
+ digest.BlockUpdate(input, 0, input.Length);
+ return DoFinal(digest);
+ }
+
+ public static byte[] DoFinal(
+ IDigest digest)
+ {
+ byte[] b = new byte[digest.GetDigestSize()];
+ digest.DoFinal(b, 0);
+ return b;
+ }
+
+ public static byte[] DoFinal(
+ IDigest digest,
+ byte[] input)
+ {
+ digest.BlockUpdate(input, 0, input.Length);
+ return DoFinal(digest);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/DigestUtilities.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/DigestUtilities.cs.meta
new file mode 100644
index 00000000..cb014f72
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/DigestUtilities.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: e02cda66c755ac94ea2ee882e29a2dfe
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/DotNetUtilities.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/DotNetUtilities.cs
new file mode 100644
index 00000000..c0620d08
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/DotNetUtilities.cs
@@ -0,0 +1,264 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+#if !(NETCF_1_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+
+using System;
+using System.Security.Cryptography;
+using SystemX509 = System.Security.Cryptography.X509Certificates;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security
+{
+ ///
+ /// A class containing methods to interface the BouncyCastle world to the .NET Crypto world.
+ ///
+ public sealed class DotNetUtilities
+ {
+ private DotNetUtilities()
+ {
+ }
+
+ ///
+ /// Create an System.Security.Cryptography.X509Certificate from an X509Certificate Structure.
+ ///
+ ///
+ /// A System.Security.Cryptography.X509Certificate.
+ public static SystemX509.X509Certificate ToX509Certificate(
+ X509CertificateStructure x509Struct)
+ {
+ return new SystemX509.X509Certificate(x509Struct.GetDerEncoded());
+ }
+
+ public static SystemX509.X509Certificate ToX509Certificate(
+ X509Certificate x509Cert)
+ {
+ return new SystemX509.X509Certificate(x509Cert.GetEncoded());
+ }
+
+ public static X509Certificate FromX509Certificate(
+ SystemX509.X509Certificate x509Cert)
+ {
+ return new X509CertificateParser().ReadCertificate(x509Cert.GetRawCertData());
+ }
+
+ public static AsymmetricCipherKeyPair GetDsaKeyPair(DSA dsa)
+ {
+ return GetDsaKeyPair(dsa.ExportParameters(true));
+ }
+
+ public static AsymmetricCipherKeyPair GetDsaKeyPair(DSAParameters dp)
+ {
+ DsaValidationParameters validationParameters = (dp.Seed != null)
+ ? new DsaValidationParameters(dp.Seed, dp.Counter)
+ : null;
+
+ DsaParameters parameters = new DsaParameters(
+ new BigInteger(1, dp.P),
+ new BigInteger(1, dp.Q),
+ new BigInteger(1, dp.G),
+ validationParameters);
+
+ DsaPublicKeyParameters pubKey = new DsaPublicKeyParameters(
+ new BigInteger(1, dp.Y),
+ parameters);
+
+ DsaPrivateKeyParameters privKey = new DsaPrivateKeyParameters(
+ new BigInteger(1, dp.X),
+ parameters);
+
+ return new AsymmetricCipherKeyPair(pubKey, privKey);
+ }
+
+ public static DsaPublicKeyParameters GetDsaPublicKey(DSA dsa)
+ {
+ return GetDsaPublicKey(dsa.ExportParameters(false));
+ }
+
+ public static DsaPublicKeyParameters GetDsaPublicKey(DSAParameters dp)
+ {
+ DsaValidationParameters validationParameters = (dp.Seed != null)
+ ? new DsaValidationParameters(dp.Seed, dp.Counter)
+ : null;
+
+ DsaParameters parameters = new DsaParameters(
+ new BigInteger(1, dp.P),
+ new BigInteger(1, dp.Q),
+ new BigInteger(1, dp.G),
+ validationParameters);
+
+ return new DsaPublicKeyParameters(
+ new BigInteger(1, dp.Y),
+ parameters);
+ }
+
+ public static AsymmetricCipherKeyPair GetRsaKeyPair(RSA rsa)
+ {
+ return GetRsaKeyPair(rsa.ExportParameters(true));
+ }
+
+ public static AsymmetricCipherKeyPair GetRsaKeyPair(RSAParameters rp)
+ {
+ BigInteger modulus = new BigInteger(1, rp.Modulus);
+ BigInteger pubExp = new BigInteger(1, rp.Exponent);
+
+ RsaKeyParameters pubKey = new RsaKeyParameters(
+ false,
+ modulus,
+ pubExp);
+
+ RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters(
+ modulus,
+ pubExp,
+ new BigInteger(1, rp.D),
+ new BigInteger(1, rp.P),
+ new BigInteger(1, rp.Q),
+ new BigInteger(1, rp.DP),
+ new BigInteger(1, rp.DQ),
+ new BigInteger(1, rp.InverseQ));
+
+ return new AsymmetricCipherKeyPair(pubKey, privKey);
+ }
+
+ public static RsaKeyParameters GetRsaPublicKey(RSA rsa)
+ {
+ return GetRsaPublicKey(rsa.ExportParameters(false));
+ }
+
+ public static RsaKeyParameters GetRsaPublicKey(
+ RSAParameters rp)
+ {
+ return new RsaKeyParameters(
+ false,
+ new BigInteger(1, rp.Modulus),
+ new BigInteger(1, rp.Exponent));
+ }
+
+ public static AsymmetricCipherKeyPair GetKeyPair(AsymmetricAlgorithm privateKey)
+ {
+ if (privateKey is DSA)
+ {
+ return GetDsaKeyPair((DSA)privateKey);
+ }
+
+ if (privateKey is RSA)
+ {
+ return GetRsaKeyPair((RSA)privateKey);
+ }
+
+ throw new ArgumentException("Unsupported algorithm specified", "privateKey");
+ }
+
+ public static RSA ToRSA(RsaKeyParameters rsaKey)
+ {
+ // TODO This appears to not work for private keys (when no CRT info)
+ return CreateRSAProvider(ToRSAParameters(rsaKey));
+ }
+
+ public static RSA ToRSA(RsaKeyParameters rsaKey, CspParameters csp)
+ {
+ // TODO This appears to not work for private keys (when no CRT info)
+ return CreateRSAProvider(ToRSAParameters(rsaKey), csp);
+ }
+
+ public static RSA ToRSA(RsaPrivateCrtKeyParameters privKey)
+ {
+ return CreateRSAProvider(ToRSAParameters(privKey));
+ }
+
+ public static RSA ToRSA(RsaPrivateCrtKeyParameters privKey, CspParameters csp)
+ {
+ return CreateRSAProvider(ToRSAParameters(privKey), csp);
+ }
+
+ public static RSA ToRSA(RsaPrivateKeyStructure privKey)
+ {
+ return CreateRSAProvider(ToRSAParameters(privKey));
+ }
+
+ public static RSA ToRSA(RsaPrivateKeyStructure privKey, CspParameters csp)
+ {
+ return CreateRSAProvider(ToRSAParameters(privKey), csp);
+ }
+
+ public static RSAParameters ToRSAParameters(RsaKeyParameters rsaKey)
+ {
+ RSAParameters rp = new RSAParameters();
+ rp.Modulus = rsaKey.Modulus.ToByteArrayUnsigned();
+ if (rsaKey.IsPrivate)
+ rp.D = ConvertRSAParametersField(rsaKey.Exponent, rp.Modulus.Length);
+ else
+ rp.Exponent = rsaKey.Exponent.ToByteArrayUnsigned();
+ return rp;
+ }
+
+ public static RSAParameters ToRSAParameters(RsaPrivateCrtKeyParameters privKey)
+ {
+ RSAParameters rp = new RSAParameters();
+ rp.Modulus = privKey.Modulus.ToByteArrayUnsigned();
+ rp.Exponent = privKey.PublicExponent.ToByteArrayUnsigned();
+ rp.P = privKey.P.ToByteArrayUnsigned();
+ rp.Q = privKey.Q.ToByteArrayUnsigned();
+ rp.D = ConvertRSAParametersField(privKey.Exponent, rp.Modulus.Length);
+ rp.DP = ConvertRSAParametersField(privKey.DP, rp.P.Length);
+ rp.DQ = ConvertRSAParametersField(privKey.DQ, rp.Q.Length);
+ rp.InverseQ = ConvertRSAParametersField(privKey.QInv, rp.Q.Length);
+ return rp;
+ }
+
+ public static RSAParameters ToRSAParameters(RsaPrivateKeyStructure privKey)
+ {
+ RSAParameters rp = new RSAParameters();
+ rp.Modulus = privKey.Modulus.ToByteArrayUnsigned();
+ rp.Exponent = privKey.PublicExponent.ToByteArrayUnsigned();
+ rp.P = privKey.Prime1.ToByteArrayUnsigned();
+ rp.Q = privKey.Prime2.ToByteArrayUnsigned();
+ rp.D = ConvertRSAParametersField(privKey.PrivateExponent, rp.Modulus.Length);
+ rp.DP = ConvertRSAParametersField(privKey.Exponent1, rp.P.Length);
+ rp.DQ = ConvertRSAParametersField(privKey.Exponent2, rp.Q.Length);
+ rp.InverseQ = ConvertRSAParametersField(privKey.Coefficient, rp.Q.Length);
+ return rp;
+ }
+
+ // TODO Move functionality to more general class
+ private static byte[] ConvertRSAParametersField(BigInteger n, int size)
+ {
+ byte[] bs = n.ToByteArrayUnsigned();
+
+ if (bs.Length == size)
+ return bs;
+
+ if (bs.Length > size)
+ throw new ArgumentException("Specified size too small", "size");
+
+ byte[] padded = new byte[size];
+ Array.Copy(bs, 0, padded, size - bs.Length, bs.Length);
+ return padded;
+ }
+
+ private static RSA CreateRSAProvider(RSAParameters rp)
+ {
+ CspParameters csp = new CspParameters();
+ csp.KeyContainerName = string.Format("BouncyCastle-{0}", Guid.NewGuid());
+ RSACryptoServiceProvider rsaCsp = new RSACryptoServiceProvider(csp);
+ rsaCsp.ImportParameters(rp);
+ return rsaCsp;
+ }
+
+ private static RSA CreateRSAProvider(RSAParameters rp, CspParameters csp)
+ {
+ RSACryptoServiceProvider rsaCsp = new RSACryptoServiceProvider(csp);
+ rsaCsp.ImportParameters(rp);
+ return rsaCsp;
+ }
+ }
+}
+
+#endif
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/DotNetUtilities.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/DotNetUtilities.cs.meta
new file mode 100644
index 00000000..f376fde4
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/DotNetUtilities.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0d8495888a65d924dac5d55806d57007
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/GeneralSecurityException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/GeneralSecurityException.cs
new file mode 100644
index 00000000..ec37dc70
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/GeneralSecurityException.cs
@@ -0,0 +1,33 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security
+{
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class GeneralSecurityException
+ : Exception
+ {
+ public GeneralSecurityException()
+ : base()
+ {
+ }
+
+ public GeneralSecurityException(
+ string message)
+ : base(message)
+ {
+ }
+
+ public GeneralSecurityException(
+ string message,
+ Exception exception)
+ : base(message, exception)
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/GeneralSecurityException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/GeneralSecurityException.cs.meta
new file mode 100644
index 00000000..47ce6133
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/GeneralSecurityException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: b0d8c41189aa7a947b6acbdfbd4f0401
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/GeneratorUtilities.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/GeneratorUtilities.cs
new file mode 100644
index 00000000..09b9903e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/GeneratorUtilities.cs
@@ -0,0 +1,394 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.EdEC;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Iana;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Kisa;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Ntt;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Oiw;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Rosstandart;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security
+{
+ public sealed class GeneratorUtilities
+ {
+ private GeneratorUtilities()
+ {
+ }
+
+ private static readonly IDictionary kgAlgorithms = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ private static readonly IDictionary kpgAlgorithms = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ private static readonly IDictionary defaultKeySizes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+
+ static GeneratorUtilities()
+ {
+ //
+ // key generators.
+ //
+ AddKgAlgorithm("AES",
+ "AESWRAP");
+ AddKgAlgorithm("AES128",
+ "2.16.840.1.101.3.4.2",
+ NistObjectIdentifiers.IdAes128Cbc,
+ NistObjectIdentifiers.IdAes128Cfb,
+ NistObjectIdentifiers.IdAes128Ecb,
+ NistObjectIdentifiers.IdAes128Ofb,
+ NistObjectIdentifiers.IdAes128Wrap);
+ AddKgAlgorithm("AES192",
+ "2.16.840.1.101.3.4.22",
+ NistObjectIdentifiers.IdAes192Cbc,
+ NistObjectIdentifiers.IdAes192Cfb,
+ NistObjectIdentifiers.IdAes192Ecb,
+ NistObjectIdentifiers.IdAes192Ofb,
+ NistObjectIdentifiers.IdAes192Wrap);
+ AddKgAlgorithm("AES256",
+ "2.16.840.1.101.3.4.42",
+ NistObjectIdentifiers.IdAes256Cbc,
+ NistObjectIdentifiers.IdAes256Cfb,
+ NistObjectIdentifiers.IdAes256Ecb,
+ NistObjectIdentifiers.IdAes256Ofb,
+ NistObjectIdentifiers.IdAes256Wrap);
+ AddKgAlgorithm("BLOWFISH",
+ "1.3.6.1.4.1.3029.1.2");
+ AddKgAlgorithm("CAMELLIA",
+ "CAMELLIAWRAP");
+ AddKgAlgorithm("CAMELLIA128",
+ NttObjectIdentifiers.IdCamellia128Cbc,
+ NttObjectIdentifiers.IdCamellia128Wrap);
+ AddKgAlgorithm("CAMELLIA192",
+ NttObjectIdentifiers.IdCamellia192Cbc,
+ NttObjectIdentifiers.IdCamellia192Wrap);
+ AddKgAlgorithm("CAMELLIA256",
+ NttObjectIdentifiers.IdCamellia256Cbc,
+ NttObjectIdentifiers.IdCamellia256Wrap);
+ AddKgAlgorithm("CAST5",
+ "1.2.840.113533.7.66.10");
+ AddKgAlgorithm("CAST6");
+ AddKgAlgorithm("DES",
+ OiwObjectIdentifiers.DesCbc,
+ OiwObjectIdentifiers.DesCfb,
+ OiwObjectIdentifiers.DesEcb,
+ OiwObjectIdentifiers.DesOfb);
+ AddKgAlgorithm("DESEDE",
+ "DESEDEWRAP",
+ "TDEA",
+ OiwObjectIdentifiers.DesEde);
+ AddKgAlgorithm("DESEDE3",
+ PkcsObjectIdentifiers.DesEde3Cbc,
+ PkcsObjectIdentifiers.IdAlgCms3DesWrap);
+ AddKgAlgorithm("GOST28147",
+ "GOST",
+ "GOST-28147",
+ CryptoProObjectIdentifiers.GostR28147Cbc);
+ AddKgAlgorithm("HC128");
+ AddKgAlgorithm("HC256");
+ AddKgAlgorithm("IDEA",
+ "1.3.6.1.4.1.188.7.1.1.2");
+ AddKgAlgorithm("NOEKEON");
+ AddKgAlgorithm("RC2",
+ PkcsObjectIdentifiers.RC2Cbc,
+ PkcsObjectIdentifiers.IdAlgCmsRC2Wrap);
+ AddKgAlgorithm("RC4",
+ "ARC4",
+ "1.2.840.113549.3.4");
+ AddKgAlgorithm("RC5",
+ "RC5-32");
+ AddKgAlgorithm("RC5-64");
+ AddKgAlgorithm("RC6");
+ AddKgAlgorithm("RIJNDAEL");
+ AddKgAlgorithm("SALSA20");
+ AddKgAlgorithm("SEED",
+ KisaObjectIdentifiers.IdNpkiAppCmsSeedWrap,
+ KisaObjectIdentifiers.IdSeedCbc);
+ AddKgAlgorithm("SERPENT");
+ AddKgAlgorithm("SKIPJACK");
+ AddKgAlgorithm("SM4");
+ AddKgAlgorithm("TEA");
+ AddKgAlgorithm("THREEFISH-256");
+ AddKgAlgorithm("THREEFISH-512");
+ AddKgAlgorithm("THREEFISH-1024");
+ AddKgAlgorithm("TNEPRES");
+ AddKgAlgorithm("TWOFISH");
+ AddKgAlgorithm("VMPC");
+ AddKgAlgorithm("VMPC-KSA3");
+ AddKgAlgorithm("XTEA");
+
+ //
+ // HMac key generators
+ //
+ AddHMacKeyGenerator("MD2");
+ AddHMacKeyGenerator("MD4");
+ AddHMacKeyGenerator("MD5",
+ IanaObjectIdentifiers.HmacMD5);
+ AddHMacKeyGenerator("SHA1",
+ PkcsObjectIdentifiers.IdHmacWithSha1,
+ IanaObjectIdentifiers.HmacSha1);
+ AddHMacKeyGenerator("SHA224",
+ PkcsObjectIdentifiers.IdHmacWithSha224);
+ AddHMacKeyGenerator("SHA256",
+ PkcsObjectIdentifiers.IdHmacWithSha256);
+ AddHMacKeyGenerator("SHA384",
+ PkcsObjectIdentifiers.IdHmacWithSha384);
+ AddHMacKeyGenerator("SHA512",
+ PkcsObjectIdentifiers.IdHmacWithSha512);
+ AddHMacKeyGenerator("SHA512/224");
+ AddHMacKeyGenerator("SHA512/256");
+ AddHMacKeyGenerator("KECCAK224");
+ AddHMacKeyGenerator("KECCAK256");
+ AddHMacKeyGenerator("KECCAK288");
+ AddHMacKeyGenerator("KECCAK384");
+ AddHMacKeyGenerator("KECCAK512");
+ AddHMacKeyGenerator("SHA3-224",
+ NistObjectIdentifiers.IdHMacWithSha3_224);
+ AddHMacKeyGenerator("SHA3-256",
+ NistObjectIdentifiers.IdHMacWithSha3_256);
+ AddHMacKeyGenerator("SHA3-384",
+ NistObjectIdentifiers.IdHMacWithSha3_384);
+ AddHMacKeyGenerator("SHA3-512",
+ NistObjectIdentifiers.IdHMacWithSha3_512);
+ AddHMacKeyGenerator("RIPEMD128");
+ AddHMacKeyGenerator("RIPEMD160",
+ IanaObjectIdentifiers.HmacRipeMD160);
+ AddHMacKeyGenerator("TIGER",
+ IanaObjectIdentifiers.HmacTiger);
+ AddHMacKeyGenerator("GOST3411-2012-256",
+ RosstandartObjectIdentifiers.id_tc26_hmac_gost_3411_12_256);
+ AddHMacKeyGenerator("GOST3411-2012-512",
+ RosstandartObjectIdentifiers.id_tc26_hmac_gost_3411_12_512);
+
+ //
+ // key pair generators.
+ //
+ AddKpgAlgorithm("DH",
+ "DIFFIEHELLMAN");
+ AddKpgAlgorithm("DSA");
+ AddKpgAlgorithm("EC",
+ // TODO Should this be an alias for ECDH?
+ X9ObjectIdentifiers.DHSinglePassStdDHSha1KdfScheme);
+ AddKpgAlgorithm("ECDH",
+ "ECIES");
+ AddKpgAlgorithm("ECDHC");
+ AddKpgAlgorithm("ECMQV",
+ X9ObjectIdentifiers.MqvSinglePassSha1KdfScheme);
+ AddKpgAlgorithm("ECDSA");
+ AddKpgAlgorithm("ECGOST3410",
+ "ECGOST-3410",
+ "GOST-3410-2001");
+ AddKpgAlgorithm("Ed25519",
+ "Ed25519ctx",
+ "Ed25519ph",
+ EdECObjectIdentifiers.id_Ed25519);
+ AddKpgAlgorithm("Ed448",
+ "Ed448ph",
+ EdECObjectIdentifiers.id_Ed448);
+ AddKpgAlgorithm("ELGAMAL");
+ AddKpgAlgorithm("GOST3410",
+ "GOST-3410",
+ "GOST-3410-94");
+ AddKpgAlgorithm("RSA",
+ "1.2.840.113549.1.1.1");
+ AddKpgAlgorithm("X25519",
+ EdECObjectIdentifiers.id_X25519);
+ AddKpgAlgorithm("X448",
+ EdECObjectIdentifiers.id_X448);
+
+ AddDefaultKeySizeEntries(64, "DES");
+ AddDefaultKeySizeEntries(80, "SKIPJACK");
+ AddDefaultKeySizeEntries(128, "AES128", "BLOWFISH", "CAMELLIA128", "CAST5", "DESEDE",
+ "HC128", "HMACMD2", "HMACMD4", "HMACMD5", "HMACRIPEMD128", "IDEA", "NOEKEON",
+ "RC2", "RC4", "RC5", "SALSA20", "SEED", "SM4", "TEA", "XTEA", "VMPC", "VMPC-KSA3");
+ AddDefaultKeySizeEntries(160, "HMACRIPEMD160", "HMACSHA1");
+ AddDefaultKeySizeEntries(192, "AES", "AES192", "CAMELLIA192", "DESEDE3", "HMACTIGER",
+ "RIJNDAEL", "SERPENT", "TNEPRES");
+ AddDefaultKeySizeEntries(224, "HMACSHA3-224", "HMACKECCAK224", "HMACSHA224", "HMACSHA512/224");
+ AddDefaultKeySizeEntries(256, "AES256", "CAMELLIA", "CAMELLIA256", "CAST6", "GOST28147",
+ "HC256", "HMACGOST3411-2012-256", "HMACSHA3-256", "HMACKECCAK256", "HMACSHA256", "HMACSHA512/256", "RC5-64", "RC6", "THREEFISH-256", "TWOFISH");
+ AddDefaultKeySizeEntries(288, "HMACKECCAK288");
+ AddDefaultKeySizeEntries(384, "HMACSHA3-384", "HMACKECCAK384", "HMACSHA384");
+ AddDefaultKeySizeEntries(512, "HMACGOST3411-2012-512", "HMACSHA3-512", "HMACKECCAK512", "HMACSHA512", "THREEFISH-512");
+ AddDefaultKeySizeEntries(1024, "THREEFISH-1024");
+ }
+
+ private static void AddDefaultKeySizeEntries(int size, params string[] algorithms)
+ {
+ foreach (string algorithm in algorithms)
+ {
+ defaultKeySizes.Add(algorithm, size);
+ }
+ }
+
+ private static void AddKgAlgorithm(
+ string canonicalName,
+ params object[] aliases)
+ {
+ kgAlgorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(canonicalName)] = canonicalName;
+
+ foreach (object alias in aliases)
+ {
+ kgAlgorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(alias.ToString())] = canonicalName;
+ }
+ }
+
+ private static void AddKpgAlgorithm(
+ string canonicalName,
+ params object[] aliases)
+ {
+ kpgAlgorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(canonicalName)] = canonicalName;
+
+ foreach (object alias in aliases)
+ {
+ kpgAlgorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(alias.ToString())] = canonicalName;
+ }
+ }
+
+ private static void AddHMacKeyGenerator(
+ string algorithm,
+ params object[] aliases)
+ {
+ string mainName = "HMAC" + algorithm;
+
+ kgAlgorithms[mainName] = mainName;
+ kgAlgorithms["HMAC-" + algorithm] = mainName;
+ kgAlgorithms["HMAC/" + algorithm] = mainName;
+
+ foreach (object alias in aliases)
+ {
+ kgAlgorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(alias.ToString())] = mainName;
+ }
+ }
+
+ // TODO Consider making this public
+ internal static string GetCanonicalKeyGeneratorAlgorithm(
+ string algorithm)
+ {
+ return (string) kgAlgorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm)];
+ }
+
+ // TODO Consider making this public
+ internal static string GetCanonicalKeyPairGeneratorAlgorithm(
+ string algorithm)
+ {
+ return (string)kpgAlgorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm)];
+ }
+
+ public static CipherKeyGenerator GetKeyGenerator(
+ DerObjectIdentifier oid)
+ {
+ return GetKeyGenerator(oid.Id);
+ }
+
+ public static CipherKeyGenerator GetKeyGenerator(
+ string algorithm)
+ {
+ string canonicalName = GetCanonicalKeyGeneratorAlgorithm(algorithm);
+
+ if (canonicalName == null)
+ throw new SecurityUtilityException("KeyGenerator " + algorithm + " not recognised.");
+
+ int defaultKeySize = FindDefaultKeySize(canonicalName);
+ if (defaultKeySize == -1)
+ throw new SecurityUtilityException("KeyGenerator " + algorithm
+ + " (" + canonicalName + ") not supported.");
+
+ if (canonicalName == "DES")
+ return new DesKeyGenerator(defaultKeySize);
+
+ if (canonicalName == "DESEDE" || canonicalName == "DESEDE3")
+ return new DesEdeKeyGenerator(defaultKeySize);
+
+ return new CipherKeyGenerator(defaultKeySize);
+ }
+
+ public static IAsymmetricCipherKeyPairGenerator GetKeyPairGenerator(
+ DerObjectIdentifier oid)
+ {
+ return GetKeyPairGenerator(oid.Id);
+ }
+
+ public static IAsymmetricCipherKeyPairGenerator GetKeyPairGenerator(
+ string algorithm)
+ {
+ string canonicalName = GetCanonicalKeyPairGeneratorAlgorithm(algorithm);
+
+ if (canonicalName == null)
+ throw new SecurityUtilityException("KeyPairGenerator " + algorithm + " not recognised.");
+
+ if (canonicalName == "DH")
+ return new DHKeyPairGenerator();
+
+ if (canonicalName == "DSA")
+ return new DsaKeyPairGenerator();
+
+ // "EC", "ECDH", "ECDHC", "ECDSA", "ECGOST3410", "ECMQV"
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(canonicalName, "EC"))
+ return new ECKeyPairGenerator(canonicalName);
+
+ if (canonicalName == "Ed25519")
+ return new Ed25519KeyPairGenerator();
+
+ if (canonicalName == "Ed448")
+ return new Ed448KeyPairGenerator();
+
+ if (canonicalName == "ELGAMAL")
+ return new ElGamalKeyPairGenerator();
+
+ if (canonicalName == "GOST3410")
+ return new Gost3410KeyPairGenerator();
+
+ if (canonicalName == "RSA")
+ return new RsaKeyPairGenerator();
+
+ if (canonicalName == "X25519")
+ return new X25519KeyPairGenerator();
+
+ if (canonicalName == "X448")
+ return new X448KeyPairGenerator();
+
+ throw new SecurityUtilityException("KeyPairGenerator " + algorithm
+ + " (" + canonicalName + ") not supported.");
+ }
+
+ internal static int GetDefaultKeySize(
+ DerObjectIdentifier oid)
+ {
+ return GetDefaultKeySize(oid.Id);
+ }
+
+ internal static int GetDefaultKeySize(
+ string algorithm)
+ {
+ string canonicalName = GetCanonicalKeyGeneratorAlgorithm(algorithm);
+
+ if (canonicalName == null)
+ throw new SecurityUtilityException("KeyGenerator " + algorithm + " not recognised.");
+
+ int defaultKeySize = FindDefaultKeySize(canonicalName);
+ if (defaultKeySize == -1)
+ throw new SecurityUtilityException("KeyGenerator " + algorithm
+ + " (" + canonicalName + ") not supported.");
+
+ return defaultKeySize;
+ }
+
+ private static int FindDefaultKeySize(
+ string canonicalName)
+ {
+ if (!defaultKeySizes.Contains(canonicalName))
+ return -1;
+
+ return (int)defaultKeySizes[canonicalName];
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/GeneratorUtilities.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/GeneratorUtilities.cs.meta
new file mode 100644
index 00000000..ed0b2e29
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/GeneratorUtilities.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 71114e4af0270f34ba2d802c33a9bd5b
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/InvalidKeyException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/InvalidKeyException.cs
new file mode 100644
index 00000000..0b9a79d9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/InvalidKeyException.cs
@@ -0,0 +1,18 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security
+{
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class InvalidKeyException : KeyException
+ {
+ public InvalidKeyException() : base() { }
+ public InvalidKeyException(string message) : base(message) { }
+ public InvalidKeyException(string message, Exception exception) : base(message, exception) { }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/InvalidKeyException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/InvalidKeyException.cs.meta
new file mode 100644
index 00000000..8b9b345d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/InvalidKeyException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 9842e68a8ae8895468c08cc98231c060
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/InvalidParameterException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/InvalidParameterException.cs
new file mode 100644
index 00000000..5bce04a8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/InvalidParameterException.cs
@@ -0,0 +1,18 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security
+{
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class InvalidParameterException : KeyException
+ {
+ public InvalidParameterException() : base() { }
+ public InvalidParameterException(string message) : base(message) { }
+ public InvalidParameterException(string message, Exception exception) : base(message, exception) { }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/InvalidParameterException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/InvalidParameterException.cs.meta
new file mode 100644
index 00000000..6807bfe2
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/InvalidParameterException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a02c4f553fcf8d749801284afc4da77a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/KeyException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/KeyException.cs
new file mode 100644
index 00000000..91872fcb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/KeyException.cs
@@ -0,0 +1,18 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security
+{
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class KeyException : GeneralSecurityException
+ {
+ public KeyException() : base() { }
+ public KeyException(string message) : base(message) { }
+ public KeyException(string message, Exception exception) : base(message, exception) { }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/KeyException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/KeyException.cs.meta
new file mode 100644
index 00000000..17107b96
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/KeyException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 981c3b6a3e40ccc479b9b7c4a5e4568e
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/MacUtilities.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/MacUtilities.cs
new file mode 100644
index 00000000..1a30b6f9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/MacUtilities.cs
@@ -0,0 +1,270 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.Globalization;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Iana;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Rosstandart;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Paddings;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security
+{
+ ///
+ /// Utility class for creating HMac object from their names/Oids
+ ///
+ public sealed class MacUtilities
+ {
+ private MacUtilities()
+ {
+ }
+
+ private static readonly IDictionary algorithms = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ //private static readonly IDictionary oids = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+
+ static MacUtilities()
+ {
+ algorithms[IanaObjectIdentifiers.HmacMD5.Id] = "HMAC-MD5";
+ algorithms[IanaObjectIdentifiers.HmacRipeMD160.Id] = "HMAC-RIPEMD160";
+ algorithms[IanaObjectIdentifiers.HmacSha1.Id] = "HMAC-SHA1";
+ algorithms[IanaObjectIdentifiers.HmacTiger.Id] = "HMAC-TIGER";
+
+ algorithms[PkcsObjectIdentifiers.IdHmacWithSha1.Id] = "HMAC-SHA1";
+ algorithms[PkcsObjectIdentifiers.IdHmacWithSha224.Id] = "HMAC-SHA224";
+ algorithms[PkcsObjectIdentifiers.IdHmacWithSha256.Id] = "HMAC-SHA256";
+ algorithms[PkcsObjectIdentifiers.IdHmacWithSha384.Id] = "HMAC-SHA384";
+ algorithms[PkcsObjectIdentifiers.IdHmacWithSha512.Id] = "HMAC-SHA512";
+
+ algorithms[NistObjectIdentifiers.IdHMacWithSha3_224.Id] = "HMAC-SHA3-224";
+ algorithms[NistObjectIdentifiers.IdHMacWithSha3_256.Id] = "HMAC-SHA3-256";
+ algorithms[NistObjectIdentifiers.IdHMacWithSha3_384.Id] = "HMAC-SHA3-384";
+ algorithms[NistObjectIdentifiers.IdHMacWithSha3_512.Id] = "HMAC-SHA3-512";
+
+ algorithms[RosstandartObjectIdentifiers.id_tc26_hmac_gost_3411_12_256.Id] = "HMAC-GOST3411-2012-256";
+ algorithms[RosstandartObjectIdentifiers.id_tc26_hmac_gost_3411_12_512.Id] = "HMAC-GOST3411-2012-512";
+
+ // TODO AESMAC?
+
+ algorithms["DES"] = "DESMAC";
+ algorithms["DES/CFB8"] = "DESMAC/CFB8";
+ algorithms["DES64"] = "DESMAC64";
+ algorithms["DESEDE"] = "DESEDEMAC";
+ algorithms[PkcsObjectIdentifiers.DesEde3Cbc.Id] = "DESEDEMAC";
+ algorithms["DESEDE/CFB8"] = "DESEDEMAC/CFB8";
+ algorithms["DESISO9797MAC"] = "DESWITHISO9797";
+ algorithms["DESEDE64"] = "DESEDEMAC64";
+
+ algorithms["DESEDE64WITHISO7816-4PADDING"] = "DESEDEMAC64WITHISO7816-4PADDING";
+ algorithms["DESEDEISO9797ALG1MACWITHISO7816-4PADDING"] = "DESEDEMAC64WITHISO7816-4PADDING";
+ algorithms["DESEDEISO9797ALG1WITHISO7816-4PADDING"] = "DESEDEMAC64WITHISO7816-4PADDING";
+
+ algorithms["ISO9797ALG3"] = "ISO9797ALG3MAC";
+ algorithms["ISO9797ALG3MACWITHISO7816-4PADDING"] = "ISO9797ALG3WITHISO7816-4PADDING";
+
+ algorithms["SKIPJACK"] = "SKIPJACKMAC";
+ algorithms["SKIPJACK/CFB8"] = "SKIPJACKMAC/CFB8";
+ algorithms["IDEA"] = "IDEAMAC";
+ algorithms["IDEA/CFB8"] = "IDEAMAC/CFB8";
+ algorithms["RC2"] = "RC2MAC";
+ algorithms["RC2/CFB8"] = "RC2MAC/CFB8";
+ algorithms["RC5"] = "RC5MAC";
+ algorithms["RC5/CFB8"] = "RC5MAC/CFB8";
+ algorithms["GOST28147"] = "GOST28147MAC";
+ algorithms["VMPC"] = "VMPCMAC";
+ algorithms["VMPC-MAC"] = "VMPCMAC";
+ algorithms["SIPHASH"] = "SIPHASH-2-4";
+
+ algorithms["PBEWITHHMACSHA"] = "PBEWITHHMACSHA1";
+ algorithms["1.3.14.3.2.26"] = "PBEWITHHMACSHA1";
+ }
+
+// ///
+// /// Returns a ObjectIdentifier for a given digest mechanism.
+// ///
+// /// A string representation of the digest meanism.
+// /// A DerObjectIdentifier, null if the Oid is not available.
+// public static DerObjectIdentifier GetObjectIdentifier(
+// string mechanism)
+// {
+// mechanism = (string) algorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(mechanism)];
+//
+// if (mechanism != null)
+// {
+// return (DerObjectIdentifier)oids[mechanism];
+// }
+//
+// return null;
+// }
+
+// public static ICollection Algorithms
+// {
+// get { return oids.Keys; }
+// }
+
+ public static IMac GetMac(
+ DerObjectIdentifier id)
+ {
+ return GetMac(id.Id);
+ }
+
+ public static IMac GetMac(
+ string algorithm)
+ {
+ string upper = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm);
+
+ string mechanism = (string) algorithms[upper];
+
+ if (mechanism == null)
+ {
+ mechanism = upper;
+ }
+
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "PBEWITH"))
+ {
+ mechanism = mechanism.Substring("PBEWITH".Length);
+ }
+
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "HMAC"))
+ {
+ string digestName;
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "HMAC-") || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "HMAC/"))
+ {
+ digestName = mechanism.Substring(5);
+ }
+ else
+ {
+ digestName = mechanism.Substring(4);
+ }
+
+ return new HMac(DigestUtilities.GetDigest(digestName));
+ }
+
+ if (mechanism == "AESCMAC")
+ {
+ return new CMac(new AesEngine());
+ }
+ if (mechanism == "DESMAC")
+ {
+ return new CbcBlockCipherMac(new DesEngine());
+ }
+ if (mechanism == "DESMAC/CFB8")
+ {
+ return new CfbBlockCipherMac(new DesEngine());
+ }
+ if (mechanism == "DESMAC64")
+ {
+ return new CbcBlockCipherMac(new DesEngine(), 64);
+ }
+ if (mechanism == "DESEDECMAC")
+ {
+ return new CMac(new DesEdeEngine());
+ }
+ if (mechanism == "DESEDEMAC")
+ {
+ return new CbcBlockCipherMac(new DesEdeEngine());
+ }
+ if (mechanism == "DESEDEMAC/CFB8")
+ {
+ return new CfbBlockCipherMac(new DesEdeEngine());
+ }
+ if (mechanism == "DESEDEMAC64")
+ {
+ return new CbcBlockCipherMac(new DesEdeEngine(), 64);
+ }
+ if (mechanism == "DESEDEMAC64WITHISO7816-4PADDING")
+ {
+ return new CbcBlockCipherMac(new DesEdeEngine(), 64, new ISO7816d4Padding());
+ }
+ if (mechanism == "DESWITHISO9797"
+ || mechanism == "ISO9797ALG3MAC")
+ {
+ return new ISO9797Alg3Mac(new DesEngine());
+ }
+ if (mechanism == "ISO9797ALG3WITHISO7816-4PADDING")
+ {
+ return new ISO9797Alg3Mac(new DesEngine(), new ISO7816d4Padding());
+ }
+ if (mechanism == "SKIPJACKMAC")
+ {
+ return new CbcBlockCipherMac(new SkipjackEngine());
+ }
+ if (mechanism == "SKIPJACKMAC/CFB8")
+ {
+ return new CfbBlockCipherMac(new SkipjackEngine());
+ }
+ if (mechanism == "IDEAMAC")
+ {
+ return new CbcBlockCipherMac(new IdeaEngine());
+ }
+ if (mechanism == "IDEAMAC/CFB8")
+ {
+ return new CfbBlockCipherMac(new IdeaEngine());
+ }
+ if (mechanism == "RC2MAC")
+ {
+ return new CbcBlockCipherMac(new RC2Engine());
+ }
+ if (mechanism == "RC2MAC/CFB8")
+ {
+ return new CfbBlockCipherMac(new RC2Engine());
+ }
+ if (mechanism == "RC5MAC")
+ {
+ return new CbcBlockCipherMac(new RC532Engine());
+ }
+ if (mechanism == "RC5MAC/CFB8")
+ {
+ return new CfbBlockCipherMac(new RC532Engine());
+ }
+ if (mechanism == "GOST28147MAC")
+ {
+ return new Gost28147Mac();
+ }
+ if (mechanism == "VMPCMAC")
+ {
+ return new VmpcMac();
+ }
+ if (mechanism == "SIPHASH-2-4")
+ {
+ return new SipHash();
+ }
+ throw new SecurityUtilityException("Mac " + mechanism + " not recognised.");
+ }
+
+ public static string GetAlgorithmName(
+ DerObjectIdentifier oid)
+ {
+ return (string) algorithms[oid.Id];
+ }
+
+ public static byte[] CalculateMac(string algorithm, ICipherParameters cp, byte[] input)
+ {
+ IMac mac = GetMac(algorithm);
+ mac.Init(cp);
+ mac.BlockUpdate(input, 0, input.Length);
+ return DoFinal(mac);
+ }
+
+ public static byte[] DoFinal(IMac mac)
+ {
+ byte[] b = new byte[mac.GetMacSize()];
+ mac.DoFinal(b, 0);
+ return b;
+ }
+
+ public static byte[] DoFinal(IMac mac, byte[] input)
+ {
+ mac.BlockUpdate(input, 0, input.Length);
+ return DoFinal(mac);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/MacUtilities.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/MacUtilities.cs.meta
new file mode 100644
index 00000000..d49ea38a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/MacUtilities.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: dc8314b890aed0843acbd81d9e6db0cc
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/NoSuchAlgorithmException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/NoSuchAlgorithmException.cs
new file mode 100644
index 00000000..83fe801a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/NoSuchAlgorithmException.cs
@@ -0,0 +1,19 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security
+{
+ [Obsolete("Never thrown")]
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class NoSuchAlgorithmException : GeneralSecurityException
+ {
+ public NoSuchAlgorithmException() : base() {}
+ public NoSuchAlgorithmException(string message) : base(message) {}
+ public NoSuchAlgorithmException(string message, Exception exception) : base(message, exception) {}
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/NoSuchAlgorithmException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/NoSuchAlgorithmException.cs.meta
new file mode 100644
index 00000000..1f15b373
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/NoSuchAlgorithmException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 38a27f8bfff09634a8b5577f53682a2c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/ParameterUtilities.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/ParameterUtilities.cs
new file mode 100644
index 00000000..e6ad7908
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/ParameterUtilities.cs
@@ -0,0 +1,340 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Kisa;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Misc;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Ntt;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Oiw;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security
+{
+ public sealed class ParameterUtilities
+ {
+ private ParameterUtilities()
+ {
+ }
+
+ private static readonly IDictionary algorithms = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ private static readonly IDictionary basicIVSizes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+
+ static ParameterUtilities()
+ {
+ AddAlgorithm("AES",
+ "AESWRAP");
+ AddAlgorithm("AES128",
+ "2.16.840.1.101.3.4.2",
+ NistObjectIdentifiers.IdAes128Cbc,
+ NistObjectIdentifiers.IdAes128Cfb,
+ NistObjectIdentifiers.IdAes128Ecb,
+ NistObjectIdentifiers.IdAes128Ofb,
+ NistObjectIdentifiers.IdAes128Wrap);
+ AddAlgorithm("AES192",
+ "2.16.840.1.101.3.4.22",
+ NistObjectIdentifiers.IdAes192Cbc,
+ NistObjectIdentifiers.IdAes192Cfb,
+ NistObjectIdentifiers.IdAes192Ecb,
+ NistObjectIdentifiers.IdAes192Ofb,
+ NistObjectIdentifiers.IdAes192Wrap);
+ AddAlgorithm("AES256",
+ "2.16.840.1.101.3.4.42",
+ NistObjectIdentifiers.IdAes256Cbc,
+ NistObjectIdentifiers.IdAes256Cfb,
+ NistObjectIdentifiers.IdAes256Ecb,
+ NistObjectIdentifiers.IdAes256Ofb,
+ NistObjectIdentifiers.IdAes256Wrap);
+ AddAlgorithm("BLOWFISH",
+ "1.3.6.1.4.1.3029.1.2");
+ AddAlgorithm("CAMELLIA",
+ "CAMELLIAWRAP");
+ AddAlgorithm("CAMELLIA128",
+ NttObjectIdentifiers.IdCamellia128Cbc,
+ NttObjectIdentifiers.IdCamellia128Wrap);
+ AddAlgorithm("CAMELLIA192",
+ NttObjectIdentifiers.IdCamellia192Cbc,
+ NttObjectIdentifiers.IdCamellia192Wrap);
+ AddAlgorithm("CAMELLIA256",
+ NttObjectIdentifiers.IdCamellia256Cbc,
+ NttObjectIdentifiers.IdCamellia256Wrap);
+ AddAlgorithm("CAST5",
+ "1.2.840.113533.7.66.10");
+ AddAlgorithm("CAST6");
+ AddAlgorithm("DES",
+ OiwObjectIdentifiers.DesCbc,
+ OiwObjectIdentifiers.DesCfb,
+ OiwObjectIdentifiers.DesEcb,
+ OiwObjectIdentifiers.DesOfb);
+ AddAlgorithm("DESEDE",
+ "DESEDEWRAP",
+ "TDEA",
+ OiwObjectIdentifiers.DesEde,
+ PkcsObjectIdentifiers.IdAlgCms3DesWrap);
+ AddAlgorithm("DESEDE3",
+ PkcsObjectIdentifiers.DesEde3Cbc);
+ AddAlgorithm("GOST28147",
+ "GOST",
+ "GOST-28147",
+ CryptoProObjectIdentifiers.GostR28147Cbc);
+ AddAlgorithm("HC128");
+ AddAlgorithm("HC256");
+ AddAlgorithm("IDEA",
+ "1.3.6.1.4.1.188.7.1.1.2");
+ AddAlgorithm("NOEKEON");
+ AddAlgorithm("RC2",
+ PkcsObjectIdentifiers.RC2Cbc,
+ PkcsObjectIdentifiers.IdAlgCmsRC2Wrap);
+ AddAlgorithm("RC4",
+ "ARC4",
+ "1.2.840.113549.3.4");
+ AddAlgorithm("RC5",
+ "RC5-32");
+ AddAlgorithm("RC5-64");
+ AddAlgorithm("RC6");
+ AddAlgorithm("RIJNDAEL");
+ AddAlgorithm("SALSA20");
+ AddAlgorithm("SEED",
+ KisaObjectIdentifiers.IdNpkiAppCmsSeedWrap,
+ KisaObjectIdentifiers.IdSeedCbc);
+ AddAlgorithm("SERPENT");
+ AddAlgorithm("SKIPJACK");
+ AddAlgorithm("SM4");
+ AddAlgorithm("TEA");
+ AddAlgorithm("THREEFISH-256");
+ AddAlgorithm("THREEFISH-512");
+ AddAlgorithm("THREEFISH-1024");
+ AddAlgorithm("TNEPRES");
+ AddAlgorithm("TWOFISH");
+ AddAlgorithm("VMPC");
+ AddAlgorithm("VMPC-KSA3");
+ AddAlgorithm("XTEA");
+
+ AddBasicIVSizeEntries(8, "BLOWFISH", "DES", "DESEDE", "DESEDE3");
+ AddBasicIVSizeEntries(16, "AES", "AES128", "AES192", "AES256",
+ "CAMELLIA", "CAMELLIA128", "CAMELLIA192", "CAMELLIA256",
+ "NOEKEON", "SEED", "SM4");
+
+ // TODO These algorithms support an IV
+ // but JCE doesn't seem to provide an AlgorithmParametersGenerator for them
+ // "RIJNDAEL", "SKIPJACK", "TWOFISH"
+ }
+
+ private static void AddAlgorithm(
+ string canonicalName,
+ params object[] aliases)
+ {
+ algorithms[canonicalName] = canonicalName;
+
+ foreach (object alias in aliases)
+ {
+ algorithms[alias.ToString()] = canonicalName;
+ }
+ }
+
+ private static void AddBasicIVSizeEntries(int size, params string[] algorithms)
+ {
+ foreach (string algorithm in algorithms)
+ {
+ basicIVSizes.Add(algorithm, size);
+ }
+ }
+
+ public static string GetCanonicalAlgorithmName(
+ string algorithm)
+ {
+ return (string) algorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm)];
+ }
+
+ public static KeyParameter CreateKeyParameter(
+ DerObjectIdentifier algOid,
+ byte[] keyBytes)
+ {
+ return CreateKeyParameter(algOid.Id, keyBytes, 0, keyBytes.Length);
+ }
+
+ public static KeyParameter CreateKeyParameter(
+ string algorithm,
+ byte[] keyBytes)
+ {
+ return CreateKeyParameter(algorithm, keyBytes, 0, keyBytes.Length);
+ }
+
+ public static KeyParameter CreateKeyParameter(
+ DerObjectIdentifier algOid,
+ byte[] keyBytes,
+ int offset,
+ int length)
+ {
+ return CreateKeyParameter(algOid.Id, keyBytes, offset, length);
+ }
+
+ public static KeyParameter CreateKeyParameter(
+ string algorithm,
+ byte[] keyBytes,
+ int offset,
+ int length)
+ {
+ if (algorithm == null)
+ throw new ArgumentNullException("algorithm");
+
+ string canonical = GetCanonicalAlgorithmName(algorithm);
+
+ if (canonical == null)
+ throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised.");
+
+ if (canonical == "DES")
+ return new DesParameters(keyBytes, offset, length);
+
+ if (canonical == "DESEDE" || canonical =="DESEDE3")
+ return new DesEdeParameters(keyBytes, offset, length);
+
+ if (canonical == "RC2")
+ return new RC2Parameters(keyBytes, offset, length);
+
+ return new KeyParameter(keyBytes, offset, length);
+ }
+
+ public static ICipherParameters GetCipherParameters(
+ DerObjectIdentifier algOid,
+ ICipherParameters key,
+ Asn1Object asn1Params)
+ {
+ return GetCipherParameters(algOid.Id, key, asn1Params);
+ }
+
+ public static ICipherParameters GetCipherParameters(
+ string algorithm,
+ ICipherParameters key,
+ Asn1Object asn1Params)
+ {
+ if (algorithm == null)
+ throw new ArgumentNullException("algorithm");
+
+ string canonical = GetCanonicalAlgorithmName(algorithm);
+
+ if (canonical == null)
+ throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised.");
+
+ byte[] iv = null;
+
+ try
+ {
+ // TODO These algorithms support an IV
+ // but JCE doesn't seem to provide an AlgorithmParametersGenerator for them
+ // "RIJNDAEL", "SKIPJACK", "TWOFISH"
+
+ int basicIVKeySize = FindBasicIVSize(canonical);
+ if (basicIVKeySize != -1
+ || canonical == "RIJNDAEL" || canonical == "SKIPJACK" || canonical == "TWOFISH")
+ {
+ iv = ((Asn1OctetString) asn1Params).GetOctets();
+ }
+ else if (canonical == "CAST5")
+ {
+ iv = Cast5CbcParameters.GetInstance(asn1Params).GetIV();
+ }
+ else if (canonical == "IDEA")
+ {
+ iv = IdeaCbcPar.GetInstance(asn1Params).GetIV();
+ }
+ else if (canonical == "RC2")
+ {
+ iv = RC2CbcParameter.GetInstance(asn1Params).GetIV();
+ }
+ }
+ catch (Exception e)
+ {
+ throw new ArgumentException("Could not process ASN.1 parameters", e);
+ }
+
+ if (iv != null)
+ {
+ return new ParametersWithIV(key, iv);
+ }
+
+ throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised.");
+ }
+
+ public static Asn1Encodable GenerateParameters(
+ DerObjectIdentifier algID,
+ SecureRandom random)
+ {
+ return GenerateParameters(algID.Id, random);
+ }
+
+ public static Asn1Encodable GenerateParameters(
+ string algorithm,
+ SecureRandom random)
+ {
+ if (algorithm == null)
+ throw new ArgumentNullException("algorithm");
+
+ string canonical = GetCanonicalAlgorithmName(algorithm);
+
+ if (canonical == null)
+ throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised.");
+
+ // TODO These algorithms support an IV
+ // but JCE doesn't seem to provide an AlgorithmParametersGenerator for them
+ // "RIJNDAEL", "SKIPJACK", "TWOFISH"
+
+ int basicIVKeySize = FindBasicIVSize(canonical);
+ if (basicIVKeySize != -1)
+ return CreateIVOctetString(random, basicIVKeySize);
+
+ if (canonical == "CAST5")
+ return new Cast5CbcParameters(CreateIV(random, 8), 128);
+
+ if (canonical == "IDEA")
+ return new IdeaCbcPar(CreateIV(random, 8));
+
+ if (canonical == "RC2")
+ return new RC2CbcParameter(CreateIV(random, 8));
+
+ throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised.");
+ }
+
+ public static ICipherParameters WithRandom(ICipherParameters cp, SecureRandom random)
+ {
+ if (random != null)
+ {
+ cp = new ParametersWithRandom(cp, random);
+ }
+ return cp;
+ }
+
+ private static Asn1OctetString CreateIVOctetString(
+ SecureRandom random,
+ int ivLength)
+ {
+ return new DerOctetString(CreateIV(random, ivLength));
+ }
+
+ private static byte[] CreateIV(
+ SecureRandom random,
+ int ivLength)
+ {
+ byte[] iv = new byte[ivLength];
+ random.NextBytes(iv);
+ return iv;
+ }
+
+ private static int FindBasicIVSize(
+ string canonicalName)
+ {
+ if (!basicIVSizes.Contains(canonicalName))
+ return -1;
+
+ return (int)basicIVSizes[canonicalName];
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/ParameterUtilities.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/ParameterUtilities.cs.meta
new file mode 100644
index 00000000..85eb922d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/ParameterUtilities.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 9c1511264e2b6be42bd6afc367283966
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/PbeUtilities.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/PbeUtilities.cs
new file mode 100644
index 00000000..c0ed3bef
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/PbeUtilities.cs
@@ -0,0 +1,667 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.BC;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Oiw;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.TeleTrust;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Paddings;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security
+{
+ ///
+ ///
+ ///
+ public sealed class PbeUtilities
+ {
+ private PbeUtilities()
+ {
+ }
+
+ const string Pkcs5S1 = "Pkcs5S1";
+ const string Pkcs5S2 = "Pkcs5S2";
+ const string Pkcs12 = "Pkcs12";
+ const string OpenSsl = "OpenSsl";
+
+ private static readonly IDictionary algorithms = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ private static readonly IDictionary algorithmType = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ private static readonly IDictionary oids = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+
+ static PbeUtilities()
+ {
+ algorithms["PKCS5SCHEME1"] = "Pkcs5scheme1";
+ algorithms["PKCS5SCHEME2"] = "Pkcs5scheme2";
+ algorithms[PkcsObjectIdentifiers.IdPbeS2.Id] = "Pkcs5scheme2";
+// algorithms[PkcsObjectIdentifiers.IdPbkdf2.Id] = "Pkcs5scheme2";
+
+ // FIXME Add support for these? (see Pkcs8Generator)
+// algorithms[PkcsObjectIdentifiers.DesEde3Cbc.Id] = "Pkcs5scheme2";
+// algorithms[NistObjectIdentifiers.IdAes128Cbc.Id] = "Pkcs5scheme2";
+// algorithms[NistObjectIdentifiers.IdAes192Cbc.Id] = "Pkcs5scheme2";
+// algorithms[NistObjectIdentifiers.IdAes256Cbc.Id] = "Pkcs5scheme2";
+
+ algorithms["PBEWITHMD2ANDDES-CBC"] = "PBEwithMD2andDES-CBC";
+ algorithms[PkcsObjectIdentifiers.PbeWithMD2AndDesCbc.Id] = "PBEwithMD2andDES-CBC";
+ algorithms["PBEWITHMD2ANDRC2-CBC"] = "PBEwithMD2andRC2-CBC";
+ algorithms[PkcsObjectIdentifiers.PbeWithMD2AndRC2Cbc.Id] = "PBEwithMD2andRC2-CBC";
+ algorithms["PBEWITHMD5ANDDES-CBC"] = "PBEwithMD5andDES-CBC";
+ algorithms[PkcsObjectIdentifiers.PbeWithMD5AndDesCbc.Id] = "PBEwithMD5andDES-CBC";
+ algorithms["PBEWITHMD5ANDRC2-CBC"] = "PBEwithMD5andRC2-CBC";
+ algorithms[PkcsObjectIdentifiers.PbeWithMD5AndRC2Cbc.Id] = "PBEwithMD5andRC2-CBC";
+ algorithms["PBEWITHSHA1ANDDES"] = "PBEwithSHA-1andDES-CBC";
+ algorithms["PBEWITHSHA-1ANDDES"] = "PBEwithSHA-1andDES-CBC";
+ algorithms["PBEWITHSHA1ANDDES-CBC"] = "PBEwithSHA-1andDES-CBC";
+ algorithms["PBEWITHSHA-1ANDDES-CBC"] = "PBEwithSHA-1andDES-CBC";
+ algorithms[PkcsObjectIdentifiers.PbeWithSha1AndDesCbc.Id] = "PBEwithSHA-1andDES-CBC";
+ algorithms["PBEWITHSHA1ANDRC2"] = "PBEwithSHA-1andRC2-CBC";
+ algorithms["PBEWITHSHA-1ANDRC2"] = "PBEwithSHA-1andRC2-CBC";
+ algorithms["PBEWITHSHA1ANDRC2-CBC"] = "PBEwithSHA-1andRC2-CBC";
+ algorithms["PBEWITHSHA-1ANDRC2-CBC"] = "PBEwithSHA-1andRC2-CBC";
+ algorithms[PkcsObjectIdentifiers.PbeWithSha1AndRC2Cbc.Id] = "PBEwithSHA-1andRC2-CBC";
+ algorithms["PKCS12"] = "Pkcs12";
+ algorithms[BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes128_cbc.Id] = "PBEwithSHA-1and128bitAES-CBC-BC";
+ algorithms[BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes192_cbc.Id] = "PBEwithSHA-1and192bitAES-CBC-BC";
+ algorithms[BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes256_cbc.Id] = "PBEwithSHA-1and256bitAES-CBC-BC";
+ algorithms[BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes128_cbc.Id] = "PBEwithSHA-256and128bitAES-CBC-BC";
+ algorithms[BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes192_cbc.Id] = "PBEwithSHA-256and192bitAES-CBC-BC";
+ algorithms[BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes256_cbc.Id] = "PBEwithSHA-256and256bitAES-CBC-BC";
+ algorithms["PBEWITHSHAAND128BITRC4"] = "PBEwithSHA-1and128bitRC4";
+ algorithms["PBEWITHSHA1AND128BITRC4"] = "PBEwithSHA-1and128bitRC4";
+ algorithms["PBEWITHSHA-1AND128BITRC4"] = "PBEwithSHA-1and128bitRC4";
+ algorithms[PkcsObjectIdentifiers.PbeWithShaAnd128BitRC4.Id] = "PBEwithSHA-1and128bitRC4";
+ algorithms["PBEWITHSHAAND40BITRC4"] = "PBEwithSHA-1and40bitRC4";
+ algorithms["PBEWITHSHA1AND40BITRC4"] = "PBEwithSHA-1and40bitRC4";
+ algorithms["PBEWITHSHA-1AND40BITRC4"] = "PBEwithSHA-1and40bitRC4";
+ algorithms[PkcsObjectIdentifiers.PbeWithShaAnd40BitRC4.Id] = "PBEwithSHA-1and40bitRC4";
+ algorithms["PBEWITHSHAAND3-KEYDESEDE-CBC"] = "PBEwithSHA-1and3-keyDESEDE-CBC";
+ algorithms["PBEWITHSHAAND3-KEYTRIPLEDES-CBC"] = "PBEwithSHA-1and3-keyDESEDE-CBC";
+ algorithms["PBEWITHSHA1AND3-KEYDESEDE-CBC"] = "PBEwithSHA-1and3-keyDESEDE-CBC";
+ algorithms["PBEWITHSHA1AND3-KEYTRIPLEDES-CBC"] = "PBEwithSHA-1and3-keyDESEDE-CBC";
+ algorithms["PBEWITHSHA-1AND3-KEYDESEDE-CBC"] = "PBEwithSHA-1and3-keyDESEDE-CBC";
+ algorithms["PBEWITHSHA-1AND3-KEYTRIPLEDES-CBC"] = "PBEwithSHA-1and3-keyDESEDE-CBC";
+ algorithms[PkcsObjectIdentifiers.PbeWithShaAnd3KeyTripleDesCbc.Id] = "PBEwithSHA-1and3-keyDESEDE-CBC";
+ algorithms["PBEWITHSHAAND2-KEYDESEDE-CBC"] = "PBEwithSHA-1and2-keyDESEDE-CBC";
+ algorithms["PBEWITHSHAAND2-KEYTRIPLEDES-CBC"] = "PBEwithSHA-1and2-keyDESEDE-CBC";
+ algorithms["PBEWITHSHA1AND2-KEYDESEDE-CBC"] = "PBEwithSHA-1and2-keyDESEDE-CBC";
+ algorithms["PBEWITHSHA1AND2-KEYTRIPLEDES-CBC"] = "PBEwithSHA-1and2-keyDESEDE-CBC";
+ algorithms["PBEWITHSHA-1AND2-KEYDESEDE-CBC"] = "PBEwithSHA-1and2-keyDESEDE-CBC";
+ algorithms["PBEWITHSHA-1AND2-KEYTRIPLEDES-CBC"] = "PBEwithSHA-1and2-keyDESEDE-CBC";
+ algorithms[PkcsObjectIdentifiers.PbeWithShaAnd2KeyTripleDesCbc.Id] = "PBEwithSHA-1and2-keyDESEDE-CBC";
+ algorithms["PBEWITHSHAAND128BITRC2-CBC"] = "PBEwithSHA-1and128bitRC2-CBC";
+ algorithms["PBEWITHSHA1AND128BITRC2-CBC"] = "PBEwithSHA-1and128bitRC2-CBC";
+ algorithms["PBEWITHSHA-1AND128BITRC2-CBC"] = "PBEwithSHA-1and128bitRC2-CBC";
+ algorithms[PkcsObjectIdentifiers.PbeWithShaAnd128BitRC2Cbc.Id] = "PBEwithSHA-1and128bitRC2-CBC";
+ algorithms["PBEWITHSHAAND40BITRC2-CBC"] = "PBEwithSHA-1and40bitRC2-CBC";
+ algorithms["PBEWITHSHA1AND40BITRC2-CBC"] = "PBEwithSHA-1and40bitRC2-CBC";
+ algorithms["PBEWITHSHA-1AND40BITRC2-CBC"] = "PBEwithSHA-1and40bitRC2-CBC";
+ algorithms[PkcsObjectIdentifiers.PbewithShaAnd40BitRC2Cbc.Id] = "PBEwithSHA-1and40bitRC2-CBC";
+ algorithms["PBEWITHSHAAND128BITAES-CBC-BC"] = "PBEwithSHA-1and128bitAES-CBC-BC";
+ algorithms["PBEWITHSHA1AND128BITAES-CBC-BC"] = "PBEwithSHA-1and128bitAES-CBC-BC";
+ algorithms["PBEWITHSHA-1AND128BITAES-CBC-BC"] = "PBEwithSHA-1and128bitAES-CBC-BC";
+ algorithms["PBEWITHSHAAND192BITAES-CBC-BC"] = "PBEwithSHA-1and192bitAES-CBC-BC";
+ algorithms["PBEWITHSHA1AND192BITAES-CBC-BC"] = "PBEwithSHA-1and192bitAES-CBC-BC";
+ algorithms["PBEWITHSHA-1AND192BITAES-CBC-BC"] = "PBEwithSHA-1and192bitAES-CBC-BC";
+ algorithms["PBEWITHSHAAND256BITAES-CBC-BC"] = "PBEwithSHA-1and256bitAES-CBC-BC";
+ algorithms["PBEWITHSHA1AND256BITAES-CBC-BC"] = "PBEwithSHA-1and256bitAES-CBC-BC";
+ algorithms["PBEWITHSHA-1AND256BITAES-CBC-BC"] = "PBEwithSHA-1and256bitAES-CBC-BC";
+ algorithms["PBEWITHSHA256AND128BITAES-CBC-BC"] = "PBEwithSHA-256and128bitAES-CBC-BC";
+ algorithms["PBEWITHSHA-256AND128BITAES-CBC-BC"] = "PBEwithSHA-256and128bitAES-CBC-BC";
+ algorithms["PBEWITHSHA256AND192BITAES-CBC-BC"] = "PBEwithSHA-256and192bitAES-CBC-BC";
+ algorithms["PBEWITHSHA-256AND192BITAES-CBC-BC"] = "PBEwithSHA-256and192bitAES-CBC-BC";
+ algorithms["PBEWITHSHA256AND256BITAES-CBC-BC"] = "PBEwithSHA-256and256bitAES-CBC-BC";
+ algorithms["PBEWITHSHA-256AND256BITAES-CBC-BC"] = "PBEwithSHA-256and256bitAES-CBC-BC";
+ algorithms["PBEWITHSHAANDIDEA"] = "PBEwithSHA-1andIDEA-CBC";
+ algorithms["PBEWITHSHAANDIDEA-CBC"] = "PBEwithSHA-1andIDEA-CBC";
+ algorithms["PBEWITHSHAANDTWOFISH"] = "PBEwithSHA-1andTWOFISH-CBC";
+ algorithms["PBEWITHSHAANDTWOFISH-CBC"] = "PBEwithSHA-1andTWOFISH-CBC";
+ algorithms["PBEWITHHMACSHA1"] = "PBEwithHmacSHA-1";
+ algorithms["PBEWITHHMACSHA-1"] = "PBEwithHmacSHA-1";
+ algorithms[OiwObjectIdentifiers.IdSha1.Id] = "PBEwithHmacSHA-1";
+ algorithms["PBEWITHHMACSHA224"] = "PBEwithHmacSHA-224";
+ algorithms["PBEWITHHMACSHA-224"] = "PBEwithHmacSHA-224";
+ algorithms[NistObjectIdentifiers.IdSha224.Id] = "PBEwithHmacSHA-224";
+ algorithms["PBEWITHHMACSHA256"] = "PBEwithHmacSHA-256";
+ algorithms["PBEWITHHMACSHA-256"] = "PBEwithHmacSHA-256";
+ algorithms[NistObjectIdentifiers.IdSha256.Id] = "PBEwithHmacSHA-256";
+ algorithms["PBEWITHHMACRIPEMD128"] = "PBEwithHmacRipeMD128";
+ algorithms[TeleTrusTObjectIdentifiers.RipeMD128.Id] = "PBEwithHmacRipeMD128";
+ algorithms["PBEWITHHMACRIPEMD160"] = "PBEwithHmacRipeMD160";
+ algorithms[TeleTrusTObjectIdentifiers.RipeMD160.Id] = "PBEwithHmacRipeMD160";
+ algorithms["PBEWITHHMACRIPEMD256"] = "PBEwithHmacRipeMD256";
+ algorithms[TeleTrusTObjectIdentifiers.RipeMD256.Id] = "PBEwithHmacRipeMD256";
+ algorithms["PBEWITHHMACTIGER"] = "PBEwithHmacTiger";
+
+ algorithms["PBEWITHMD5AND128BITAES-CBC-OPENSSL"] = "PBEwithMD5and128bitAES-CBC-OpenSSL";
+ algorithms["PBEWITHMD5AND192BITAES-CBC-OPENSSL"] = "PBEwithMD5and192bitAES-CBC-OpenSSL";
+ algorithms["PBEWITHMD5AND256BITAES-CBC-OPENSSL"] = "PBEwithMD5and256bitAES-CBC-OpenSSL";
+
+ algorithmType["Pkcs5scheme1"] = Pkcs5S1;
+ algorithmType["Pkcs5scheme2"] = Pkcs5S2;
+ algorithmType["PBEwithMD2andDES-CBC"] = Pkcs5S1;
+ algorithmType["PBEwithMD2andRC2-CBC"] = Pkcs5S1;
+ algorithmType["PBEwithMD5andDES-CBC"] = Pkcs5S1;
+ algorithmType["PBEwithMD5andRC2-CBC"] = Pkcs5S1;
+ algorithmType["PBEwithSHA-1andDES-CBC"] = Pkcs5S1;
+ algorithmType["PBEwithSHA-1andRC2-CBC"] = Pkcs5S1;
+ algorithmType["Pkcs12"] = Pkcs12;
+ algorithmType["PBEwithSHA-1and128bitRC4"] = Pkcs12;
+ algorithmType["PBEwithSHA-1and40bitRC4"] = Pkcs12;
+ algorithmType["PBEwithSHA-1and3-keyDESEDE-CBC"] = Pkcs12;
+ algorithmType["PBEwithSHA-1and2-keyDESEDE-CBC"] = Pkcs12;
+ algorithmType["PBEwithSHA-1and128bitRC2-CBC"] = Pkcs12;
+ algorithmType["PBEwithSHA-1and40bitRC2-CBC"] = Pkcs12;
+ algorithmType["PBEwithSHA-1and128bitAES-CBC-BC"] = Pkcs12;
+ algorithmType["PBEwithSHA-1and192bitAES-CBC-BC"] = Pkcs12;
+ algorithmType["PBEwithSHA-1and256bitAES-CBC-BC"] = Pkcs12;
+ algorithmType["PBEwithSHA-256and128bitAES-CBC-BC"] = Pkcs12;
+ algorithmType["PBEwithSHA-256and192bitAES-CBC-BC"] = Pkcs12;
+ algorithmType["PBEwithSHA-256and256bitAES-CBC-BC"] = Pkcs12;
+ algorithmType["PBEwithSHA-1andIDEA-CBC"] = Pkcs12;
+ algorithmType["PBEwithSHA-1andTWOFISH-CBC"] = Pkcs12;
+ algorithmType["PBEwithHmacSHA-1"] = Pkcs12;
+ algorithmType["PBEwithHmacSHA-224"] = Pkcs12;
+ algorithmType["PBEwithHmacSHA-256"] = Pkcs12;
+ algorithmType["PBEwithHmacRipeMD128"] = Pkcs12;
+ algorithmType["PBEwithHmacRipeMD160"] = Pkcs12;
+ algorithmType["PBEwithHmacRipeMD256"] = Pkcs12;
+ algorithmType["PBEwithHmacTiger"] = Pkcs12;
+
+ algorithmType["PBEwithMD5and128bitAES-CBC-OpenSSL"] = OpenSsl;
+ algorithmType["PBEwithMD5and192bitAES-CBC-OpenSSL"] = OpenSsl;
+ algorithmType["PBEwithMD5and256bitAES-CBC-OpenSSL"] = OpenSsl;
+
+ oids["PBEwithMD2andDES-CBC"] = PkcsObjectIdentifiers.PbeWithMD2AndDesCbc;
+ oids["PBEwithMD2andRC2-CBC"] = PkcsObjectIdentifiers.PbeWithMD2AndRC2Cbc;
+ oids["PBEwithMD5andDES-CBC"] = PkcsObjectIdentifiers.PbeWithMD5AndDesCbc;
+ oids["PBEwithMD5andRC2-CBC"] = PkcsObjectIdentifiers.PbeWithMD5AndRC2Cbc;
+ oids["PBEwithSHA-1andDES-CBC"] = PkcsObjectIdentifiers.PbeWithSha1AndDesCbc;
+ oids["PBEwithSHA-1andRC2-CBC"] = PkcsObjectIdentifiers.PbeWithSha1AndRC2Cbc;
+ oids["PBEwithSHA-1and128bitRC4"] = PkcsObjectIdentifiers.PbeWithShaAnd128BitRC4;
+ oids["PBEwithSHA-1and40bitRC4"] = PkcsObjectIdentifiers.PbeWithShaAnd40BitRC4;
+ oids["PBEwithSHA-1and3-keyDESEDE-CBC"] = PkcsObjectIdentifiers.PbeWithShaAnd3KeyTripleDesCbc;
+ oids["PBEwithSHA-1and2-keyDESEDE-CBC"] = PkcsObjectIdentifiers.PbeWithShaAnd2KeyTripleDesCbc;
+ oids["PBEwithSHA-1and128bitRC2-CBC"] = PkcsObjectIdentifiers.PbeWithShaAnd128BitRC2Cbc;
+ oids["PBEwithSHA-1and40bitRC2-CBC"] = PkcsObjectIdentifiers.PbewithShaAnd40BitRC2Cbc;
+ oids["PBEwithHmacSHA-1"] = OiwObjectIdentifiers.IdSha1;
+ oids["PBEwithHmacSHA-224"] = NistObjectIdentifiers.IdSha224;
+ oids["PBEwithHmacSHA-256"] = NistObjectIdentifiers.IdSha256;
+ oids["PBEwithHmacRipeMD128"] = TeleTrusTObjectIdentifiers.RipeMD128;
+ oids["PBEwithHmacRipeMD160"] = TeleTrusTObjectIdentifiers.RipeMD160;
+ oids["PBEwithHmacRipeMD256"] = TeleTrusTObjectIdentifiers.RipeMD256;
+ oids["Pkcs5scheme2"] = PkcsObjectIdentifiers.IdPbeS2;
+ }
+
+ static PbeParametersGenerator MakePbeGenerator(
+ string type,
+ IDigest digest,
+ byte[] key,
+ byte[] salt,
+ int iterationCount)
+ {
+ PbeParametersGenerator generator;
+
+ if (type.Equals(Pkcs5S1))
+ {
+ generator = new Pkcs5S1ParametersGenerator(digest);
+ }
+ else if (type.Equals(Pkcs5S2))
+ {
+ generator = new Pkcs5S2ParametersGenerator();
+ }
+ else if (type.Equals(Pkcs12))
+ {
+ generator = new Pkcs12ParametersGenerator(digest);
+ }
+ else if (type.Equals(OpenSsl))
+ {
+ generator = new OpenSslPbeParametersGenerator();
+ }
+ else
+ {
+ throw new ArgumentException("Unknown PBE type: " + type, "type");
+ }
+
+ generator.Init(key, salt, iterationCount);
+ return generator;
+ }
+
+ ///
+ /// Returns a ObjectIdentifier for a give encoding.
+ ///
+ /// A string representation of the encoding.
+ /// A DerObjectIdentifier, null if the Oid is not available.
+ public static DerObjectIdentifier GetObjectIdentifier(
+ string mechanism)
+ {
+ mechanism = (string) algorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(mechanism)];
+ if (mechanism != null)
+ {
+ return (DerObjectIdentifier)oids[mechanism];
+ }
+ return null;
+ }
+
+ public static ICollection Algorithms
+ {
+ get { return oids.Keys; }
+ }
+
+ public static bool IsPkcs12(
+ string algorithm)
+ {
+ string mechanism = (string)algorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm)];
+
+ return mechanism != null && Pkcs12.Equals(algorithmType[mechanism]);
+ }
+
+ public static bool IsPkcs5Scheme1(
+ string algorithm)
+ {
+ string mechanism = (string)algorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm)];
+
+ return mechanism != null && Pkcs5S1.Equals(algorithmType[mechanism]);
+ }
+
+ public static bool IsPkcs5Scheme2(
+ string algorithm)
+ {
+ string mechanism = (string)algorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm)];
+
+ return mechanism != null && Pkcs5S2.Equals(algorithmType[mechanism]);
+ }
+
+ public static bool IsOpenSsl(
+ string algorithm)
+ {
+ string mechanism = (string)algorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm)];
+
+ return mechanism != null && OpenSsl.Equals(algorithmType[mechanism]);
+ }
+
+ public static bool IsPbeAlgorithm(
+ string algorithm)
+ {
+ string mechanism = (string)algorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm)];
+
+ return mechanism != null && algorithmType[mechanism] != null;
+ }
+
+ public static Asn1Encodable GenerateAlgorithmParameters(
+ DerObjectIdentifier algorithmOid,
+ byte[] salt,
+ int iterationCount)
+ {
+ return GenerateAlgorithmParameters(algorithmOid.Id, salt, iterationCount);
+ }
+
+ public static Asn1Encodable GenerateAlgorithmParameters(
+ string algorithm,
+ byte[] salt,
+ int iterationCount)
+ {
+ if (IsPkcs12(algorithm))
+ {
+ return new Pkcs12PbeParams(salt, iterationCount);
+ }
+ else if (IsPkcs5Scheme2(algorithm))
+ {
+ return new Pbkdf2Params(salt, iterationCount);
+ }
+ else
+ {
+ return new PbeParameter(salt, iterationCount);
+ }
+ }
+
+ public static ICipherParameters GenerateCipherParameters(
+ DerObjectIdentifier algorithmOid,
+ char[] password,
+ Asn1Encodable pbeParameters)
+ {
+ return GenerateCipherParameters(algorithmOid.Id, password, false, pbeParameters);
+ }
+
+ public static ICipherParameters GenerateCipherParameters(
+ DerObjectIdentifier algorithmOid,
+ char[] password,
+ bool wrongPkcs12Zero,
+ Asn1Encodable pbeParameters)
+ {
+ return GenerateCipherParameters(algorithmOid.Id, password, wrongPkcs12Zero, pbeParameters);
+ }
+
+ public static ICipherParameters GenerateCipherParameters(
+ AlgorithmIdentifier algID,
+ char[] password)
+ {
+ return GenerateCipherParameters(algID.Algorithm.Id, password, false, algID.Parameters);
+ }
+
+ public static ICipherParameters GenerateCipherParameters(
+ AlgorithmIdentifier algID,
+ char[] password,
+ bool wrongPkcs12Zero)
+ {
+ return GenerateCipherParameters(algID.Algorithm.Id, password, wrongPkcs12Zero, algID.Parameters);
+ }
+
+ public static ICipherParameters GenerateCipherParameters(
+ string algorithm,
+ char[] password,
+ Asn1Encodable pbeParameters)
+ {
+ return GenerateCipherParameters(algorithm, password, false, pbeParameters);
+ }
+
+ public static ICipherParameters GenerateCipherParameters(
+ string algorithm,
+ char[] password,
+ bool wrongPkcs12Zero,
+ Asn1Encodable pbeParameters)
+ {
+ string mechanism = (string)algorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm)];
+
+ byte[] keyBytes = null;
+ byte[] salt = null;
+ int iterationCount = 0;
+
+ if (IsPkcs12(mechanism))
+ {
+ Pkcs12PbeParams pbeParams = Pkcs12PbeParams.GetInstance(pbeParameters);
+ salt = pbeParams.GetIV();
+ iterationCount = pbeParams.Iterations.IntValue;
+ keyBytes = PbeParametersGenerator.Pkcs12PasswordToBytes(password, wrongPkcs12Zero);
+ }
+ else if (IsPkcs5Scheme2(mechanism))
+ {
+ // See below
+ }
+ else
+ {
+ PbeParameter pbeParams = PbeParameter.GetInstance(pbeParameters);
+ salt = pbeParams.GetSalt();
+ iterationCount = pbeParams.IterationCount.IntValue;
+ keyBytes = PbeParametersGenerator.Pkcs5PasswordToBytes(password);
+ }
+
+ ICipherParameters parameters = null;
+
+ if (IsPkcs5Scheme2(mechanism))
+ {
+ PbeS2Parameters s2p = PbeS2Parameters.GetInstance(pbeParameters.ToAsn1Object());
+ AlgorithmIdentifier encScheme = s2p.EncryptionScheme;
+ DerObjectIdentifier encOid = encScheme.Algorithm;
+ Asn1Object encParams = encScheme.Parameters.ToAsn1Object();
+
+ // TODO What about s2p.KeyDerivationFunc.Algorithm?
+ Pbkdf2Params pbeParams = Pbkdf2Params.GetInstance(s2p.KeyDerivationFunc.Parameters.ToAsn1Object());
+
+ byte[] iv;
+ if (encOid.Equals(PkcsObjectIdentifiers.RC2Cbc)) // PKCS5.B.2.3
+ {
+ RC2CbcParameter rc2Params = RC2CbcParameter.GetInstance(encParams);
+ iv = rc2Params.GetIV();
+ }
+ else
+ {
+ iv = Asn1OctetString.GetInstance(encParams).GetOctets();
+ }
+
+ salt = pbeParams.GetSalt();
+ iterationCount = pbeParams.IterationCount.IntValue;
+ keyBytes = PbeParametersGenerator.Pkcs5PasswordToBytes(password);
+
+ int keyLength = pbeParams.KeyLength != null
+ ? pbeParams.KeyLength.IntValue * 8
+ : GeneratorUtilities.GetDefaultKeySize(encOid);
+
+ PbeParametersGenerator gen = MakePbeGenerator(
+ (string)algorithmType[mechanism], null, keyBytes, salt, iterationCount);
+
+ parameters = gen.GenerateDerivedParameters(encOid.Id, keyLength);
+
+ if (iv != null)
+ {
+ // FIXME? OpenSSL weirdness with IV of zeros (for ECB keys?)
+ if (Arrays.AreEqual(iv, new byte[iv.Length]))
+ {
+ //Console.Error.Write("***** IV all 0 (length " + iv.Length + ") *****");
+ }
+ else
+ {
+ parameters = new ParametersWithIV(parameters, iv);
+ }
+ }
+ }
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "PBEwithSHA-1"))
+ {
+ PbeParametersGenerator generator = MakePbeGenerator(
+ (string) algorithmType[mechanism], new Sha1Digest(), keyBytes, salt, iterationCount);
+
+ if (mechanism.Equals("PBEwithSHA-1and128bitAES-CBC-BC"))
+ {
+ parameters = generator.GenerateDerivedParameters("AES", 128, 128);
+ }
+ else if (mechanism.Equals("PBEwithSHA-1and192bitAES-CBC-BC"))
+ {
+ parameters = generator.GenerateDerivedParameters("AES", 192, 128);
+ }
+ else if (mechanism.Equals("PBEwithSHA-1and256bitAES-CBC-BC"))
+ {
+ parameters = generator.GenerateDerivedParameters("AES", 256, 128);
+ }
+ else if (mechanism.Equals("PBEwithSHA-1and128bitRC4"))
+ {
+ parameters = generator.GenerateDerivedParameters("RC4", 128);
+ }
+ else if (mechanism.Equals("PBEwithSHA-1and40bitRC4"))
+ {
+ parameters = generator.GenerateDerivedParameters("RC4", 40);
+ }
+ else if (mechanism.Equals("PBEwithSHA-1and3-keyDESEDE-CBC"))
+ {
+ parameters = generator.GenerateDerivedParameters("DESEDE", 192, 64);
+ }
+ else if (mechanism.Equals("PBEwithSHA-1and2-keyDESEDE-CBC"))
+ {
+ parameters = generator.GenerateDerivedParameters("DESEDE", 128, 64);
+ }
+ else if (mechanism.Equals("PBEwithSHA-1and128bitRC2-CBC"))
+ {
+ parameters = generator.GenerateDerivedParameters("RC2", 128, 64);
+ }
+ else if (mechanism.Equals("PBEwithSHA-1and40bitRC2-CBC"))
+ {
+ parameters = generator.GenerateDerivedParameters("RC2", 40, 64);
+ }
+ else if (mechanism.Equals("PBEwithSHA-1andDES-CBC"))
+ {
+ parameters = generator.GenerateDerivedParameters("DES", 64, 64);
+ }
+ else if (mechanism.Equals("PBEwithSHA-1andRC2-CBC"))
+ {
+ parameters = generator.GenerateDerivedParameters("RC2", 64, 64);
+ }
+ }
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "PBEwithSHA-256"))
+ {
+ PbeParametersGenerator generator = MakePbeGenerator(
+ (string) algorithmType[mechanism], new Sha256Digest(), keyBytes, salt, iterationCount);
+
+ if (mechanism.Equals("PBEwithSHA-256and128bitAES-CBC-BC"))
+ {
+ parameters = generator.GenerateDerivedParameters("AES", 128, 128);
+ }
+ else if (mechanism.Equals("PBEwithSHA-256and192bitAES-CBC-BC"))
+ {
+ parameters = generator.GenerateDerivedParameters("AES", 192, 128);
+ }
+ else if (mechanism.Equals("PBEwithSHA-256and256bitAES-CBC-BC"))
+ {
+ parameters = generator.GenerateDerivedParameters("AES", 256, 128);
+ }
+ }
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "PBEwithMD5"))
+ {
+ PbeParametersGenerator generator = MakePbeGenerator(
+ (string)algorithmType[mechanism], new MD5Digest(), keyBytes, salt, iterationCount);
+
+ if (mechanism.Equals("PBEwithMD5andDES-CBC"))
+ {
+ parameters = generator.GenerateDerivedParameters("DES", 64, 64);
+ }
+ else if (mechanism.Equals("PBEwithMD5andRC2-CBC"))
+ {
+ parameters = generator.GenerateDerivedParameters("RC2", 64, 64);
+ }
+ else if (mechanism.Equals("PBEwithMD5and128bitAES-CBC-OpenSSL"))
+ {
+ parameters = generator.GenerateDerivedParameters("AES", 128, 128);
+ }
+ else if (mechanism.Equals("PBEwithMD5and192bitAES-CBC-OpenSSL"))
+ {
+ parameters = generator.GenerateDerivedParameters("AES", 192, 128);
+ }
+ else if (mechanism.Equals("PBEwithMD5and256bitAES-CBC-OpenSSL"))
+ {
+ parameters = generator.GenerateDerivedParameters("AES", 256, 128);
+ }
+ }
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "PBEwithMD2"))
+ {
+ PbeParametersGenerator generator = MakePbeGenerator(
+ (string)algorithmType[mechanism], new MD2Digest(), keyBytes, salt, iterationCount);
+ if (mechanism.Equals("PBEwithMD2andDES-CBC"))
+ {
+ parameters = generator.GenerateDerivedParameters("DES", 64, 64);
+ }
+ else if (mechanism.Equals("PBEwithMD2andRC2-CBC"))
+ {
+ parameters = generator.GenerateDerivedParameters("RC2", 64, 64);
+ }
+ }
+ else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "PBEwithHmac"))
+ {
+ string digestName = mechanism.Substring("PBEwithHmac".Length);
+ IDigest digest = DigestUtilities.GetDigest(digestName);
+
+ PbeParametersGenerator generator = MakePbeGenerator(
+ (string) algorithmType[mechanism], digest, keyBytes, salt, iterationCount);
+
+ int bitLen = digest.GetDigestSize() * 8;
+ parameters = generator.GenerateDerivedMacParameters(bitLen);
+ }
+
+ Array.Clear(keyBytes, 0, keyBytes.Length);
+
+ return FixDesParity(mechanism, parameters);
+ }
+
+ public static object CreateEngine(
+ DerObjectIdentifier algorithmOid)
+ {
+ return CreateEngine(algorithmOid.Id);
+ }
+
+ public static object CreateEngine(
+ AlgorithmIdentifier algID)
+ {
+ string algorithm = algID.Algorithm.Id;
+
+ if (IsPkcs5Scheme2(algorithm))
+ {
+ PbeS2Parameters s2p = PbeS2Parameters.GetInstance(algID.Parameters.ToAsn1Object());
+ AlgorithmIdentifier encScheme = s2p.EncryptionScheme;
+ return CipherUtilities.GetCipher(encScheme.Algorithm);
+ }
+
+ return CreateEngine(algorithm);
+ }
+
+ public static object CreateEngine(
+ string algorithm)
+ {
+ string mechanism = (string)algorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm)];
+
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "PBEwithHmac"))
+ {
+ string digestName = mechanism.Substring("PBEwithHmac".Length);
+
+ return MacUtilities.GetMac("HMAC/" + digestName);
+ }
+
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "PBEwithMD2")
+ || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "PBEwithMD5")
+ || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "PBEwithSHA-1")
+ || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "PBEwithSHA-256"))
+ {
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "AES-CBC-BC") || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "AES-CBC-OPENSSL"))
+ {
+ return CipherUtilities.GetCipher("AES/CBC");
+ }
+
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "DES-CBC"))
+ {
+ return CipherUtilities.GetCipher("DES/CBC");
+ }
+
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "DESEDE-CBC"))
+ {
+ return CipherUtilities.GetCipher("DESEDE/CBC");
+ }
+
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "RC2-CBC"))
+ {
+ return CipherUtilities.GetCipher("RC2/CBC");
+ }
+
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "RC4"))
+ {
+ return CipherUtilities.GetCipher("RC4");
+ }
+ }
+
+ return null;
+ }
+
+ public static string GetEncodingName(
+ DerObjectIdentifier oid)
+ {
+ return (string) algorithms[oid.Id];
+ }
+
+ private static ICipherParameters FixDesParity(string mechanism, ICipherParameters parameters)
+ {
+ if (!BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "DES-CBC") && !BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "DESEDE-CBC"))
+ {
+ return parameters;
+ }
+
+ if (parameters is ParametersWithIV)
+ {
+ ParametersWithIV ivParams = (ParametersWithIV)parameters;
+ return new ParametersWithIV(FixDesParity(mechanism, ivParams.Parameters), ivParams.GetIV());
+ }
+
+ KeyParameter kParam = (KeyParameter)parameters;
+ byte[] keyBytes = kParam.GetKey();
+ DesParameters.SetOddParity(keyBytes);
+ return new KeyParameter(keyBytes);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/PbeUtilities.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/PbeUtilities.cs.meta
new file mode 100644
index 00000000..bd4dbdac
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/PbeUtilities.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: dfc85a93228ca944eb2c23feecec2821
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/PrivateKeyFactory.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/PrivateKeyFactory.cs
new file mode 100644
index 00000000..f8da7483
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/PrivateKeyFactory.cs
@@ -0,0 +1,259 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.EdEC;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Oiw;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Sec;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security
+{
+ public sealed class PrivateKeyFactory
+ {
+ private PrivateKeyFactory()
+ {
+ }
+
+ public static AsymmetricKeyParameter CreateKey(
+ byte[] privateKeyInfoData)
+ {
+ return CreateKey(
+ PrivateKeyInfo.GetInstance(
+ Asn1Object.FromByteArray(privateKeyInfoData)));
+ }
+
+ public static AsymmetricKeyParameter CreateKey(
+ Stream inStr)
+ {
+ return CreateKey(
+ PrivateKeyInfo.GetInstance(
+ Asn1Object.FromStream(inStr)));
+ }
+
+ public static AsymmetricKeyParameter CreateKey(
+ PrivateKeyInfo keyInfo)
+ {
+ AlgorithmIdentifier algID = keyInfo.PrivateKeyAlgorithm;
+ DerObjectIdentifier algOid = algID.Algorithm;
+
+ // TODO See RSAUtil.isRsaOid in Java build
+ if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption)
+ || algOid.Equals(X509ObjectIdentifiers.IdEARsa)
+ || algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss)
+ || algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep))
+ {
+ RsaPrivateKeyStructure keyStructure = RsaPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey());
+
+ return new RsaPrivateCrtKeyParameters(
+ keyStructure.Modulus,
+ keyStructure.PublicExponent,
+ keyStructure.PrivateExponent,
+ keyStructure.Prime1,
+ keyStructure.Prime2,
+ keyStructure.Exponent1,
+ keyStructure.Exponent2,
+ keyStructure.Coefficient);
+ }
+ // TODO?
+// else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber))
+ else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement))
+ {
+ DHParameter para = new DHParameter(
+ Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
+ DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey();
+
+ BigInteger lVal = para.L;
+ int l = lVal == null ? 0 : lVal.IntValue;
+ DHParameters dhParams = new DHParameters(para.P, para.G, null, l);
+
+ return new DHPrivateKeyParameters(derX.Value, dhParams, algOid);
+ }
+ else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm))
+ {
+ ElGamalParameter para = new ElGamalParameter(
+ Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
+ DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey();
+
+ return new ElGamalPrivateKeyParameters(
+ derX.Value,
+ new ElGamalParameters(para.P, para.G));
+ }
+ else if (algOid.Equals(X9ObjectIdentifiers.IdDsa))
+ {
+ DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey();
+ Asn1Encodable ae = algID.Parameters;
+
+ DsaParameters parameters = null;
+ if (ae != null)
+ {
+ DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object());
+ parameters = new DsaParameters(para.P, para.Q, para.G);
+ }
+
+ return new DsaPrivateKeyParameters(derX.Value, parameters);
+ }
+ else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey))
+ {
+ X962Parameters para = new X962Parameters(algID.Parameters.ToAsn1Object());
+
+ X9ECParameters x9;
+ if (para.IsNamedCurve)
+ {
+ x9 = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters);
+ }
+ else
+ {
+ x9 = new X9ECParameters((Asn1Sequence)para.Parameters);
+ }
+
+ ECPrivateKeyStructure ec = ECPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey());
+ BigInteger d = ec.GetKey();
+
+ if (para.IsNamedCurve)
+ {
+ return new ECPrivateKeyParameters("EC", d, (DerObjectIdentifier)para.Parameters);
+ }
+
+ ECDomainParameters dParams = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed());
+ return new ECPrivateKeyParameters(d, dParams);
+ }
+ else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001))
+ {
+ Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
+ Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
+
+ ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet);
+
+ if (ecP == null)
+ throw new ArgumentException("Unrecognized curve OID for GostR3410x2001 private key");
+
+ Asn1Object privKey = keyInfo.ParsePrivateKey();
+ ECPrivateKeyStructure ec;
+
+ if (privKey is DerInteger)
+ {
+ ec = new ECPrivateKeyStructure(ecP.N.BitLength, ((DerInteger)privKey).PositiveValue);
+ }
+ else
+ {
+ ec = ECPrivateKeyStructure.GetInstance(privKey);
+ }
+
+ return new ECPrivateKeyParameters("ECGOST3410", ec.GetKey(), gostParams.PublicKeyParamSet);
+ }
+ else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94))
+ {
+ Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance(algID.Parameters);
+
+ Asn1Object privKey = keyInfo.ParsePrivateKey();
+ BigInteger x;
+
+ if (privKey is DerInteger)
+ {
+ x = DerInteger.GetInstance(privKey).PositiveValue;
+ }
+ else
+ {
+ x = new BigInteger(1, Arrays.Reverse(Asn1OctetString.GetInstance(privKey).GetOctets()));
+ }
+
+ return new Gost3410PrivateKeyParameters(x, gostParams.PublicKeyParamSet);
+ }
+ else if (algOid.Equals(EdECObjectIdentifiers.id_X25519))
+ {
+ return new X25519PrivateKeyParameters(GetRawKey(keyInfo, X25519PrivateKeyParameters.KeySize), 0);
+ }
+ else if (algOid.Equals(EdECObjectIdentifiers.id_X448))
+ {
+ return new X448PrivateKeyParameters(GetRawKey(keyInfo, X448PrivateKeyParameters.KeySize), 0);
+ }
+ else if (algOid.Equals(EdECObjectIdentifiers.id_Ed25519))
+ {
+ return new Ed25519PrivateKeyParameters(GetRawKey(keyInfo, Ed25519PrivateKeyParameters.KeySize), 0);
+ }
+ else if (algOid.Equals(EdECObjectIdentifiers.id_Ed448))
+ {
+ return new Ed448PrivateKeyParameters(GetRawKey(keyInfo, Ed448PrivateKeyParameters.KeySize), 0);
+ }
+ else
+ {
+ throw new SecurityUtilityException("algorithm identifier in private key not recognised");
+ }
+ }
+
+ private static byte[] GetRawKey(PrivateKeyInfo keyInfo, int expectedSize)
+ {
+ byte[] result = Asn1OctetString.GetInstance(keyInfo.ParsePrivateKey()).GetOctets();
+ if (expectedSize != result.Length)
+ throw new SecurityUtilityException("private key encoding has incorrect length");
+
+ return result;
+ }
+
+ public static AsymmetricKeyParameter DecryptKey(
+ char[] passPhrase,
+ EncryptedPrivateKeyInfo encInfo)
+ {
+ return CreateKey(PrivateKeyInfoFactory.CreatePrivateKeyInfo(passPhrase, encInfo));
+ }
+
+ public static AsymmetricKeyParameter DecryptKey(
+ char[] passPhrase,
+ byte[] encryptedPrivateKeyInfoData)
+ {
+ return DecryptKey(passPhrase, Asn1Object.FromByteArray(encryptedPrivateKeyInfoData));
+ }
+
+ public static AsymmetricKeyParameter DecryptKey(
+ char[] passPhrase,
+ Stream encryptedPrivateKeyInfoStream)
+ {
+ return DecryptKey(passPhrase, Asn1Object.FromStream(encryptedPrivateKeyInfoStream));
+ }
+
+ private static AsymmetricKeyParameter DecryptKey(
+ char[] passPhrase,
+ Asn1Object asn1Object)
+ {
+ return DecryptKey(passPhrase, EncryptedPrivateKeyInfo.GetInstance(asn1Object));
+ }
+
+ public static byte[] EncryptKey(
+ DerObjectIdentifier algorithm,
+ char[] passPhrase,
+ byte[] salt,
+ int iterationCount,
+ AsymmetricKeyParameter key)
+ {
+ return EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
+ algorithm, passPhrase, salt, iterationCount, key).GetEncoded();
+ }
+
+ public static byte[] EncryptKey(
+ string algorithm,
+ char[] passPhrase,
+ byte[] salt,
+ int iterationCount,
+ AsymmetricKeyParameter key)
+ {
+ return EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
+ algorithm, passPhrase, salt, iterationCount, key).GetEncoded();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/PrivateKeyFactory.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/PrivateKeyFactory.cs.meta
new file mode 100644
index 00000000..6c6f2ca9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/PrivateKeyFactory.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c8352ae57e5012f4a946e51451ff22a2
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/PublicKeyFactory.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/PublicKeyFactory.cs
new file mode 100644
index 00000000..e57fa9d9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/PublicKeyFactory.cs
@@ -0,0 +1,287 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.EdEC;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Oiw;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Sec;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security
+{
+ public sealed class PublicKeyFactory
+ {
+ private PublicKeyFactory()
+ {
+ }
+
+ public static AsymmetricKeyParameter CreateKey(
+ byte[] keyInfoData)
+ {
+ return CreateKey(
+ SubjectPublicKeyInfo.GetInstance(
+ Asn1Object.FromByteArray(keyInfoData)));
+ }
+
+ public static AsymmetricKeyParameter CreateKey(
+ Stream inStr)
+ {
+ return CreateKey(
+ SubjectPublicKeyInfo.GetInstance(
+ Asn1Object.FromStream(inStr)));
+ }
+
+ public static AsymmetricKeyParameter CreateKey(
+ SubjectPublicKeyInfo keyInfo)
+ {
+ AlgorithmIdentifier algID = keyInfo.AlgorithmID;
+ DerObjectIdentifier algOid = algID.Algorithm;
+
+ // TODO See RSAUtil.isRsaOid in Java build
+ if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption)
+ || algOid.Equals(X509ObjectIdentifiers.IdEARsa)
+ || algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss)
+ || algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep))
+ {
+ RsaPublicKeyStructure pubKey = RsaPublicKeyStructure.GetInstance(
+ keyInfo.GetPublicKey());
+
+ return new RsaKeyParameters(false, pubKey.Modulus, pubKey.PublicExponent);
+ }
+ else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber))
+ {
+ Asn1Sequence seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object());
+
+ DHPublicKey dhPublicKey = DHPublicKey.GetInstance(keyInfo.GetPublicKey());
+
+ BigInteger y = dhPublicKey.Y.Value;
+
+ if (IsPkcsDHParam(seq))
+ return ReadPkcsDHParam(algOid, y, seq);
+
+ DHDomainParameters dhParams = DHDomainParameters.GetInstance(seq);
+
+ BigInteger p = dhParams.P.Value;
+ BigInteger g = dhParams.G.Value;
+ BigInteger q = dhParams.Q.Value;
+
+ BigInteger j = null;
+ if (dhParams.J != null)
+ {
+ j = dhParams.J.Value;
+ }
+
+ DHValidationParameters validation = null;
+ DHValidationParms dhValidationParms = dhParams.ValidationParms;
+ if (dhValidationParms != null)
+ {
+ byte[] seed = dhValidationParms.Seed.GetBytes();
+ BigInteger pgenCounter = dhValidationParms.PgenCounter.Value;
+
+ // TODO Check pgenCounter size?
+
+ validation = new DHValidationParameters(seed, pgenCounter.IntValue);
+ }
+
+ return new DHPublicKeyParameters(y, new DHParameters(p, g, q, j, validation));
+ }
+ else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement))
+ {
+ Asn1Sequence seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object());
+
+ DerInteger derY = (DerInteger) keyInfo.GetPublicKey();
+
+ return ReadPkcsDHParam(algOid, derY.Value, seq);
+ }
+ else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm))
+ {
+ ElGamalParameter para = new ElGamalParameter(
+ Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
+ DerInteger derY = (DerInteger) keyInfo.GetPublicKey();
+
+ return new ElGamalPublicKeyParameters(
+ derY.Value,
+ new ElGamalParameters(para.P, para.G));
+ }
+ else if (algOid.Equals(X9ObjectIdentifiers.IdDsa)
+ || algOid.Equals(OiwObjectIdentifiers.DsaWithSha1))
+ {
+ DerInteger derY = (DerInteger) keyInfo.GetPublicKey();
+ Asn1Encodable ae = algID.Parameters;
+
+ DsaParameters parameters = null;
+ if (ae != null)
+ {
+ DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object());
+ parameters = new DsaParameters(para.P, para.Q, para.G);
+ }
+
+ return new DsaPublicKeyParameters(derY.Value, parameters);
+ }
+ else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey))
+ {
+ X962Parameters para = new X962Parameters(algID.Parameters.ToAsn1Object());
+
+ X9ECParameters x9;
+ if (para.IsNamedCurve)
+ {
+ x9 = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters);
+ }
+ else
+ {
+ x9 = new X9ECParameters((Asn1Sequence)para.Parameters);
+ }
+
+ Asn1OctetString key = new DerOctetString(keyInfo.PublicKeyData.GetBytes());
+ X9ECPoint derQ = new X9ECPoint(x9.Curve, key);
+ ECPoint q = derQ.Point;
+
+ if (para.IsNamedCurve)
+ {
+ return new ECPublicKeyParameters("EC", q, (DerObjectIdentifier)para.Parameters);
+ }
+
+ ECDomainParameters dParams = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed());
+ return new ECPublicKeyParameters(q, dParams);
+ }
+ else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001))
+ {
+ Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
+ (Asn1Sequence) algID.Parameters);
+
+ Asn1OctetString key;
+ try
+ {
+ key = (Asn1OctetString) keyInfo.GetPublicKey();
+ }
+ catch (IOException)
+ {
+ throw new ArgumentException("invalid info structure in GOST3410 public key");
+ }
+
+ byte[] keyEnc = key.GetOctets();
+ byte[] x = new byte[32];
+ byte[] y = new byte[32];
+
+ for (int i = 0; i != y.Length; i++)
+ {
+ x[i] = keyEnc[32 - 1 - i];
+ }
+
+ for (int i = 0; i != x.Length; i++)
+ {
+ y[i] = keyEnc[64 - 1 - i];
+ }
+
+ ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet);
+
+ if (ecP == null)
+ return null;
+
+ ECPoint q = ecP.Curve.CreatePoint(new BigInteger(1, x), new BigInteger(1, y));
+
+ return new ECPublicKeyParameters("ECGOST3410", q, gostParams.PublicKeyParamSet);
+ }
+ else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94))
+ {
+ Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters(
+ (Asn1Sequence) algID.Parameters);
+
+ DerOctetString derY;
+ try
+ {
+ derY = (DerOctetString) keyInfo.GetPublicKey();
+ }
+ catch (IOException)
+ {
+ throw new ArgumentException("invalid info structure in GOST3410 public key");
+ }
+
+ byte[] keyEnc = derY.GetOctets();
+ byte[] keyBytes = new byte[keyEnc.Length];
+
+ for (int i = 0; i != keyEnc.Length; i++)
+ {
+ keyBytes[i] = keyEnc[keyEnc.Length - 1 - i]; // was little endian
+ }
+
+ BigInteger y = new BigInteger(1, keyBytes);
+
+ return new Gost3410PublicKeyParameters(y, algParams.PublicKeyParamSet);
+ }
+ else if (algOid.Equals(EdECObjectIdentifiers.id_X25519))
+ {
+ return new X25519PublicKeyParameters(GetRawKey(keyInfo, X25519PublicKeyParameters.KeySize), 0);
+ }
+ else if (algOid.Equals(EdECObjectIdentifiers.id_X448))
+ {
+ return new X448PublicKeyParameters(GetRawKey(keyInfo, X448PublicKeyParameters.KeySize), 0);
+ }
+ else if (algOid.Equals(EdECObjectIdentifiers.id_Ed25519))
+ {
+ return new Ed25519PublicKeyParameters(GetRawKey(keyInfo, Ed25519PublicKeyParameters.KeySize), 0);
+ }
+ else if (algOid.Equals(EdECObjectIdentifiers.id_Ed448))
+ {
+ return new Ed448PublicKeyParameters(GetRawKey(keyInfo, Ed448PublicKeyParameters.KeySize), 0);
+ }
+ else
+ {
+ throw new SecurityUtilityException("algorithm identifier in public key not recognised: " + algOid);
+ }
+ }
+
+ private static byte[] GetRawKey(SubjectPublicKeyInfo keyInfo, int expectedSize)
+ {
+ /*
+ * TODO[RFC 8422]
+ * - Require keyInfo.Algorithm.Parameters == null?
+ */
+ byte[] result = keyInfo.PublicKeyData.GetOctets();
+ if (expectedSize != result.Length)
+ throw new SecurityUtilityException("public key encoding has incorrect length");
+
+ return result;
+ }
+
+ private static bool IsPkcsDHParam(Asn1Sequence seq)
+ {
+ if (seq.Count == 2)
+ return true;
+
+ if (seq.Count > 3)
+ return false;
+
+ DerInteger l = DerInteger.GetInstance(seq[2]);
+ DerInteger p = DerInteger.GetInstance(seq[0]);
+
+ return l.Value.CompareTo(BigInteger.ValueOf(p.Value.BitLength)) <= 0;
+ }
+
+ private static DHPublicKeyParameters ReadPkcsDHParam(DerObjectIdentifier algOid,
+ BigInteger y, Asn1Sequence seq)
+ {
+ DHParameter para = new DHParameter(seq);
+
+ BigInteger lVal = para.L;
+ int l = lVal == null ? 0 : lVal.IntValue;
+ DHParameters dhParams = new DHParameters(para.P, para.G, null, l);
+
+ return new DHPublicKeyParameters(y, dhParams, algOid);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/PublicKeyFactory.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/PublicKeyFactory.cs.meta
new file mode 100644
index 00000000..b5b6405a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/PublicKeyFactory.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: bd0cb884524a32c429146ce48d62f30d
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/SecureRandom.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/SecureRandom.cs
new file mode 100644
index 00000000..90590d71
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/SecureRandom.cs
@@ -0,0 +1,266 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Threading;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security
+{
+ public class SecureRandom
+ : Random
+ {
+ private static long counter = Times.NanoTime();
+
+#if NETCF_1_0 || PORTABLE || NETFX_CORE
+ private static object counterLock = new object();
+ private static long NextCounterValue()
+ {
+ lock (counterLock)
+ {
+ return ++counter;
+ }
+ }
+
+ private static readonly SecureRandom[] master = { null };
+ private static SecureRandom Master
+ {
+ get
+ {
+ lock (master)
+ {
+ if (master[0] == null)
+ {
+ SecureRandom sr = master[0] = GetInstance("SHA256PRNG", false);
+
+ // Even though Ticks has at most 8 or 14 bits of entropy, there's no harm in adding it.
+ sr.SetSeed(DateTime.Now.Ticks);
+
+ // 32 will be enough when ThreadedSeedGenerator is fixed. Until then, ThreadedSeedGenerator returns low
+ // entropy, and this is not sufficient to be secure. http://www.bouncycastle.org/csharpdevmailarchive/msg00814.html
+ sr.SetSeed(new ThreadedSeedGenerator().GenerateSeed(32, true));
+ }
+
+ return master[0];
+ }
+ }
+ }
+#else
+ private static long NextCounterValue()
+ {
+ return Interlocked.Increment(ref counter);
+ }
+
+ private static readonly SecureRandom master = new SecureRandom(new CryptoApiRandomGenerator());
+ private static SecureRandom Master
+ {
+ get { return master; }
+ }
+#endif
+
+ private static DigestRandomGenerator CreatePrng(string digestName, bool autoSeed)
+ {
+ IDigest digest = DigestUtilities.GetDigest(digestName);
+ if (digest == null)
+ return null;
+ DigestRandomGenerator prng = new DigestRandomGenerator(digest);
+ if (autoSeed)
+ {
+ prng.AddSeedMaterial(NextCounterValue());
+ prng.AddSeedMaterial(GetNextBytes(Master, digest.GetDigestSize()));
+ }
+ return prng;
+ }
+
+ public static byte[] GetNextBytes(SecureRandom secureRandom, int length)
+ {
+ byte[] result = new byte[length];
+ secureRandom.NextBytes(result);
+ return result;
+ }
+
+ ///
+ /// Create and auto-seed an instance based on the given algorithm.
+ ///
+ /// Equivalent to GetInstance(algorithm, true)
+ /// e.g. "SHA256PRNG"
+ public static SecureRandom GetInstance(string algorithm)
+ {
+ return GetInstance(algorithm, true);
+ }
+
+ ///
+ /// Create an instance based on the given algorithm, with optional auto-seeding
+ ///
+ /// e.g. "SHA256PRNG"
+ /// If true, the instance will be auto-seeded.
+ public static SecureRandom GetInstance(string algorithm, bool autoSeed)
+ {
+ string upper = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm);
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(upper, "PRNG"))
+ {
+ string digestName = upper.Substring(0, upper.Length - "PRNG".Length);
+ DigestRandomGenerator prng = CreatePrng(digestName, autoSeed);
+ if (prng != null)
+ {
+ return new SecureRandom(prng);
+ }
+ }
+
+ throw new ArgumentException("Unrecognised PRNG algorithm: " + algorithm, "algorithm");
+ }
+
+ [Obsolete("Call GenerateSeed() on a SecureRandom instance instead")]
+ public static byte[] GetSeed(int length)
+ {
+ return GetNextBytes(Master, length);
+ }
+
+ protected readonly IRandomGenerator generator;
+
+ public SecureRandom()
+ : this(CreatePrng("SHA256", true))
+ {
+ }
+
+ ///
+ /// To replicate existing predictable output, replace with GetInstance("SHA1PRNG", false), followed by SetSeed(seed)
+ ///
+ [Obsolete("Use GetInstance/SetSeed instead")]
+ public SecureRandom(byte[] seed)
+ : this(CreatePrng("SHA1", false))
+ {
+ SetSeed(seed);
+ }
+
+ /// Use the specified instance of IRandomGenerator as random source.
+ ///
+ /// This constructor performs no seeding of either the IRandomGenerator or the
+ /// constructed SecureRandom. It is the responsibility of the client to provide
+ /// proper seed material as necessary/appropriate for the given IRandomGenerator
+ /// implementation.
+ ///
+ /// The source to generate all random bytes from.
+ public SecureRandom(IRandomGenerator generator)
+ : base(0)
+ {
+ this.generator = generator;
+ }
+
+ public virtual byte[] GenerateSeed(int length)
+ {
+ return GetNextBytes(Master, length);
+ }
+
+ public virtual void SetSeed(byte[] seed)
+ {
+ generator.AddSeedMaterial(seed);
+ }
+
+ public virtual void SetSeed(long seed)
+ {
+ generator.AddSeedMaterial(seed);
+ }
+
+ public override int Next()
+ {
+ return NextInt() & int.MaxValue;
+ }
+
+ public override int Next(int maxValue)
+ {
+
+ if (maxValue < 2)
+ {
+ if (maxValue < 0)
+ throw new ArgumentOutOfRangeException("maxValue", "cannot be negative");
+
+ return 0;
+ }
+
+ int bits;
+
+ // Test whether maxValue is a power of 2
+ if ((maxValue & (maxValue - 1)) == 0)
+ {
+ bits = NextInt() & int.MaxValue;
+ return (int)(((long)bits * maxValue) >> 31);
+ }
+
+ int result;
+ do
+ {
+ bits = NextInt() & int.MaxValue;
+ result = bits % maxValue;
+ }
+ while (bits - result + (maxValue - 1) < 0); // Ignore results near overflow
+
+ return result;
+ }
+
+ public override int Next(int minValue, int maxValue)
+ {
+ if (maxValue <= minValue)
+ {
+ if (maxValue == minValue)
+ return minValue;
+
+ throw new ArgumentException("maxValue cannot be less than minValue");
+ }
+
+ int diff = maxValue - minValue;
+ if (diff > 0)
+ return minValue + Next(diff);
+
+ for (;;)
+ {
+ int i = NextInt();
+
+ if (i >= minValue && i < maxValue)
+ return i;
+ }
+ }
+
+ public override void NextBytes(byte[] buf)
+ {
+ generator.NextBytes(buf);
+ }
+
+ public virtual void NextBytes(byte[] buf, int off, int len)
+ {
+ generator.NextBytes(buf, off, len);
+ }
+
+ private static readonly double DoubleScale = System.Math.Pow(2.0, 64.0);
+
+ public override double NextDouble()
+ {
+ return Convert.ToDouble((ulong) NextLong()) / DoubleScale;
+ }
+
+ public virtual int NextInt()
+ {
+ byte[] bytes = new byte[4];
+ NextBytes(bytes);
+
+ uint result = bytes[0];
+ result <<= 8;
+ result |= bytes[1];
+ result <<= 8;
+ result |= bytes[2];
+ result <<= 8;
+ result |= bytes[3];
+ return (int)result;
+ }
+
+ public virtual long NextLong()
+ {
+ return ((long)(uint) NextInt() << 32) | (long)(uint) NextInt();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/SecureRandom.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/SecureRandom.cs.meta
new file mode 100644
index 00000000..13d3f23c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/SecureRandom.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: dad6d1b180992fa4bbefb141195487f5
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/SecurityUtilityException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/SecurityUtilityException.cs
new file mode 100644
index 00000000..d5a19d8a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/SecurityUtilityException.cs
@@ -0,0 +1,40 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security
+{
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class SecurityUtilityException
+ : Exception
+ {
+ /**
+ * base constructor.
+ */
+ public SecurityUtilityException()
+ {
+ }
+
+ /**
+ * create a SecurityUtilityException with the given message.
+ *
+ * @param message the message to be carried with the exception.
+ */
+ public SecurityUtilityException(
+ string message)
+ : base(message)
+ {
+ }
+
+ public SecurityUtilityException(
+ string message,
+ Exception exception)
+ : base(message, exception)
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/SecurityUtilityException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/SecurityUtilityException.cs.meta
new file mode 100644
index 00000000..8199f5d3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/SecurityUtilityException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 776c8efaf8c3b3843aa42677ef63afd3
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/SignatureException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/SignatureException.cs
new file mode 100644
index 00000000..12849655
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/SignatureException.cs
@@ -0,0 +1,18 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security
+{
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class SignatureException : GeneralSecurityException
+ {
+ public SignatureException() : base() { }
+ public SignatureException(string message) : base(message) { }
+ public SignatureException(string message, Exception exception) : base(message, exception) { }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/SignatureException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/SignatureException.cs.meta
new file mode 100644
index 00000000..4fc1b8ef
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/SignatureException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 464c53a8485e7d44e828bede8f580c3b
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/SignerUtilities.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/SignerUtilities.cs
new file mode 100644
index 00000000..f64e3d42
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/SignerUtilities.cs
@@ -0,0 +1,640 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Bsi;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Eac;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.EdEC;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Oiw;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.TeleTrust;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security
+{
+ ///
+ /// Signer Utility class contains methods that can not be specifically grouped into other classes.
+ ///
+ public sealed class SignerUtilities
+ {
+ private SignerUtilities()
+ {
+ }
+
+ internal static readonly IDictionary algorithms = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ internal static readonly IDictionary oids = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+
+ static SignerUtilities()
+ {
+ algorithms["MD2WITHRSA"] = "MD2withRSA";
+ algorithms["MD2WITHRSAENCRYPTION"] = "MD2withRSA";
+ algorithms[PkcsObjectIdentifiers.MD2WithRsaEncryption.Id] = "MD2withRSA";
+
+ algorithms["MD4WITHRSA"] = "MD4withRSA";
+ algorithms["MD4WITHRSAENCRYPTION"] = "MD4withRSA";
+ algorithms[PkcsObjectIdentifiers.MD4WithRsaEncryption.Id] = "MD4withRSA";
+ algorithms[OiwObjectIdentifiers.MD4WithRsa.Id] = "MD4withRSA";
+ algorithms[OiwObjectIdentifiers.MD4WithRsaEncryption.Id] = "MD4withRSA";
+
+ algorithms["MD5WITHRSA"] = "MD5withRSA";
+ algorithms["MD5WITHRSAENCRYPTION"] = "MD5withRSA";
+ algorithms[PkcsObjectIdentifiers.MD5WithRsaEncryption.Id] = "MD5withRSA";
+ algorithms[OiwObjectIdentifiers.MD5WithRsa.Id] = "MD5withRSA";
+
+ algorithms["SHA1WITHRSA"] = "SHA-1withRSA";
+ algorithms["SHA1WITHRSAENCRYPTION"] = "SHA-1withRSA";
+ algorithms["SHA-1WITHRSA"] = "SHA-1withRSA";
+ algorithms[PkcsObjectIdentifiers.Sha1WithRsaEncryption.Id] = "SHA-1withRSA";
+ algorithms[OiwObjectIdentifiers.Sha1WithRsa.Id] = "SHA-1withRSA";
+
+ algorithms["SHA224WITHRSA"] = "SHA-224withRSA";
+ algorithms["SHA224WITHRSAENCRYPTION"] = "SHA-224withRSA";
+ algorithms[PkcsObjectIdentifiers.Sha224WithRsaEncryption.Id] = "SHA-224withRSA";
+ algorithms["SHA-224WITHRSA"] = "SHA-224withRSA";
+
+ algorithms["SHA256WITHRSA"] = "SHA-256withRSA";
+ algorithms["SHA256WITHRSAENCRYPTION"] = "SHA-256withRSA";
+ algorithms[PkcsObjectIdentifiers.Sha256WithRsaEncryption.Id] = "SHA-256withRSA";
+ algorithms["SHA-256WITHRSA"] = "SHA-256withRSA";
+
+ algorithms["SHA384WITHRSA"] = "SHA-384withRSA";
+ algorithms["SHA384WITHRSAENCRYPTION"] = "SHA-384withRSA";
+ algorithms[PkcsObjectIdentifiers.Sha384WithRsaEncryption.Id] = "SHA-384withRSA";
+ algorithms["SHA-384WITHRSA"] = "SHA-384withRSA";
+
+ algorithms["SHA512WITHRSA"] = "SHA-512withRSA";
+ algorithms["SHA512WITHRSAENCRYPTION"] = "SHA-512withRSA";
+ algorithms[PkcsObjectIdentifiers.Sha512WithRsaEncryption.Id] = "SHA-512withRSA";
+ algorithms["SHA-512WITHRSA"] = "SHA-512withRSA";
+
+ algorithms["PSSWITHRSA"] = "PSSwithRSA";
+ algorithms["RSASSA-PSS"] = "PSSwithRSA";
+ algorithms[PkcsObjectIdentifiers.IdRsassaPss.Id] = "PSSwithRSA";
+ algorithms["RSAPSS"] = "PSSwithRSA";
+
+ algorithms["SHA1WITHRSAANDMGF1"] = "SHA-1withRSAandMGF1";
+ algorithms["SHA-1WITHRSAANDMGF1"] = "SHA-1withRSAandMGF1";
+ algorithms["SHA1WITHRSA/PSS"] = "SHA-1withRSAandMGF1";
+ algorithms["SHA-1WITHRSA/PSS"] = "SHA-1withRSAandMGF1";
+
+ algorithms["SHA224WITHRSAANDMGF1"] = "SHA-224withRSAandMGF1";
+ algorithms["SHA-224WITHRSAANDMGF1"] = "SHA-224withRSAandMGF1";
+ algorithms["SHA224WITHRSA/PSS"] = "SHA-224withRSAandMGF1";
+ algorithms["SHA-224WITHRSA/PSS"] = "SHA-224withRSAandMGF1";
+
+ algorithms["SHA256WITHRSAANDMGF1"] = "SHA-256withRSAandMGF1";
+ algorithms["SHA-256WITHRSAANDMGF1"] = "SHA-256withRSAandMGF1";
+ algorithms["SHA256WITHRSA/PSS"] = "SHA-256withRSAandMGF1";
+ algorithms["SHA-256WITHRSA/PSS"] = "SHA-256withRSAandMGF1";
+
+ algorithms["SHA384WITHRSAANDMGF1"] = "SHA-384withRSAandMGF1";
+ algorithms["SHA-384WITHRSAANDMGF1"] = "SHA-384withRSAandMGF1";
+ algorithms["SHA384WITHRSA/PSS"] = "SHA-384withRSAandMGF1";
+ algorithms["SHA-384WITHRSA/PSS"] = "SHA-384withRSAandMGF1";
+
+ algorithms["SHA512WITHRSAANDMGF1"] = "SHA-512withRSAandMGF1";
+ algorithms["SHA-512WITHRSAANDMGF1"] = "SHA-512withRSAandMGF1";
+ algorithms["SHA512WITHRSA/PSS"] = "SHA-512withRSAandMGF1";
+ algorithms["SHA-512WITHRSA/PSS"] = "SHA-512withRSAandMGF1";
+
+ algorithms["RIPEMD128WITHRSA"] = "RIPEMD128withRSA";
+ algorithms["RIPEMD128WITHRSAENCRYPTION"] = "RIPEMD128withRSA";
+ algorithms[TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128.Id] = "RIPEMD128withRSA";
+
+ algorithms["RIPEMD160WITHRSA"] = "RIPEMD160withRSA";
+ algorithms["RIPEMD160WITHRSAENCRYPTION"] = "RIPEMD160withRSA";
+ algorithms[TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160.Id] = "RIPEMD160withRSA";
+
+ algorithms["RIPEMD256WITHRSA"] = "RIPEMD256withRSA";
+ algorithms["RIPEMD256WITHRSAENCRYPTION"] = "RIPEMD256withRSA";
+ algorithms[TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256.Id] = "RIPEMD256withRSA";
+
+ algorithms["NONEWITHRSA"] = "RSA";
+ algorithms["RSAWITHNONE"] = "RSA";
+ algorithms["RAWRSA"] = "RSA";
+
+ algorithms["RAWRSAPSS"] = "RAWRSASSA-PSS";
+ algorithms["NONEWITHRSAPSS"] = "RAWRSASSA-PSS";
+ algorithms["NONEWITHRSASSA-PSS"] = "RAWRSASSA-PSS";
+
+ algorithms["NONEWITHDSA"] = "NONEwithDSA";
+ algorithms["DSAWITHNONE"] = "NONEwithDSA";
+ algorithms["RAWDSA"] = "NONEwithDSA";
+
+ algorithms["DSA"] = "SHA-1withDSA";
+ algorithms["DSAWITHSHA1"] = "SHA-1withDSA";
+ algorithms["DSAWITHSHA-1"] = "SHA-1withDSA";
+ algorithms["SHA/DSA"] = "SHA-1withDSA";
+ algorithms["SHA1/DSA"] = "SHA-1withDSA";
+ algorithms["SHA-1/DSA"] = "SHA-1withDSA";
+ algorithms["SHA1WITHDSA"] = "SHA-1withDSA";
+ algorithms["SHA-1WITHDSA"] = "SHA-1withDSA";
+ algorithms[X9ObjectIdentifiers.IdDsaWithSha1.Id] = "SHA-1withDSA";
+ algorithms[OiwObjectIdentifiers.DsaWithSha1.Id] = "SHA-1withDSA";
+
+ algorithms["DSAWITHSHA224"] = "SHA-224withDSA";
+ algorithms["DSAWITHSHA-224"] = "SHA-224withDSA";
+ algorithms["SHA224/DSA"] = "SHA-224withDSA";
+ algorithms["SHA-224/DSA"] = "SHA-224withDSA";
+ algorithms["SHA224WITHDSA"] = "SHA-224withDSA";
+ algorithms["SHA-224WITHDSA"] = "SHA-224withDSA";
+ algorithms[NistObjectIdentifiers.DsaWithSha224.Id] = "SHA-224withDSA";
+
+ algorithms["DSAWITHSHA256"] = "SHA-256withDSA";
+ algorithms["DSAWITHSHA-256"] = "SHA-256withDSA";
+ algorithms["SHA256/DSA"] = "SHA-256withDSA";
+ algorithms["SHA-256/DSA"] = "SHA-256withDSA";
+ algorithms["SHA256WITHDSA"] = "SHA-256withDSA";
+ algorithms["SHA-256WITHDSA"] = "SHA-256withDSA";
+ algorithms[NistObjectIdentifiers.DsaWithSha256.Id] = "SHA-256withDSA";
+
+ algorithms["DSAWITHSHA384"] = "SHA-384withDSA";
+ algorithms["DSAWITHSHA-384"] = "SHA-384withDSA";
+ algorithms["SHA384/DSA"] = "SHA-384withDSA";
+ algorithms["SHA-384/DSA"] = "SHA-384withDSA";
+ algorithms["SHA384WITHDSA"] = "SHA-384withDSA";
+ algorithms["SHA-384WITHDSA"] = "SHA-384withDSA";
+ algorithms[NistObjectIdentifiers.DsaWithSha384.Id] = "SHA-384withDSA";
+
+ algorithms["DSAWITHSHA512"] = "SHA-512withDSA";
+ algorithms["DSAWITHSHA-512"] = "SHA-512withDSA";
+ algorithms["SHA512/DSA"] = "SHA-512withDSA";
+ algorithms["SHA-512/DSA"] = "SHA-512withDSA";
+ algorithms["SHA512WITHDSA"] = "SHA-512withDSA";
+ algorithms["SHA-512WITHDSA"] = "SHA-512withDSA";
+ algorithms[NistObjectIdentifiers.DsaWithSha512.Id] = "SHA-512withDSA";
+
+ algorithms["NONEWITHECDSA"] = "NONEwithECDSA";
+ algorithms["ECDSAWITHNONE"] = "NONEwithECDSA";
+
+ algorithms["ECDSA"] = "SHA-1withECDSA";
+ algorithms["SHA1/ECDSA"] = "SHA-1withECDSA";
+ algorithms["SHA-1/ECDSA"] = "SHA-1withECDSA";
+ algorithms["ECDSAWITHSHA1"] = "SHA-1withECDSA";
+ algorithms["ECDSAWITHSHA-1"] = "SHA-1withECDSA";
+ algorithms["SHA1WITHECDSA"] = "SHA-1withECDSA";
+ algorithms["SHA-1WITHECDSA"] = "SHA-1withECDSA";
+ algorithms[X9ObjectIdentifiers.ECDsaWithSha1.Id] = "SHA-1withECDSA";
+ algorithms[TeleTrusTObjectIdentifiers.ECSignWithSha1.Id] = "SHA-1withECDSA";
+
+ algorithms["SHA224/ECDSA"] = "SHA-224withECDSA";
+ algorithms["SHA-224/ECDSA"] = "SHA-224withECDSA";
+ algorithms["ECDSAWITHSHA224"] = "SHA-224withECDSA";
+ algorithms["ECDSAWITHSHA-224"] = "SHA-224withECDSA";
+ algorithms["SHA224WITHECDSA"] = "SHA-224withECDSA";
+ algorithms["SHA-224WITHECDSA"] = "SHA-224withECDSA";
+ algorithms[X9ObjectIdentifiers.ECDsaWithSha224.Id] = "SHA-224withECDSA";
+
+ algorithms["SHA256/ECDSA"] = "SHA-256withECDSA";
+ algorithms["SHA-256/ECDSA"] = "SHA-256withECDSA";
+ algorithms["ECDSAWITHSHA256"] = "SHA-256withECDSA";
+ algorithms["ECDSAWITHSHA-256"] = "SHA-256withECDSA";
+ algorithms["SHA256WITHECDSA"] = "SHA-256withECDSA";
+ algorithms["SHA-256WITHECDSA"] = "SHA-256withECDSA";
+ algorithms[X9ObjectIdentifiers.ECDsaWithSha256.Id] = "SHA-256withECDSA";
+
+ algorithms["SHA384/ECDSA"] = "SHA-384withECDSA";
+ algorithms["SHA-384/ECDSA"] = "SHA-384withECDSA";
+ algorithms["ECDSAWITHSHA384"] = "SHA-384withECDSA";
+ algorithms["ECDSAWITHSHA-384"] = "SHA-384withECDSA";
+ algorithms["SHA384WITHECDSA"] = "SHA-384withECDSA";
+ algorithms["SHA-384WITHECDSA"] = "SHA-384withECDSA";
+ algorithms[X9ObjectIdentifiers.ECDsaWithSha384.Id] = "SHA-384withECDSA";
+
+ algorithms["SHA512/ECDSA"] = "SHA-512withECDSA";
+ algorithms["SHA-512/ECDSA"] = "SHA-512withECDSA";
+ algorithms["ECDSAWITHSHA512"] = "SHA-512withECDSA";
+ algorithms["ECDSAWITHSHA-512"] = "SHA-512withECDSA";
+ algorithms["SHA512WITHECDSA"] = "SHA-512withECDSA";
+ algorithms["SHA-512WITHECDSA"] = "SHA-512withECDSA";
+ algorithms[X9ObjectIdentifiers.ECDsaWithSha512.Id] = "SHA-512withECDSA";
+
+ algorithms["RIPEMD160/ECDSA"] = "RIPEMD160withECDSA";
+ algorithms["ECDSAWITHRIPEMD160"] = "RIPEMD160withECDSA";
+ algorithms["RIPEMD160WITHECDSA"] = "RIPEMD160withECDSA";
+ algorithms[TeleTrusTObjectIdentifiers.ECSignWithRipeMD160.Id] = "RIPEMD160withECDSA";
+
+ algorithms["NONEWITHCVC-ECDSA"] = "NONEwithCVC-ECDSA";
+ algorithms["CVC-ECDSAWITHNONE"] = "NONEwithCVC-ECDSA";
+
+ algorithms["SHA1/CVC-ECDSA"] = "SHA-1withCVC-ECDSA";
+ algorithms["SHA-1/CVC-ECDSA"] = "SHA-1withCVC-ECDSA";
+ algorithms["CVC-ECDSAWITHSHA1"] = "SHA-1withCVC-ECDSA";
+ algorithms["CVC-ECDSAWITHSHA-1"] = "SHA-1withCVC-ECDSA";
+ algorithms["SHA1WITHCVC-ECDSA"] = "SHA-1withCVC-ECDSA";
+ algorithms["SHA-1WITHCVC-ECDSA"] = "SHA-1withCVC-ECDSA";
+ algorithms[EacObjectIdentifiers.id_TA_ECDSA_SHA_1.Id] = "SHA-1withCVC-ECDSA";
+
+ algorithms["SHA224/CVC-ECDSA"] = "SHA-224withCVC-ECDSA";
+ algorithms["SHA-224/CVC-ECDSA"] = "SHA-224withCVC-ECDSA";
+ algorithms["CVC-ECDSAWITHSHA224"] = "SHA-224withCVC-ECDSA";
+ algorithms["CVC-ECDSAWITHSHA-224"] = "SHA-224withCVC-ECDSA";
+ algorithms["SHA224WITHCVC-ECDSA"] = "SHA-224withCVC-ECDSA";
+ algorithms["SHA-224WITHCVC-ECDSA"] = "SHA-224withCVC-ECDSA";
+ algorithms[EacObjectIdentifiers.id_TA_ECDSA_SHA_224.Id] = "SHA-224withCVC-ECDSA";
+
+ algorithms["SHA256/CVC-ECDSA"] = "SHA-256withCVC-ECDSA";
+ algorithms["SHA-256/CVC-ECDSA"] = "SHA-256withCVC-ECDSA";
+ algorithms["CVC-ECDSAWITHSHA256"] = "SHA-256withCVC-ECDSA";
+ algorithms["CVC-ECDSAWITHSHA-256"] = "SHA-256withCVC-ECDSA";
+ algorithms["SHA256WITHCVC-ECDSA"] = "SHA-256withCVC-ECDSA";
+ algorithms["SHA-256WITHCVC-ECDSA"] = "SHA-256withCVC-ECDSA";
+ algorithms[EacObjectIdentifiers.id_TA_ECDSA_SHA_256.Id] = "SHA-256withCVC-ECDSA";
+
+ algorithms["SHA384/CVC-ECDSA"] = "SHA-384withCVC-ECDSA";
+ algorithms["SHA-384/CVC-ECDSA"] = "SHA-384withCVC-ECDSA";
+ algorithms["CVC-ECDSAWITHSHA384"] = "SHA-384withCVC-ECDSA";
+ algorithms["CVC-ECDSAWITHSHA-384"] = "SHA-384withCVC-ECDSA";
+ algorithms["SHA384WITHCVC-ECDSA"] = "SHA-384withCVC-ECDSA";
+ algorithms["SHA-384WITHCVC-ECDSA"] = "SHA-384withCVC-ECDSA";
+ algorithms[EacObjectIdentifiers.id_TA_ECDSA_SHA_384.Id] = "SHA-384withCVC-ECDSA";
+
+ algorithms["SHA512/CVC-ECDSA"] = "SHA-512withCVC-ECDSA";
+ algorithms["SHA-512/CVC-ECDSA"] = "SHA-512withCVC-ECDSA";
+ algorithms["CVC-ECDSAWITHSHA512"] = "SHA-512withCVC-ECDSA";
+ algorithms["CVC-ECDSAWITHSHA-512"] = "SHA-512withCVC-ECDSA";
+ algorithms["SHA512WITHCVC-ECDSA"] = "SHA-512withCVC-ECDSA";
+ algorithms["SHA-512WITHCVC-ECDSA"] = "SHA-512withCVC-ECDSA";
+ algorithms[EacObjectIdentifiers.id_TA_ECDSA_SHA_512.Id] = "SHA-512withCVC-ECDSA";
+
+ algorithms["NONEWITHPLAIN-ECDSA"] = "NONEwithPLAIN-ECDSA";
+ algorithms["PLAIN-ECDSAWITHNONE"] = "NONEwithPLAIN-ECDSA";
+
+ algorithms["SHA1/PLAIN-ECDSA"] = "SHA-1withPLAIN-ECDSA";
+ algorithms["SHA-1/PLAIN-ECDSA"] = "SHA-1withPLAIN-ECDSA";
+ algorithms["PLAIN-ECDSAWITHSHA1"] = "SHA-1withPLAIN-ECDSA";
+ algorithms["PLAIN-ECDSAWITHSHA-1"] = "SHA-1withPLAIN-ECDSA";
+ algorithms["SHA1WITHPLAIN-ECDSA"] = "SHA-1withPLAIN-ECDSA";
+ algorithms["SHA-1WITHPLAIN-ECDSA"] = "SHA-1withPLAIN-ECDSA";
+ algorithms[BsiObjectIdentifiers.ecdsa_plain_SHA1.Id] = "SHA-1withPLAIN-ECDSA";
+
+ algorithms["SHA224/PLAIN-ECDSA"] = "SHA-224withPLAIN-ECDSA";
+ algorithms["SHA-224/PLAIN-ECDSA"] = "SHA-224withPLAIN-ECDSA";
+ algorithms["PLAIN-ECDSAWITHSHA224"] = "SHA-224withPLAIN-ECDSA";
+ algorithms["PLAIN-ECDSAWITHSHA-224"] = "SHA-224withPLAIN-ECDSA";
+ algorithms["SHA224WITHPLAIN-ECDSA"] = "SHA-224withPLAIN-ECDSA";
+ algorithms["SHA-224WITHPLAIN-ECDSA"] = "SHA-224withPLAIN-ECDSA";
+ algorithms[BsiObjectIdentifiers.ecdsa_plain_SHA224.Id] = "SHA-224withPLAIN-ECDSA";
+
+ algorithms["SHA256/PLAIN-ECDSA"] = "SHA-256withPLAIN-ECDSA";
+ algorithms["SHA-256/PLAIN-ECDSA"] = "SHA-256withPLAIN-ECDSA";
+ algorithms["PLAIN-ECDSAWITHSHA256"] = "SHA-256withPLAIN-ECDSA";
+ algorithms["PLAIN-ECDSAWITHSHA-256"] = "SHA-256withPLAIN-ECDSA";
+ algorithms["SHA256WITHPLAIN-ECDSA"] = "SHA-256withPLAIN-ECDSA";
+ algorithms["SHA-256WITHPLAIN-ECDSA"] = "SHA-256withPLAIN-ECDSA";
+ algorithms[BsiObjectIdentifiers.ecdsa_plain_SHA256.Id] = "SHA-256withPLAIN-ECDSA";
+
+ algorithms["SHA384/PLAIN-ECDSA"] = "SHA-384withPLAIN-ECDSA";
+ algorithms["SHA-384/PLAIN-ECDSA"] = "SHA-384withPLAIN-ECDSA";
+ algorithms["PLAIN-ECDSAWITHSHA384"] = "SHA-384withPLAIN-ECDSA";
+ algorithms["PLAIN-ECDSAWITHSHA-384"] = "SHA-384withPLAIN-ECDSA";
+ algorithms["SHA384WITHPLAIN-ECDSA"] = "SHA-384withPLAIN-ECDSA";
+ algorithms["SHA-384WITHPLAIN-ECDSA"] = "SHA-384withPLAIN-ECDSA";
+ algorithms[BsiObjectIdentifiers.ecdsa_plain_SHA384.Id] = "SHA-384withPLAIN-ECDSA";
+
+ algorithms["SHA512/PLAIN-ECDSA"] = "SHA-512withPLAIN-ECDSA";
+ algorithms["SHA-512/PLAIN-ECDSA"] = "SHA-512withPLAIN-ECDSA";
+ algorithms["PLAIN-ECDSAWITHSHA512"] = "SHA-512withPLAIN-ECDSA";
+ algorithms["PLAIN-ECDSAWITHSHA-512"] = "SHA-512withPLAIN-ECDSA";
+ algorithms["SHA512WITHPLAIN-ECDSA"] = "SHA-512withPLAIN-ECDSA";
+ algorithms["SHA-512WITHPLAIN-ECDSA"] = "SHA-512withPLAIN-ECDSA";
+ algorithms[BsiObjectIdentifiers.ecdsa_plain_SHA512.Id] = "SHA-512withPLAIN-ECDSA";
+
+ algorithms["RIPEMD160/PLAIN-ECDSA"] = "RIPEMD160withPLAIN-ECDSA";
+ algorithms["PLAIN-ECDSAWITHRIPEMD160"] = "RIPEMD160withPLAIN-ECDSA";
+ algorithms["RIPEMD160WITHPLAIN-ECDSA"] = "RIPEMD160withPLAIN-ECDSA";
+ algorithms[BsiObjectIdentifiers.ecdsa_plain_RIPEMD160.Id] = "RIPEMD160withPLAIN-ECDSA";
+
+ algorithms["SHA1WITHECNR"] = "SHA-1withECNR";
+ algorithms["SHA-1WITHECNR"] = "SHA-1withECNR";
+ algorithms["SHA224WITHECNR"] = "SHA-224withECNR";
+ algorithms["SHA-224WITHECNR"] = "SHA-224withECNR";
+ algorithms["SHA256WITHECNR"] = "SHA-256withECNR";
+ algorithms["SHA-256WITHECNR"] = "SHA-256withECNR";
+ algorithms["SHA384WITHECNR"] = "SHA-384withECNR";
+ algorithms["SHA-384WITHECNR"] = "SHA-384withECNR";
+ algorithms["SHA512WITHECNR"] = "SHA-512withECNR";
+ algorithms["SHA-512WITHECNR"] = "SHA-512withECNR";
+
+ algorithms["GOST-3410"] = "GOST3410";
+ algorithms["GOST-3410-94"] = "GOST3410";
+ algorithms["GOST3411WITHGOST3410"] = "GOST3410";
+ algorithms[CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94.Id] = "GOST3410";
+
+ algorithms["ECGOST-3410"] = "ECGOST3410";
+ algorithms["ECGOST-3410-2001"] = "ECGOST3410";
+ algorithms["GOST3411WITHECGOST3410"] = "ECGOST3410";
+ algorithms[CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001.Id] = "ECGOST3410";
+
+ algorithms["ED25519"] = "Ed25519";
+ algorithms[EdECObjectIdentifiers.id_Ed25519.Id] = "Ed25519";
+ algorithms["ED25519CTX"] = "Ed25519ctx";
+ algorithms["ED25519PH"] = "Ed25519ph";
+ algorithms["ED448"] = "Ed448";
+ algorithms[EdECObjectIdentifiers.id_Ed448.Id] = "Ed448";
+ algorithms["ED448PH"] = "Ed448ph";
+
+ oids["MD2withRSA"] = PkcsObjectIdentifiers.MD2WithRsaEncryption;
+ oids["MD4withRSA"] = PkcsObjectIdentifiers.MD4WithRsaEncryption;
+ oids["MD5withRSA"] = PkcsObjectIdentifiers.MD5WithRsaEncryption;
+
+ oids["SHA-1withRSA"] = PkcsObjectIdentifiers.Sha1WithRsaEncryption;
+ oids["SHA-224withRSA"] = PkcsObjectIdentifiers.Sha224WithRsaEncryption;
+ oids["SHA-256withRSA"] = PkcsObjectIdentifiers.Sha256WithRsaEncryption;
+ oids["SHA-384withRSA"] = PkcsObjectIdentifiers.Sha384WithRsaEncryption;
+ oids["SHA-512withRSA"] = PkcsObjectIdentifiers.Sha512WithRsaEncryption;
+
+ oids["PSSwithRSA"] = PkcsObjectIdentifiers.IdRsassaPss;
+ oids["SHA-1withRSAandMGF1"] = PkcsObjectIdentifiers.IdRsassaPss;
+ oids["SHA-224withRSAandMGF1"] = PkcsObjectIdentifiers.IdRsassaPss;
+ oids["SHA-256withRSAandMGF1"] = PkcsObjectIdentifiers.IdRsassaPss;
+ oids["SHA-384withRSAandMGF1"] = PkcsObjectIdentifiers.IdRsassaPss;
+ oids["SHA-512withRSAandMGF1"] = PkcsObjectIdentifiers.IdRsassaPss;
+
+ oids["RIPEMD128withRSA"] = TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128;
+ oids["RIPEMD160withRSA"] = TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160;
+ oids["RIPEMD256withRSA"] = TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256;
+
+ oids["SHA-1withDSA"] = X9ObjectIdentifiers.IdDsaWithSha1;
+
+ oids["SHA-1withECDSA"] = X9ObjectIdentifiers.ECDsaWithSha1;
+ oids["SHA-224withECDSA"] = X9ObjectIdentifiers.ECDsaWithSha224;
+ oids["SHA-256withECDSA"] = X9ObjectIdentifiers.ECDsaWithSha256;
+ oids["SHA-384withECDSA"] = X9ObjectIdentifiers.ECDsaWithSha384;
+ oids["SHA-512withECDSA"] = X9ObjectIdentifiers.ECDsaWithSha512;
+ oids["RIPEMD160withECDSA"] = TeleTrusTObjectIdentifiers.ECSignWithRipeMD160;
+
+ oids["SHA-1withCVC-ECDSA"] = EacObjectIdentifiers.id_TA_ECDSA_SHA_1;
+ oids["SHA-224withCVC-ECDSA"] = EacObjectIdentifiers.id_TA_ECDSA_SHA_224;
+ oids["SHA-256withCVC-ECDSA"] = EacObjectIdentifiers.id_TA_ECDSA_SHA_256;
+ oids["SHA-384withCVC-ECDSA"] = EacObjectIdentifiers.id_TA_ECDSA_SHA_384;
+ oids["SHA-512withCVC-ECDSA"] = EacObjectIdentifiers.id_TA_ECDSA_SHA_512;
+
+ oids["SHA-1withPLAIN-ECDSA"] = BsiObjectIdentifiers.ecdsa_plain_SHA1;
+ oids["SHA-224withPLAIN-ECDSA"] = BsiObjectIdentifiers.ecdsa_plain_SHA224;
+ oids["SHA-256withPLAIN-ECDSA"] = BsiObjectIdentifiers.ecdsa_plain_SHA256;
+ oids["SHA-384withPLAIN-ECDSA"] = BsiObjectIdentifiers.ecdsa_plain_SHA384;
+ oids["SHA-512withPLAIN-ECDSA"] = BsiObjectIdentifiers.ecdsa_plain_SHA512;
+ oids["RIPEMD160withPLAIN-ECDSA"] = BsiObjectIdentifiers.ecdsa_plain_RIPEMD160;
+
+ oids["GOST3410"] = CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94;
+ oids["ECGOST3410"] = CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001;
+
+ oids["Ed25519"] = EdECObjectIdentifiers.id_Ed25519;
+ oids["Ed448"] = EdECObjectIdentifiers.id_Ed448;
+ }
+
+ ///
+ /// Returns an ObjectIdentifier for a given encoding.
+ ///
+ /// A string representation of the encoding.
+ /// A DerObjectIdentifier, null if the OID is not available.
+ // TODO Don't really want to support this
+ public static DerObjectIdentifier GetObjectIdentifier(
+ string mechanism)
+ {
+ if (mechanism == null)
+ throw new ArgumentNullException("mechanism");
+
+ mechanism = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(mechanism);
+ string aliased = (string) algorithms[mechanism];
+
+ if (aliased != null)
+ mechanism = aliased;
+
+ return (DerObjectIdentifier) oids[mechanism];
+ }
+
+ public static ICollection Algorithms
+ {
+ get { return oids.Keys; }
+ }
+
+ public static Asn1Encodable GetDefaultX509Parameters(
+ DerObjectIdentifier id)
+ {
+ return GetDefaultX509Parameters(id.Id);
+ }
+
+ public static Asn1Encodable GetDefaultX509Parameters(
+ string algorithm)
+ {
+ if (algorithm == null)
+ throw new ArgumentNullException("algorithm");
+
+ algorithm = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm);
+
+ string mechanism = (string) algorithms[algorithm];
+
+ if (mechanism == null)
+ mechanism = algorithm;
+
+ if (mechanism == "PSSwithRSA")
+ {
+ // TODO The Sha1Digest here is a default. In JCE version, the actual digest
+ // to be used can be overridden by subsequent parameter settings.
+ return GetPssX509Parameters("SHA-1");
+ }
+
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "withRSAandMGF1"))
+ {
+ string digestName = mechanism.Substring(0, mechanism.Length - "withRSAandMGF1".Length);
+ return GetPssX509Parameters(digestName);
+ }
+
+ return DerNull.Instance;
+ }
+
+ private static Asn1Encodable GetPssX509Parameters(
+ string digestName)
+ {
+ AlgorithmIdentifier hashAlgorithm = new AlgorithmIdentifier(
+ DigestUtilities.GetObjectIdentifier(digestName), DerNull.Instance);
+
+ // TODO Is it possible for the MGF hash alg to be different from the PSS one?
+ AlgorithmIdentifier maskGenAlgorithm = new AlgorithmIdentifier(
+ PkcsObjectIdentifiers.IdMgf1, hashAlgorithm);
+
+ int saltLen = DigestUtilities.GetDigest(digestName).GetDigestSize();
+ return new RsassaPssParameters(hashAlgorithm, maskGenAlgorithm,
+ new DerInteger(saltLen), new DerInteger(1));
+ }
+
+ public static ISigner GetSigner(
+ DerObjectIdentifier id)
+ {
+ return GetSigner(id.Id);
+ }
+
+ public static ISigner GetSigner(
+ string algorithm)
+ {
+ if (algorithm == null)
+ throw new ArgumentNullException("algorithm");
+
+ algorithm = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm);
+
+ string mechanism = (string) algorithms[algorithm];
+
+ if (mechanism == null)
+ mechanism = algorithm;
+
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "Ed"))
+ {
+ if (mechanism.Equals("Ed25519"))
+ {
+ return new Ed25519Signer();
+ }
+ if (mechanism.Equals("Ed25519ctx"))
+ {
+ return new Ed25519ctxSigner(Arrays.EmptyBytes);
+ }
+ if (mechanism.Equals("Ed25519ph"))
+ {
+ return new Ed25519phSigner(Arrays.EmptyBytes);
+ }
+ if (mechanism.Equals("Ed448"))
+ {
+ return new Ed448Signer(Arrays.EmptyBytes);
+ }
+ if (mechanism.Equals("Ed448ph"))
+ {
+ return new Ed448phSigner(Arrays.EmptyBytes);
+ }
+ }
+
+ if (mechanism.Equals("RSA"))
+ {
+ return (new RsaDigestSigner(new NullDigest(), (AlgorithmIdentifier)null));
+ }
+ if (mechanism.Equals("RAWRSASSA-PSS"))
+ {
+ // TODO Add support for other parameter settings
+ return PssSigner.CreateRawSigner(new RsaBlindedEngine(), new Sha1Digest());
+ }
+ if (mechanism.Equals("PSSwithRSA"))
+ {
+ // TODO The Sha1Digest here is a default. In JCE version, the actual digest
+ // to be used can be overridden by subsequent parameter settings.
+ return (new PssSigner(new RsaBlindedEngine(), new Sha1Digest()));
+ }
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "withRSA"))
+ {
+ string digestName = mechanism.Substring(0, mechanism.LastIndexOf("with"));
+ IDigest digest = DigestUtilities.GetDigest(digestName);
+ return new RsaDigestSigner(digest);
+ }
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "withRSAandMGF1"))
+ {
+ string digestName = mechanism.Substring(0, mechanism.LastIndexOf("with"));
+ IDigest digest = DigestUtilities.GetDigest(digestName);
+ return new PssSigner(new RsaBlindedEngine(), digest);
+ }
+
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "withDSA"))
+ {
+ string digestName = mechanism.Substring(0, mechanism.LastIndexOf("with"));
+ IDigest digest = DigestUtilities.GetDigest(digestName);
+ return new DsaDigestSigner(new DsaSigner(), digest);
+ }
+
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "withECDSA"))
+ {
+ string digestName = mechanism.Substring(0, mechanism.LastIndexOf("with"));
+ IDigest digest = DigestUtilities.GetDigest(digestName);
+ return new DsaDigestSigner(new ECDsaSigner(), digest);
+ }
+
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "withCVC-ECDSA")
+ || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "withPLAIN-ECDSA"))
+ {
+ string digestName = mechanism.Substring(0, mechanism.LastIndexOf("with"));
+ IDigest digest = DigestUtilities.GetDigest(digestName);
+ return new DsaDigestSigner(new ECDsaSigner(), digest, PlainDsaEncoding.Instance);
+ }
+
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "withECNR"))
+ {
+ string digestName = mechanism.Substring(0, mechanism.LastIndexOf("with"));
+ IDigest digest = DigestUtilities.GetDigest(digestName);
+ return new DsaDigestSigner(new ECNRSigner(), digest);
+ }
+
+ if (mechanism.Equals("GOST3410"))
+ {
+ return new Gost3410DigestSigner(new Gost3410Signer(), new Gost3411Digest());
+ }
+ if (mechanism.Equals("ECGOST3410"))
+ {
+ return new Gost3410DigestSigner(new ECGost3410Signer(), new Gost3411Digest());
+ }
+
+ if (mechanism.Equals("SHA1WITHRSA/ISO9796-2"))
+ {
+ return new Iso9796d2Signer(new RsaBlindedEngine(), new Sha1Digest(), true);
+ }
+ if (mechanism.Equals("MD5WITHRSA/ISO9796-2"))
+ {
+ return new Iso9796d2Signer(new RsaBlindedEngine(), new MD5Digest(), true);
+ }
+ if (mechanism.Equals("RIPEMD160WITHRSA/ISO9796-2"))
+ {
+ return new Iso9796d2Signer(new RsaBlindedEngine(), new RipeMD160Digest(), true);
+ }
+
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "/X9.31"))
+ {
+ string x931 = mechanism.Substring(0, mechanism.Length - "/X9.31".Length);
+ int withPos = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.IndexOf(x931, "WITH");
+ if (withPos > 0)
+ {
+ int endPos = withPos + "WITH".Length;
+
+ string digestName = x931.Substring(0, withPos);
+ IDigest digest = DigestUtilities.GetDigest(digestName);
+
+ string cipherName = x931.Substring(endPos, x931.Length - endPos);
+ if (cipherName.Equals("RSA"))
+ {
+ IAsymmetricBlockCipher cipher = new RsaBlindedEngine();
+ return new X931Signer(cipher, digest);
+ }
+ }
+ }
+
+ throw new SecurityUtilityException("Signer " + algorithm + " not recognised.");
+ }
+
+ public static string GetEncodingName(
+ DerObjectIdentifier oid)
+ {
+ return (string) algorithms[oid.Id];
+ }
+
+ public static ISigner InitSigner(DerObjectIdentifier algorithmOid, bool forSigning, AsymmetricKeyParameter privateKey, SecureRandom random)
+ {
+ return InitSigner(algorithmOid.Id, forSigning, privateKey, random);
+ }
+
+ public static ISigner InitSigner(string algorithm, bool forSigning, AsymmetricKeyParameter privateKey, SecureRandom random)
+ {
+ ISigner signer = SignerUtilities.GetSigner(algorithm);
+ signer.Init(forSigning, ParameterUtilities.WithRandom(privateKey, random));
+ return signer;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/SignerUtilities.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/SignerUtilities.cs.meta
new file mode 100644
index 00000000..f77e633c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/SignerUtilities.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 06997fffd3bfe604f912392f70471c57
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/WrapperUtilities.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/WrapperUtilities.cs
new file mode 100644
index 00000000..18e581d1
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/WrapperUtilities.cs
@@ -0,0 +1,157 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Kisa;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Ntt;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security
+{
+ ///
+ /// Utility class for creating IWrapper objects from their names/Oids
+ ///
+ public sealed class WrapperUtilities
+ {
+ private enum WrapAlgorithm { AESWRAP, CAMELLIAWRAP, DESEDEWRAP, RC2WRAP, SEEDWRAP,
+ DESEDERFC3211WRAP, AESRFC3211WRAP, CAMELLIARFC3211WRAP };
+
+ private WrapperUtilities()
+ {
+ }
+
+ private static readonly IDictionary algorithms = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ //private static readonly IDictionary oids = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+
+ static WrapperUtilities()
+ {
+ // Signal to obfuscation tools not to change enum constants
+ ((WrapAlgorithm)Enums.GetArbitraryValue(typeof(WrapAlgorithm))).ToString();
+
+ algorithms[NistObjectIdentifiers.IdAes128Wrap.Id] = "AESWRAP";
+ algorithms[NistObjectIdentifiers.IdAes192Wrap.Id] = "AESWRAP";
+ algorithms[NistObjectIdentifiers.IdAes256Wrap.Id] = "AESWRAP";
+
+ algorithms[NttObjectIdentifiers.IdCamellia128Wrap.Id] = "CAMELLIAWRAP";
+ algorithms[NttObjectIdentifiers.IdCamellia192Wrap.Id] = "CAMELLIAWRAP";
+ algorithms[NttObjectIdentifiers.IdCamellia256Wrap.Id] = "CAMELLIAWRAP";
+
+ algorithms[PkcsObjectIdentifiers.IdAlgCms3DesWrap.Id] = "DESEDEWRAP";
+ algorithms["TDEAWRAP"] = "DESEDEWRAP";
+
+ algorithms[PkcsObjectIdentifiers.IdAlgCmsRC2Wrap.Id] = "RC2WRAP";
+
+ algorithms[KisaObjectIdentifiers.IdNpkiAppCmsSeedWrap.Id] = "SEEDWRAP";
+ }
+
+ public static IWrapper GetWrapper(
+ DerObjectIdentifier oid)
+ {
+ return GetWrapper(oid.Id);
+ }
+
+ public static IWrapper GetWrapper(
+ string algorithm)
+ {
+ string upper = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm);
+ string mechanism = (string)algorithms[upper];
+
+ if (mechanism == null)
+ {
+ mechanism = upper;
+ }
+
+ try
+ {
+ WrapAlgorithm wrapAlgorithm = (WrapAlgorithm)Enums.GetEnumValue(
+ typeof(WrapAlgorithm), mechanism);
+
+ switch (wrapAlgorithm)
+ {
+ case WrapAlgorithm.AESWRAP: return new AesWrapEngine();
+ case WrapAlgorithm.CAMELLIAWRAP: return new CamelliaWrapEngine();
+ case WrapAlgorithm.DESEDEWRAP: return new DesEdeWrapEngine();
+ case WrapAlgorithm.RC2WRAP: return new RC2WrapEngine();
+ case WrapAlgorithm.SEEDWRAP: return new SeedWrapEngine();
+ case WrapAlgorithm.DESEDERFC3211WRAP: return new Rfc3211WrapEngine(new DesEdeEngine());
+ case WrapAlgorithm.AESRFC3211WRAP: return new Rfc3211WrapEngine(new AesEngine());
+ case WrapAlgorithm.CAMELLIARFC3211WRAP: return new Rfc3211WrapEngine(new CamelliaEngine());
+ }
+ }
+ catch (ArgumentException)
+ {
+ }
+
+ // Create an IBufferedCipher and use it as IWrapper (via BufferedCipherWrapper)
+ IBufferedCipher blockCipher = CipherUtilities.GetCipher(algorithm);
+
+ if (blockCipher != null)
+ return new BufferedCipherWrapper(blockCipher);
+
+ throw new SecurityUtilityException("Wrapper " + algorithm + " not recognised.");
+ }
+
+ public static string GetAlgorithmName(
+ DerObjectIdentifier oid)
+ {
+ return (string) algorithms[oid.Id];
+ }
+
+ private class BufferedCipherWrapper
+ : IWrapper
+ {
+ private readonly IBufferedCipher cipher;
+ private bool forWrapping;
+
+ public BufferedCipherWrapper(
+ IBufferedCipher cipher)
+ {
+ this.cipher = cipher;
+ }
+
+ public string AlgorithmName
+ {
+ get { return cipher.AlgorithmName; }
+ }
+
+ public void Init(
+ bool forWrapping,
+ ICipherParameters parameters)
+ {
+ this.forWrapping = forWrapping;
+
+ cipher.Init(forWrapping, parameters);
+ }
+
+ public byte[] Wrap(
+ byte[] input,
+ int inOff,
+ int length)
+ {
+ if (!forWrapping)
+ throw new InvalidOperationException("Not initialised for wrapping");
+
+ return cipher.DoFinal(input, inOff, length);
+ }
+
+ public byte[] Unwrap(
+ byte[] input,
+ int inOff,
+ int length)
+ {
+ if (forWrapping)
+ throw new InvalidOperationException("Not initialised for unwrapping");
+
+ return cipher.DoFinal(input, inOff, length);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/WrapperUtilities.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/WrapperUtilities.cs.meta
new file mode 100644
index 00000000..0f7a0223
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/WrapperUtilities.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 73ae39e593069a449ae3656aa207a8c6
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert.meta
new file mode 100644
index 00000000..518fb0d9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: d73ca49e92fed5341b3ab5351606b988
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateEncodingException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateEncodingException.cs
new file mode 100644
index 00000000..b4589cb9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateEncodingException.cs
@@ -0,0 +1,18 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates
+{
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class CertificateEncodingException : CertificateException
+ {
+ public CertificateEncodingException() : base() { }
+ public CertificateEncodingException(string msg) : base(msg) { }
+ public CertificateEncodingException(string msg, Exception e) : base(msg, e) { }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateEncodingException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateEncodingException.cs.meta
new file mode 100644
index 00000000..8a7f8a40
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateEncodingException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 7d13d171e5bd63a43857b59678c5b634
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateException.cs
new file mode 100644
index 00000000..2d56966a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateException.cs
@@ -0,0 +1,18 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates
+{
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class CertificateException : GeneralSecurityException
+ {
+ public CertificateException() : base() { }
+ public CertificateException(string message) : base(message) { }
+ public CertificateException(string message, Exception exception) : base(message, exception) { }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateException.cs.meta
new file mode 100644
index 00000000..b1850b5f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 312dba7b3b4d2b64f9f51f95db4ee1ca
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateExpiredException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateExpiredException.cs
new file mode 100644
index 00000000..c73639a4
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateExpiredException.cs
@@ -0,0 +1,18 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates
+{
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class CertificateExpiredException : CertificateException
+ {
+ public CertificateExpiredException() : base() { }
+ public CertificateExpiredException(string message) : base(message) { }
+ public CertificateExpiredException(string message, Exception exception) : base(message, exception) { }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateExpiredException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateExpiredException.cs.meta
new file mode 100644
index 00000000..3822b60e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateExpiredException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 94e5534bd782d1d4aa1d9cdf658ef365
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateNotYetValidException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateNotYetValidException.cs
new file mode 100644
index 00000000..391b7440
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateNotYetValidException.cs
@@ -0,0 +1,18 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates
+{
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class CertificateNotYetValidException : CertificateException
+ {
+ public CertificateNotYetValidException() : base() { }
+ public CertificateNotYetValidException(string message) : base(message) { }
+ public CertificateNotYetValidException(string message, Exception exception) : base(message, exception) { }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateNotYetValidException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateNotYetValidException.cs.meta
new file mode 100644
index 00000000..b2de4bdd
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateNotYetValidException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 1c062f71e1e45684aaa24f6ec45dc08c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateParsingException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateParsingException.cs
new file mode 100644
index 00000000..6f6e09d4
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateParsingException.cs
@@ -0,0 +1,18 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates
+{
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class CertificateParsingException : CertificateException
+ {
+ public CertificateParsingException() : base() { }
+ public CertificateParsingException(string message) : base(message) { }
+ public CertificateParsingException(string message, Exception exception) : base(message, exception) { }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateParsingException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateParsingException.cs.meta
new file mode 100644
index 00000000..8a732cb0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CertificateParsingException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: cf1c2ef4e5eeedd4aac155d8a36837c3
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CrlException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CrlException.cs
new file mode 100644
index 00000000..6557a3c7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CrlException.cs
@@ -0,0 +1,18 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates
+{
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class CrlException : GeneralSecurityException
+ {
+ public CrlException() : base() { }
+ public CrlException(string msg) : base(msg) {}
+ public CrlException(string msg, Exception e) : base(msg, e) {}
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CrlException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CrlException.cs.meta
new file mode 100644
index 00000000..653afffc
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/security/cert/CrlException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: b0c28bc603c44ba4cae418797434e798
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp.meta
new file mode 100644
index 00000000..83bc41ee
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp.meta
@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: b65683262d1a3214f857d8d7a9199f0c
+folderAsset: yes
+timeCreated: 1547039641
+licenseType: Store
+DefaultImporter:
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/GenTimeAccuracy.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/GenTimeAccuracy.cs
new file mode 100644
index 00000000..2923eafc
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/GenTimeAccuracy.cs
@@ -0,0 +1,37 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Tsp;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tsp
+{
+ public class GenTimeAccuracy
+ {
+ private Accuracy accuracy;
+
+ public GenTimeAccuracy(
+ Accuracy accuracy)
+ {
+ this.accuracy = accuracy;
+ }
+
+ public int Seconds { get { return GetTimeComponent(accuracy.Seconds); } }
+
+ public int Millis { get { return GetTimeComponent(accuracy.Millis); } }
+
+ public int Micros { get { return GetTimeComponent(accuracy.Micros); } }
+
+ private int GetTimeComponent(
+ DerInteger time)
+ {
+ return time == null ? 0 : time.Value.IntValue;
+ }
+
+ public override string ToString()
+ {
+ return Seconds + "." + Millis.ToString("000") + Micros.ToString("000");
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/GenTimeAccuracy.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/GenTimeAccuracy.cs.meta
new file mode 100644
index 00000000..72858145
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/GenTimeAccuracy.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: b121e50e39f7eae438bd60a8c88d8aab
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TSPAlgorithms.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TSPAlgorithms.cs
new file mode 100644
index 00000000..f001c162
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TSPAlgorithms.cs
@@ -0,0 +1,58 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.GM;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Oiw;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Rosstandart;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.TeleTrust;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tsp
+{
+ /**
+ * Recognised hash algorithms for the time stamp protocol.
+ */
+ public abstract class TspAlgorithms
+ {
+ public static readonly string MD5 = PkcsObjectIdentifiers.MD5.Id;
+
+ public static readonly string Sha1 = OiwObjectIdentifiers.IdSha1.Id;
+
+ public static readonly string Sha224 = NistObjectIdentifiers.IdSha224.Id;
+ public static readonly string Sha256 = NistObjectIdentifiers.IdSha256.Id;
+ public static readonly string Sha384 = NistObjectIdentifiers.IdSha384.Id;
+ public static readonly string Sha512 = NistObjectIdentifiers.IdSha512.Id;
+
+ public static readonly string RipeMD128 = TeleTrusTObjectIdentifiers.RipeMD128.Id;
+ public static readonly string RipeMD160 = TeleTrusTObjectIdentifiers.RipeMD160.Id;
+ public static readonly string RipeMD256 = TeleTrusTObjectIdentifiers.RipeMD256.Id;
+
+ public static readonly string Gost3411 = CryptoProObjectIdentifiers.GostR3411.Id;
+ public static readonly string Gost3411_2012_256 = RosstandartObjectIdentifiers.id_tc26_gost_3411_12_256.Id;
+ public static readonly string Gost3411_2012_512 = RosstandartObjectIdentifiers.id_tc26_gost_3411_12_512.Id;
+
+ public static readonly string SM3 = GMObjectIdentifiers.sm3.Id;
+
+ public static readonly IList Allowed;
+
+ static TspAlgorithms()
+ {
+ string[] algs = new string[]
+ {
+ Gost3411, Gost3411_2012_256, Gost3411_2012_512, MD5, RipeMD128, RipeMD160, RipeMD256, Sha1, Sha224, Sha256, Sha384, Sha512, SM3
+ };
+
+ Allowed = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ foreach (string alg in algs)
+ {
+ Allowed.Add(alg);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TSPAlgorithms.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TSPAlgorithms.cs.meta
new file mode 100644
index 00000000..703aaa5d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TSPAlgorithms.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 499a88718c5a4bc4f83dbb4ea7aa4ed9
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TSPException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TSPException.cs
new file mode 100644
index 00000000..3771dd5f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TSPException.cs
@@ -0,0 +1,32 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tsp
+{
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class TspException
+ : Exception
+ {
+ public TspException()
+ {
+ }
+
+ public TspException(
+ string message)
+ : base(message)
+ {
+ }
+
+ public TspException(
+ string message,
+ Exception e)
+ : base(message, e)
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TSPException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TSPException.cs.meta
new file mode 100644
index 00000000..626e3ce3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TSPException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 7656ac180275ac84f835935c4731b5b5
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TSPUtil.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TSPUtil.cs
new file mode 100644
index 00000000..617cc41a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TSPUtil.cs
@@ -0,0 +1,218 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.GM;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Oiw;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Rosstandart;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.TeleTrust;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Cms;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tsp
+{
+ public class TspUtil
+ {
+ private static ISet EmptySet = CollectionUtilities.ReadOnly(new HashSet());
+ private static IList EmptyList = CollectionUtilities.ReadOnly(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList());
+
+ private static readonly IDictionary digestLengths = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ private static readonly IDictionary digestNames = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+
+ static TspUtil()
+ {
+ digestLengths.Add(PkcsObjectIdentifiers.MD5.Id, 16);
+ digestLengths.Add(OiwObjectIdentifiers.IdSha1.Id, 20);
+ digestLengths.Add(NistObjectIdentifiers.IdSha224.Id, 28);
+ digestLengths.Add(NistObjectIdentifiers.IdSha256.Id, 32);
+ digestLengths.Add(NistObjectIdentifiers.IdSha384.Id, 48);
+ digestLengths.Add(NistObjectIdentifiers.IdSha512.Id, 64);
+ digestLengths.Add(TeleTrusTObjectIdentifiers.RipeMD128.Id, 16);
+ digestLengths.Add(TeleTrusTObjectIdentifiers.RipeMD160.Id, 20);
+ digestLengths.Add(TeleTrusTObjectIdentifiers.RipeMD256.Id, 32);
+ digestLengths.Add(CryptoProObjectIdentifiers.GostR3411.Id, 32);
+ digestLengths.Add(RosstandartObjectIdentifiers.id_tc26_gost_3411_12_256.Id, 32);
+ digestLengths.Add(RosstandartObjectIdentifiers.id_tc26_gost_3411_12_512.Id, 64);
+ digestLengths.Add(GMObjectIdentifiers.sm3.Id, 32);
+
+ digestNames.Add(PkcsObjectIdentifiers.MD5.Id, "MD5");
+ digestNames.Add(OiwObjectIdentifiers.IdSha1.Id, "SHA1");
+ digestNames.Add(NistObjectIdentifiers.IdSha224.Id, "SHA224");
+ digestNames.Add(NistObjectIdentifiers.IdSha256.Id, "SHA256");
+ digestNames.Add(NistObjectIdentifiers.IdSha384.Id, "SHA384");
+ digestNames.Add(NistObjectIdentifiers.IdSha512.Id, "SHA512");
+ digestNames.Add(PkcsObjectIdentifiers.MD5WithRsaEncryption.Id, "MD5");
+ digestNames.Add(PkcsObjectIdentifiers.Sha1WithRsaEncryption.Id, "SHA1");
+ digestNames.Add(PkcsObjectIdentifiers.Sha224WithRsaEncryption.Id, "SHA224");
+ digestNames.Add(PkcsObjectIdentifiers.Sha256WithRsaEncryption.Id, "SHA256");
+ digestNames.Add(PkcsObjectIdentifiers.Sha384WithRsaEncryption.Id, "SHA384");
+ digestNames.Add(PkcsObjectIdentifiers.Sha512WithRsaEncryption.Id, "SHA512");
+ digestNames.Add(TeleTrusTObjectIdentifiers.RipeMD128.Id, "RIPEMD128");
+ digestNames.Add(TeleTrusTObjectIdentifiers.RipeMD160.Id, "RIPEMD160");
+ digestNames.Add(TeleTrusTObjectIdentifiers.RipeMD256.Id, "RIPEMD256");
+ digestNames.Add(CryptoProObjectIdentifiers.GostR3411.Id, "GOST3411");
+ digestNames.Add(OiwObjectIdentifiers.DsaWithSha1.Id, "SHA1");
+ digestNames.Add(OiwObjectIdentifiers.Sha1WithRsa.Id, "SHA1");
+ digestNames.Add(OiwObjectIdentifiers.MD5WithRsa.Id, "MD5");
+ digestNames.Add(RosstandartObjectIdentifiers.id_tc26_gost_3411_12_256.Id, "GOST3411-2012-256");
+ digestNames.Add(RosstandartObjectIdentifiers.id_tc26_gost_3411_12_512.Id, "GOST3411-2012-512");
+ digestNames.Add(GMObjectIdentifiers.sm3.Id, "SM3");
+ }
+
+
+ /**
+ * Fetches the signature time-stamp attributes from a SignerInformation object.
+ * Checks that the MessageImprint for each time-stamp matches the signature field.
+ * (see RFC 3161 Appendix A).
+ *
+ * @param signerInfo a SignerInformation to search for time-stamps
+ * @return a collection of TimeStampToken objects
+ * @throws TSPValidationException
+ */
+ public static ICollection GetSignatureTimestamps(
+ SignerInformation signerInfo)
+ {
+ IList timestamps = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+
+ Asn1.Cms.AttributeTable unsignedAttrs = signerInfo.UnsignedAttributes;
+ if (unsignedAttrs != null)
+ {
+ foreach (Asn1.Cms.Attribute tsAttr in unsignedAttrs.GetAll(
+ PkcsObjectIdentifiers.IdAASignatureTimeStampToken))
+ {
+ foreach (Asn1Encodable asn1 in tsAttr.AttrValues)
+ {
+ try
+ {
+ Asn1.Cms.ContentInfo contentInfo = Asn1.Cms.ContentInfo.GetInstance(
+ asn1.ToAsn1Object());
+ TimeStampToken timeStampToken = new TimeStampToken(contentInfo);
+ TimeStampTokenInfo tstInfo = timeStampToken.TimeStampInfo;
+
+ byte[] expectedDigest = DigestUtilities.CalculateDigest(
+ GetDigestAlgName(tstInfo.MessageImprintAlgOid),
+ signerInfo.GetSignature());
+
+ if (!Arrays.ConstantTimeAreEqual(expectedDigest, tstInfo.GetMessageImprintDigest()))
+ throw new TspValidationException("Incorrect digest in message imprint");
+
+ timestamps.Add(timeStampToken);
+ }
+ catch (SecurityUtilityException)
+ {
+ throw new TspValidationException("Unknown hash algorithm specified in timestamp");
+ }
+ catch (Exception)
+ {
+ throw new TspValidationException("Timestamp could not be parsed");
+ }
+ }
+ }
+ }
+
+ return timestamps;
+ }
+
+ /**
+ * Validate the passed in certificate as being of the correct type to be used
+ * for time stamping. To be valid it must have an ExtendedKeyUsage extension
+ * which has a key purpose identifier of id-kp-timeStamping.
+ *
+ * @param cert the certificate of interest.
+ * @throws TspValidationException if the certicate fails on one of the check points.
+ */
+ public static void ValidateCertificate(
+ X509Certificate cert)
+ {
+ if (cert.Version != 3)
+ throw new ArgumentException("Certificate must have an ExtendedKeyUsage extension.");
+
+ Asn1OctetString ext = cert.GetExtensionValue(X509Extensions.ExtendedKeyUsage);
+ if (ext == null)
+ throw new TspValidationException("Certificate must have an ExtendedKeyUsage extension.");
+
+ if (!cert.GetCriticalExtensionOids().Contains(X509Extensions.ExtendedKeyUsage.Id))
+ throw new TspValidationException("Certificate must have an ExtendedKeyUsage extension marked as critical.");
+
+ try
+ {
+ ExtendedKeyUsage extKey = ExtendedKeyUsage.GetInstance(
+ Asn1Object.FromByteArray(ext.GetOctets()));
+
+ if (!extKey.HasKeyPurposeId(KeyPurposeID.IdKPTimeStamping) || extKey.Count != 1)
+ throw new TspValidationException("ExtendedKeyUsage not solely time stamping.");
+ }
+ catch (IOException)
+ {
+ throw new TspValidationException("cannot process ExtendedKeyUsage extension");
+ }
+ }
+
+ ///
+ /// Return the digest algorithm using one of the standard JCA string
+ /// representations rather than the algorithm identifier (if possible).
+ ///
+ internal static string GetDigestAlgName(
+ string digestAlgOID)
+ {
+ string digestName = (string) digestNames[digestAlgOID];
+
+ return digestName != null ? digestName : digestAlgOID;
+ }
+
+ internal static int GetDigestLength(
+ string digestAlgOID)
+ {
+ if (!digestLengths.Contains(digestAlgOID))
+ throw new TspException("digest algorithm cannot be found.");
+
+ return (int)digestLengths[digestAlgOID];
+ }
+
+ internal static IDigest CreateDigestInstance(
+ String digestAlgOID)
+ {
+ string digestName = GetDigestAlgName(digestAlgOID);
+
+ return DigestUtilities.GetDigest(digestName);
+ }
+
+ internal static ISet GetCriticalExtensionOids(X509Extensions extensions)
+ {
+ if (extensions == null)
+ return EmptySet;
+
+ return CollectionUtilities.ReadOnly(new HashSet(extensions.GetCriticalExtensionOids()));
+ }
+
+ internal static ISet GetNonCriticalExtensionOids(X509Extensions extensions)
+ {
+ if (extensions == null)
+ return EmptySet;
+
+ // TODO: should probably produce a set that imposes correct ordering
+ return CollectionUtilities.ReadOnly(new HashSet(extensions.GetNonCriticalExtensionOids()));
+ }
+
+ internal static IList GetExtensionOids(X509Extensions extensions)
+ {
+ if (extensions == null)
+ return EmptyList;
+
+ return CollectionUtilities.ReadOnly(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(extensions.GetExtensionOids()));
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TSPUtil.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TSPUtil.cs.meta
new file mode 100644
index 00000000..26a89878
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TSPUtil.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ac5ae719ecc37554b9cf608fb87fef41
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TSPValidationException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TSPValidationException.cs
new file mode 100644
index 00000000..cb6b7e61
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TSPValidationException.cs
@@ -0,0 +1,48 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tsp
+{
+ /**
+ * Exception thrown if a TSP request or response fails to validate.
+ *
+ * If a failure code is associated with the exception it can be retrieved using
+ * the getFailureCode() method.
+ */
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class TspValidationException
+ : TspException
+ {
+ private int failureCode;
+
+ public TspValidationException(
+ string message)
+ : base(message)
+ {
+ this.failureCode = -1;
+ }
+
+ public TspValidationException(
+ string message,
+ int failureCode)
+ : base(message)
+ {
+ this.failureCode = failureCode;
+ }
+
+ /**
+ * Return the failure code associated with this exception - if one is set.
+ *
+ * @return the failure code if set, -1 otherwise.
+ */
+ public int FailureCode
+ {
+ get { return failureCode; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TSPValidationException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TSPValidationException.cs.meta
new file mode 100644
index 00000000..47e130e2
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TSPValidationException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 17b0d10ccf7ab7c4c815f6d81d87f6bb
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampRequest.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampRequest.cs
new file mode 100644
index 00000000..975424a8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampRequest.cs
@@ -0,0 +1,190 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Tsp;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tsp
+{
+ /**
+ * Base class for an RFC 3161 Time Stamp Request.
+ */
+ public class TimeStampRequest
+ : X509ExtensionBase
+ {
+ private TimeStampReq req;
+ private X509Extensions extensions;
+
+ public TimeStampRequest(
+ TimeStampReq req)
+ {
+ this.req = req;
+ this.extensions = req.Extensions;
+ }
+
+ /**
+ * Create a TimeStampRequest from the past in byte array.
+ *
+ * @param req byte array containing the request.
+ * @throws IOException if the request is malformed.
+ */
+ public TimeStampRequest(
+ byte[] req)
+ : this(new Asn1InputStream(req))
+ {
+ }
+
+ /**
+ * Create a TimeStampRequest from the past in input stream.
+ *
+ * @param in input stream containing the request.
+ * @throws IOException if the request is malformed.
+ */
+ public TimeStampRequest(
+ Stream input)
+ : this(new Asn1InputStream(input))
+ {
+ }
+
+ private TimeStampRequest(
+ Asn1InputStream str)
+ {
+ try
+ {
+ this.req = TimeStampReq.GetInstance(str.ReadObject());
+ }
+ catch (InvalidCastException e)
+ {
+ throw new IOException("malformed request: " + e);
+ }
+ catch (ArgumentException e)
+ {
+ throw new IOException("malformed request: " + e);
+ }
+ }
+
+ public int Version
+ {
+ get { return req.Version.Value.IntValue; }
+ }
+
+ public string MessageImprintAlgOid
+ {
+ get { return req.MessageImprint.HashAlgorithm.Algorithm.Id; }
+ }
+
+ public byte[] GetMessageImprintDigest()
+ {
+ return req.MessageImprint.GetHashedMessage();
+ }
+
+ public string ReqPolicy
+ {
+ get
+ {
+ return req.ReqPolicy == null
+ ? null
+ : req.ReqPolicy.Id;
+ }
+ }
+
+ public BigInteger Nonce
+ {
+ get
+ {
+ return req.Nonce == null
+ ? null
+ : req.Nonce.Value;
+ }
+ }
+
+ public bool CertReq
+ {
+ get
+ {
+ return req.CertReq == null
+ ? false
+ : req.CertReq.IsTrue;
+ }
+ }
+
+ /**
+ * Validate the timestamp request, checking the digest to see if it is of an
+ * accepted type and whether it is of the correct length for the algorithm specified.
+ *
+ * @param algorithms a set of string OIDS giving accepted algorithms.
+ * @param policies if non-null a set of policies we are willing to sign under.
+ * @param extensions if non-null a set of extensions we are willing to accept.
+ * @throws TspException if the request is invalid, or processing fails.
+ */
+ public void Validate(
+ IList algorithms,
+ IList policies,
+ IList extensions)
+ {
+ if (!algorithms.Contains(this.MessageImprintAlgOid))
+ throw new TspValidationException("request contains unknown algorithm", PkiFailureInfo.BadAlg);
+
+ if (policies != null && this.ReqPolicy != null && !policies.Contains(this.ReqPolicy))
+ throw new TspValidationException("request contains unknown policy", PkiFailureInfo.UnacceptedPolicy);
+
+ if (this.Extensions != null && extensions != null)
+ {
+ foreach (DerObjectIdentifier oid in this.Extensions.ExtensionOids)
+ {
+ if (!extensions.Contains(oid.Id))
+ throw new TspValidationException("request contains unknown extension", PkiFailureInfo.UnacceptedExtension);
+ }
+ }
+
+ int digestLength = TspUtil.GetDigestLength(this.MessageImprintAlgOid);
+
+ if (digestLength != this.GetMessageImprintDigest().Length)
+ throw new TspValidationException("imprint digest the wrong length", PkiFailureInfo.BadDataFormat);
+ }
+
+ /**
+ * return the ASN.1 encoded representation of this object.
+ */
+ public byte[] GetEncoded()
+ {
+ return req.GetEncoded();
+ }
+
+ internal X509Extensions Extensions
+ {
+ get { return req.Extensions; }
+ }
+
+ public virtual bool HasExtensions
+ {
+ get { return extensions != null; }
+ }
+
+ public virtual X509Extension GetExtension(DerObjectIdentifier oid)
+ {
+ return extensions == null ? null : extensions.GetExtension(oid);
+ }
+
+ public virtual IList GetExtensionOids()
+ {
+ return TspUtil.GetExtensionOids(extensions);
+ }
+
+ protected override X509Extensions GetX509Extensions()
+ {
+ return Extensions;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampRequest.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampRequest.cs.meta
new file mode 100644
index 00000000..04933edf
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampRequest.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a3f95e3ff8f9fee4d8c530f910ce5104
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampRequestGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampRequestGenerator.cs
new file mode 100644
index 00000000..0b1474af
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampRequestGenerator.cs
@@ -0,0 +1,143 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Tsp;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tsp
+{
+ /**
+ * Generator for RFC 3161 Time Stamp Request objects.
+ */
+ public class TimeStampRequestGenerator
+ {
+ private DerObjectIdentifier reqPolicy;
+
+ private DerBoolean certReq;
+
+ private IDictionary extensions = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ private IList extOrdering = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+
+ public void SetReqPolicy(
+ string reqPolicy)
+ {
+ this.reqPolicy = new DerObjectIdentifier(reqPolicy);
+ }
+
+ public void SetCertReq(
+ bool certReq)
+ {
+ this.certReq = DerBoolean.GetInstance(certReq);
+ }
+
+ /**
+ * add a given extension field for the standard extensions tag (tag 3)
+ * @throws IOException
+ */
+ [Obsolete("Use method taking DerObjectIdentifier")]
+ public void AddExtension(
+ string oid,
+ bool critical,
+ Asn1Encodable value)
+ {
+ this.AddExtension(oid, critical, value.GetEncoded());
+ }
+
+ /**
+ * add a given extension field for the standard extensions tag
+ * The value parameter becomes the contents of the octet string associated
+ * with the extension.
+ */
+ [Obsolete("Use method taking DerObjectIdentifier")]
+ public void AddExtension(
+ string oid,
+ bool critical,
+ byte[] value)
+ {
+ DerObjectIdentifier derOid = new DerObjectIdentifier(oid);
+ extensions[derOid] = new X509Extension(critical, new DerOctetString(value));
+ extOrdering.Add(derOid);
+ }
+
+ /**
+ * add a given extension field for the standard extensions tag (tag 3)
+ * @throws IOException
+ */
+ public virtual void AddExtension(
+ DerObjectIdentifier oid,
+ bool critical,
+ Asn1Encodable extValue)
+ {
+ this.AddExtension(oid, critical, extValue.GetEncoded());
+ }
+
+ /**
+ * add a given extension field for the standard extensions tag
+ * The value parameter becomes the contents of the octet string associated
+ * with the extension.
+ */
+ public virtual void AddExtension(
+ DerObjectIdentifier oid,
+ bool critical,
+ byte[] extValue)
+ {
+ extensions.Add(oid, new X509Extension(critical, new DerOctetString(extValue)));
+ extOrdering.Add(oid);
+ }
+
+ public TimeStampRequest Generate(
+ string digestAlgorithm,
+ byte[] digest)
+ {
+ return this.Generate(digestAlgorithm, digest, null);
+ }
+
+ public TimeStampRequest Generate(
+ string digestAlgorithmOid,
+ byte[] digest,
+ BigInteger nonce)
+ {
+ if (digestAlgorithmOid == null)
+ {
+ throw new ArgumentException("No digest algorithm specified");
+ }
+
+ DerObjectIdentifier digestAlgOid = new DerObjectIdentifier(digestAlgorithmOid);
+
+ AlgorithmIdentifier algID = new AlgorithmIdentifier(digestAlgOid, DerNull.Instance);
+ MessageImprint messageImprint = new MessageImprint(algID, digest);
+
+ X509Extensions ext = null;
+
+ if (extOrdering.Count != 0)
+ {
+ ext = new X509Extensions(extOrdering, extensions);
+ }
+
+ DerInteger derNonce = nonce == null
+ ? null
+ : new DerInteger(nonce);
+
+ return new TimeStampRequest(
+ new TimeStampReq(messageImprint, reqPolicy, derNonce, certReq, ext));
+ }
+
+ public virtual TimeStampRequest Generate(DerObjectIdentifier digestAlgorithm, byte[] digest)
+ {
+ return Generate(digestAlgorithm.Id, digest);
+ }
+
+ public virtual TimeStampRequest Generate(DerObjectIdentifier digestAlgorithm, byte[] digest, BigInteger nonce)
+ {
+ return Generate(digestAlgorithm.Id, digest, nonce);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampRequestGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampRequestGenerator.cs.meta
new file mode 100644
index 00000000..8e1f720f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampRequestGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 1cb85a8797248f249a9b03c64d756801
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampResponse.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampResponse.cs
new file mode 100644
index 00000000..5897c59c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampResponse.cs
@@ -0,0 +1,188 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Tsp;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tsp
+{
+ /**
+ * Base class for an RFC 3161 Time Stamp Response object.
+ */
+ public class TimeStampResponse
+ {
+ private TimeStampResp resp;
+ private TimeStampToken timeStampToken;
+
+ public TimeStampResponse(
+ TimeStampResp resp)
+ {
+ this.resp = resp;
+
+ if (resp.TimeStampToken != null)
+ {
+ timeStampToken = new TimeStampToken(resp.TimeStampToken);
+ }
+ }
+
+ /**
+ * Create a TimeStampResponse from a byte array containing an ASN.1 encoding.
+ *
+ * @param resp the byte array containing the encoded response.
+ * @throws TspException if the response is malformed.
+ * @throws IOException if the byte array doesn't represent an ASN.1 encoding.
+ */
+ public TimeStampResponse(
+ byte[] resp)
+ : this(readTimeStampResp(new Asn1InputStream(resp)))
+ {
+ }
+
+ /**
+ * Create a TimeStampResponse from an input stream containing an ASN.1 encoding.
+ *
+ * @param input the input stream containing the encoded response.
+ * @throws TspException if the response is malformed.
+ * @throws IOException if the stream doesn't represent an ASN.1 encoding.
+ */
+ public TimeStampResponse(
+ Stream input)
+ : this(readTimeStampResp(new Asn1InputStream(input)))
+ {
+ }
+
+ private static TimeStampResp readTimeStampResp(
+ Asn1InputStream input)
+ {
+ try
+ {
+ return TimeStampResp.GetInstance(input.ReadObject());
+ }
+ catch (ArgumentException e)
+ {
+ throw new TspException("malformed timestamp response: " + e, e);
+ }
+ catch (InvalidCastException e)
+ {
+ throw new TspException("malformed timestamp response: " + e, e);
+ }
+ }
+
+ public int Status
+ {
+ get { return resp.Status.Status.IntValue; }
+ }
+
+ public string GetStatusString()
+ {
+ if (resp.Status.StatusString == null)
+ {
+ return null;
+ }
+
+ StringBuilder statusStringBuf = new StringBuilder();
+ PkiFreeText text = resp.Status.StatusString;
+ for (int i = 0; i != text.Count; i++)
+ {
+ statusStringBuf.Append(text[i].GetString());
+ }
+
+ return statusStringBuf.ToString();
+ }
+
+ public PkiFailureInfo GetFailInfo()
+ {
+ if (resp.Status.FailInfo == null)
+ {
+ return null;
+ }
+
+ return new PkiFailureInfo(resp.Status.FailInfo);
+ }
+
+ public TimeStampToken TimeStampToken
+ {
+ get { return timeStampToken; }
+ }
+
+ /**
+ * Check this response against to see if it a well formed response for
+ * the passed in request. Validation will include checking the time stamp
+ * token if the response status is GRANTED or GRANTED_WITH_MODS.
+ *
+ * @param request the request to be checked against
+ * @throws TspException if the request can not match this response.
+ */
+ public void Validate(
+ TimeStampRequest request)
+ {
+ TimeStampToken tok = this.TimeStampToken;
+
+ if (tok != null)
+ {
+ TimeStampTokenInfo tstInfo = tok.TimeStampInfo;
+
+ if (request.Nonce != null && !request.Nonce.Equals(tstInfo.Nonce))
+ {
+ throw new TspValidationException("response contains wrong nonce value.");
+ }
+
+ if (this.Status != (int) PkiStatus.Granted && this.Status != (int) PkiStatus.GrantedWithMods)
+ {
+ throw new TspValidationException("time stamp token found in failed request.");
+ }
+
+ if (!Arrays.ConstantTimeAreEqual(request.GetMessageImprintDigest(), tstInfo.GetMessageImprintDigest()))
+ {
+ throw new TspValidationException("response for different message imprint digest.");
+ }
+
+ if (!tstInfo.MessageImprintAlgOid.Equals(request.MessageImprintAlgOid))
+ {
+ throw new TspValidationException("response for different message imprint algorithm.");
+ }
+
+ Asn1.Cms.Attribute scV1 = tok.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificate];
+ Asn1.Cms.Attribute scV2 = tok.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificateV2];
+
+ if (scV1 == null && scV2 == null)
+ {
+ throw new TspValidationException("no signing certificate attribute present.");
+ }
+
+ if (scV1 != null && scV2 != null)
+ {
+ /*
+ * RFC 5035 5.4. If both attributes exist in a single message,
+ * they are independently evaluated.
+ */
+ }
+
+ if (request.ReqPolicy != null && !request.ReqPolicy.Equals(tstInfo.Policy))
+ {
+ throw new TspValidationException("TSA policy wrong for request.");
+ }
+ }
+ else if (this.Status == (int) PkiStatus.Granted || this.Status == (int) PkiStatus.GrantedWithMods)
+ {
+ throw new TspValidationException("no time stamp token found and one expected.");
+ }
+ }
+
+ /**
+ * return the ASN.1 encoded representation of this object.
+ */
+ public byte[] GetEncoded()
+ {
+ return resp.GetEncoded();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampResponse.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampResponse.cs.meta
new file mode 100644
index 00000000..e965991a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampResponse.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0b7d9336b3bad4448a81aa956426c6d9
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampResponseGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampResponseGenerator.cs
new file mode 100644
index 00000000..21b170bd
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampResponseGenerator.cs
@@ -0,0 +1,213 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Tsp;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Date;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tsp
+{
+ /**
+ * Generator for RFC 3161 Time Stamp Responses.
+ */
+ public class TimeStampResponseGenerator
+ {
+ private PkiStatus status;
+
+ private Asn1EncodableVector statusStrings;
+
+ private int failInfo;
+ private TimeStampTokenGenerator tokenGenerator;
+ private IList acceptedAlgorithms;
+ private IList acceptedPolicies;
+ private IList acceptedExtensions;
+
+ public TimeStampResponseGenerator(
+ TimeStampTokenGenerator tokenGenerator,
+ IList acceptedAlgorithms)
+ : this(tokenGenerator, acceptedAlgorithms, null, null)
+ {
+ }
+
+ public TimeStampResponseGenerator(
+ TimeStampTokenGenerator tokenGenerator,
+ IList acceptedAlgorithms,
+ IList acceptedPolicy)
+ : this(tokenGenerator, acceptedAlgorithms, acceptedPolicy, null)
+ {
+ }
+
+ public TimeStampResponseGenerator(
+ TimeStampTokenGenerator tokenGenerator,
+ IList acceptedAlgorithms,
+ IList acceptedPolicies,
+ IList acceptedExtensions)
+ {
+ this.tokenGenerator = tokenGenerator;
+ this.acceptedAlgorithms = acceptedAlgorithms;
+ this.acceptedPolicies = acceptedPolicies;
+ this.acceptedExtensions = acceptedExtensions;
+
+ statusStrings = new Asn1EncodableVector();
+ }
+
+ private void AddStatusString(string statusString)
+ {
+ statusStrings.Add(new DerUtf8String(statusString));
+ }
+
+ private void SetFailInfoField(int field)
+ {
+ failInfo |= field;
+ }
+
+ private PkiStatusInfo GetPkiStatusInfo()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector(
+ new DerInteger((int)status));
+
+ if (statusStrings.Count > 0)
+ {
+ v.Add(new PkiFreeText(new DerSequence(statusStrings)));
+ }
+
+ if (failInfo != 0)
+ {
+ v.Add(new FailInfo(failInfo));
+ }
+
+ return new PkiStatusInfo(new DerSequence(v));
+ }
+
+ public TimeStampResponse Generate(
+ TimeStampRequest request,
+ BigInteger serialNumber,
+ DateTime genTime)
+ {
+ return Generate(request, serialNumber, new DateTimeObject(genTime));
+ }
+
+ /**
+ * Return an appropriate TimeStampResponse.
+ *
+ * If genTime is null a timeNotAvailable error response will be returned.
+ *
+ * @param request the request this response is for.
+ * @param serialNumber serial number for the response token.
+ * @param genTime generation time for the response token.
+ * @param provider provider to use for signature calculation.
+ * @return
+ * @throws NoSuchAlgorithmException
+ * @throws NoSuchProviderException
+ * @throws TSPException
+ *
+ */
+ public TimeStampResponse Generate(
+ TimeStampRequest request,
+ BigInteger serialNumber,
+ DateTimeObject genTime)
+ {
+ TimeStampResp resp;
+
+ try
+ {
+ if (genTime == null)
+ throw new TspValidationException("The time source is not available.",
+ PkiFailureInfo.TimeNotAvailable);
+
+ request.Validate(acceptedAlgorithms, acceptedPolicies, acceptedExtensions);
+
+ this.status = PkiStatus.Granted;
+ this.AddStatusString("Operation Okay");
+
+ PkiStatusInfo pkiStatusInfo = GetPkiStatusInfo();
+
+ ContentInfo tstTokenContentInfo;
+ try
+ {
+ TimeStampToken token = tokenGenerator.Generate(request, serialNumber, genTime.Value);
+ byte[] encoded = token.ToCmsSignedData().GetEncoded();
+
+ tstTokenContentInfo = ContentInfo.GetInstance(Asn1Object.FromByteArray(encoded));
+ }
+ catch (IOException e)
+ {
+ throw new TspException("Timestamp token received cannot be converted to ContentInfo", e);
+ }
+
+ resp = new TimeStampResp(pkiStatusInfo, tstTokenContentInfo);
+ }
+ catch (TspValidationException e)
+ {
+ status = PkiStatus.Rejection;
+
+ this.SetFailInfoField(e.FailureCode);
+ this.AddStatusString(e.Message);
+
+ PkiStatusInfo pkiStatusInfo = GetPkiStatusInfo();
+
+ resp = new TimeStampResp(pkiStatusInfo, null);
+ }
+
+ try
+ {
+ return new TimeStampResponse(resp);
+ }
+ catch (IOException e)
+ {
+ throw new TspException("created badly formatted response!", e);
+ }
+ }
+
+ class FailInfo
+ : DerBitString
+ {
+ internal FailInfo(int failInfoValue)
+ : base(failInfoValue)
+ {
+ }
+ }
+
+ /**
+ * Generate a TimeStampResponse with chosen status and FailInfoField.
+ *
+ * @param status the PKIStatus to set.
+ * @param failInfoField the FailInfoField to set.
+ * @param statusString an optional string describing the failure.
+ * @return a TimeStampResponse with a failInfoField and optional statusString
+ * @throws TSPException in case the response could not be created
+ */
+ public TimeStampResponse GenerateFailResponse(PkiStatus status, int failInfoField, string statusString)
+ {
+ this.status = status;
+
+ this.SetFailInfoField(failInfoField);
+
+ if (statusString != null)
+ {
+ this.AddStatusString(statusString);
+ }
+
+ PkiStatusInfo pkiStatusInfo = GetPkiStatusInfo();
+
+ TimeStampResp resp = new TimeStampResp(pkiStatusInfo, null);
+
+ try
+ {
+ return new TimeStampResponse(resp);
+ }
+ catch (IOException e)
+ {
+ throw new TspException("created badly formatted response!", e);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampResponseGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampResponseGenerator.cs.meta
new file mode 100644
index 00000000..b0393288
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampResponseGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 31244340abddb5d4ca611f3cc612ee24
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampToken.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampToken.cs
new file mode 100644
index 00000000..02bc29d3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampToken.cs
@@ -0,0 +1,309 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Ess;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Oiw;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Tsp;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Cms;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tsp
+{
+ public class TimeStampToken
+ {
+ private readonly CmsSignedData tsToken;
+ private readonly SignerInformation tsaSignerInfo;
+// private readonly DateTime genTime;
+ private readonly TimeStampTokenInfo tstInfo;
+ private readonly CertID certID;
+
+ public TimeStampToken(
+ Asn1.Cms.ContentInfo contentInfo)
+ : this(new CmsSignedData(contentInfo))
+ {
+ }
+
+ public TimeStampToken(
+ CmsSignedData signedData)
+ {
+ this.tsToken = signedData;
+
+ if (!this.tsToken.SignedContentType.Equals(PkcsObjectIdentifiers.IdCTTstInfo))
+ {
+ throw new TspValidationException("ContentInfo object not for a time stamp.");
+ }
+
+ ICollection signers = tsToken.GetSignerInfos().GetSigners();
+
+ if (signers.Count != 1)
+ {
+ throw new ArgumentException("Time-stamp token signed by "
+ + signers.Count
+ + " signers, but it must contain just the TSA signature.");
+ }
+
+
+ IEnumerator signerEnum = signers.GetEnumerator();
+
+ signerEnum.MoveNext();
+ tsaSignerInfo = (SignerInformation) signerEnum.Current;
+
+ try
+ {
+ CmsProcessable content = tsToken.SignedContent;
+ MemoryStream bOut = new MemoryStream();
+
+ content.Write(bOut);
+
+ this.tstInfo = new TimeStampTokenInfo(
+ TstInfo.GetInstance(
+ Asn1Object.FromByteArray(bOut.ToArray())));
+
+ Asn1.Cms.Attribute attr = tsaSignerInfo.SignedAttributes[
+ PkcsObjectIdentifiers.IdAASigningCertificate];
+
+// if (attr == null)
+// {
+// throw new TspValidationException(
+// "no signing certificate attribute found, time stamp invalid.");
+// }
+//
+// SigningCertificate signCert = SigningCertificate.GetInstance(
+// attr.AttrValues[0]);
+//
+// this.certID = EssCertID.GetInstance(signCert.GetCerts()[0]);
+
+ if (attr != null)
+ {
+ SigningCertificate signCert = SigningCertificate.GetInstance(attr.AttrValues[0]);
+
+ this.certID = new CertID(EssCertID.GetInstance(signCert.GetCerts()[0]));
+ }
+ else
+ {
+ attr = tsaSignerInfo.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificateV2];
+
+ if (attr == null)
+ throw new TspValidationException("no signing certificate attribute found, time stamp invalid.");
+
+ SigningCertificateV2 signCertV2 = SigningCertificateV2.GetInstance(attr.AttrValues[0]);
+
+ this.certID = new CertID(EssCertIDv2.GetInstance(signCertV2.GetCerts()[0]));
+ }
+ }
+ catch (CmsException e)
+ {
+ throw new TspException(e.Message, e.InnerException);
+ }
+ }
+
+ public TimeStampTokenInfo TimeStampInfo
+ {
+ get { return tstInfo; }
+ }
+
+ public SignerID SignerID
+ {
+ get { return tsaSignerInfo.SignerID; }
+ }
+
+ public Asn1.Cms.AttributeTable SignedAttributes
+ {
+ get { return tsaSignerInfo.SignedAttributes; }
+ }
+
+ public Asn1.Cms.AttributeTable UnsignedAttributes
+ {
+ get { return tsaSignerInfo.UnsignedAttributes; }
+ }
+
+ public IX509Store GetCertificates(
+ string type)
+ {
+ return tsToken.GetCertificates(type);
+ }
+
+ public IX509Store GetCrls(
+ string type)
+ {
+ return tsToken.GetCrls(type);
+ }
+
+ public IX509Store GetAttributeCertificates(
+ string type)
+ {
+ return tsToken.GetAttributeCertificates(type);
+ }
+
+ /**
+ * Validate the time stamp token.
+ *
+ * To be valid the token must be signed by the passed in certificate and
+ * the certificate must be the one referred to by the SigningCertificate
+ * attribute included in the hashed attributes of the token. The
+ * certificate must also have the ExtendedKeyUsageExtension with only
+ * KeyPurposeID.IdKPTimeStamping and have been valid at the time the
+ * timestamp was created.
+ *
+ *
+ * A successful call to validate means all the above are true.
+ *
+ */
+ public void Validate(
+ X509Certificate cert)
+ {
+ try
+ {
+ byte[] hash = DigestUtilities.CalculateDigest(
+ certID.GetHashAlgorithmName(), cert.GetEncoded());
+
+ if (!Arrays.ConstantTimeAreEqual(certID.GetCertHash(), hash))
+ {
+ throw new TspValidationException("certificate hash does not match certID hash.");
+ }
+
+ if (certID.IssuerSerial != null)
+ {
+ if (!certID.IssuerSerial.Serial.Value.Equals(cert.SerialNumber))
+ {
+ throw new TspValidationException("certificate serial number does not match certID for signature.");
+ }
+
+ GeneralName[] names = certID.IssuerSerial.Issuer.GetNames();
+ X509Name principal = PrincipalUtilities.GetIssuerX509Principal(cert);
+ bool found = false;
+
+ for (int i = 0; i != names.Length; i++)
+ {
+ if (names[i].TagNo == 4
+ && X509Name.GetInstance(names[i].Name).Equivalent(principal))
+ {
+ found = true;
+ break;
+ }
+ }
+
+ if (!found)
+ {
+ throw new TspValidationException("certificate name does not match certID for signature. ");
+ }
+ }
+
+ TspUtil.ValidateCertificate(cert);
+
+ cert.CheckValidity(tstInfo.GenTime);
+
+ if (!tsaSignerInfo.Verify(cert))
+ {
+ throw new TspValidationException("signature not created by certificate.");
+ }
+ }
+ catch (CmsException e)
+ {
+ if (e.InnerException != null)
+ {
+ throw new TspException(e.Message, e.InnerException);
+ }
+
+ throw new TspException("CMS exception: " + e, e);
+ }
+ catch (CertificateEncodingException e)
+ {
+ throw new TspException("problem processing certificate: " + e, e);
+ }
+ catch (SecurityUtilityException e)
+ {
+ throw new TspException("cannot find algorithm: " + e.Message, e);
+ }
+ }
+
+ /**
+ * Return the underlying CmsSignedData object.
+ *
+ * @return the underlying CMS structure.
+ */
+ public CmsSignedData ToCmsSignedData()
+ {
+ return tsToken;
+ }
+
+ /**
+ * Return a ASN.1 encoded byte stream representing the encoded object.
+ *
+ * @throws IOException if encoding fails.
+ */
+ public byte[] GetEncoded()
+ {
+ return tsToken.GetEncoded();
+ }
+
+
+ // perhaps this should be done using an interface on the ASN.1 classes...
+ private class CertID
+ {
+ private EssCertID certID;
+ private EssCertIDv2 certIDv2;
+
+ internal CertID(EssCertID certID)
+ {
+ this.certID = certID;
+ this.certIDv2 = null;
+ }
+
+ internal CertID(EssCertIDv2 certID)
+ {
+ this.certIDv2 = certID;
+ this.certID = null;
+ }
+
+ public string GetHashAlgorithmName()
+ {
+ if (certID != null)
+ return "SHA-1";
+
+ if (NistObjectIdentifiers.IdSha256.Equals(certIDv2.HashAlgorithm.Algorithm))
+ return "SHA-256";
+
+ return certIDv2.HashAlgorithm.Algorithm.Id;
+ }
+
+ public AlgorithmIdentifier GetHashAlgorithm()
+ {
+ return (certID != null)
+ ? new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1)
+ : certIDv2.HashAlgorithm;
+ }
+
+ public byte[] GetCertHash()
+ {
+ return certID != null
+ ? certID.GetCertHash()
+ : certIDv2.GetCertHash();
+ }
+
+ public IssuerSerial IssuerSerial
+ {
+ get
+ {
+ return certID != null
+ ? certID.IssuerSerial
+ : certIDv2.IssuerSerial;
+ }
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampToken.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampToken.cs.meta
new file mode 100644
index 00000000..c198a606
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampToken.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: e001862fca691964183bd415e4c373b9
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampTokenGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampTokenGenerator.cs
new file mode 100644
index 00000000..f769f5cb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampTokenGenerator.cs
@@ -0,0 +1,249 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Ess;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Tsp;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Cms;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tsp
+{
+ public class TimeStampTokenGenerator
+ {
+ private int accuracySeconds = -1;
+ private int accuracyMillis = -1;
+ private int accuracyMicros = -1;
+ private bool ordering = false;
+ private GeneralName tsa = null;
+ private string tsaPolicyOID;
+
+ private AsymmetricKeyParameter key;
+ private X509Certificate cert;
+ private string digestOID;
+ private Asn1.Cms.AttributeTable signedAttr;
+ private Asn1.Cms.AttributeTable unsignedAttr;
+ private IX509Store x509Certs;
+ private IX509Store x509Crls;
+
+ /**
+ * basic creation - only the default attributes will be included here.
+ */
+ public TimeStampTokenGenerator(
+ AsymmetricKeyParameter key,
+ X509Certificate cert,
+ string digestOID,
+ string tsaPolicyOID)
+ : this(key, cert, digestOID, tsaPolicyOID, null, null)
+ {
+ }
+
+ /**
+ * create with a signer with extra signed/unsigned attributes.
+ */
+ public TimeStampTokenGenerator(
+ AsymmetricKeyParameter key,
+ X509Certificate cert,
+ string digestOID,
+ string tsaPolicyOID,
+ Asn1.Cms.AttributeTable signedAttr,
+ Asn1.Cms.AttributeTable unsignedAttr)
+ {
+ this.key = key;
+ this.cert = cert;
+ this.digestOID = digestOID;
+ this.tsaPolicyOID = tsaPolicyOID;
+ this.unsignedAttr = unsignedAttr;
+
+ TspUtil.ValidateCertificate(cert);
+
+ //
+ // Add the ESSCertID attribute
+ //
+ IDictionary signedAttrs;
+ if (signedAttr != null)
+ {
+ signedAttrs = signedAttr.ToDictionary();
+ }
+ else
+ {
+ signedAttrs = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ }
+
+ try
+ {
+ byte[] hash = DigestUtilities.CalculateDigest("SHA-1", cert.GetEncoded());
+
+ EssCertID essCertid = new EssCertID(hash);
+
+ Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(
+ PkcsObjectIdentifiers.IdAASigningCertificate,
+ new DerSet(new SigningCertificate(essCertid)));
+
+ signedAttrs[attr.AttrType] = attr;
+ }
+ catch (CertificateEncodingException e)
+ {
+ throw new TspException("Exception processing certificate.", e);
+ }
+ catch (SecurityUtilityException e)
+ {
+ throw new TspException("Can't find a SHA-1 implementation.", e);
+ }
+
+ this.signedAttr = new Asn1.Cms.AttributeTable(signedAttrs);
+ }
+
+ public void SetCertificates(
+ IX509Store certificates)
+ {
+ this.x509Certs = certificates;
+ }
+
+ public void SetCrls(
+ IX509Store crls)
+ {
+ this.x509Crls = crls;
+ }
+
+ public void SetAccuracySeconds(
+ int accuracySeconds)
+ {
+ this.accuracySeconds = accuracySeconds;
+ }
+
+ public void SetAccuracyMillis(
+ int accuracyMillis)
+ {
+ this.accuracyMillis = accuracyMillis;
+ }
+
+ public void SetAccuracyMicros(
+ int accuracyMicros)
+ {
+ this.accuracyMicros = accuracyMicros;
+ }
+
+ public void SetOrdering(
+ bool ordering)
+ {
+ this.ordering = ordering;
+ }
+
+ public void SetTsa(
+ GeneralName tsa)
+ {
+ this.tsa = tsa;
+ }
+
+ //------------------------------------------------------------------------------
+
+ public TimeStampToken Generate(
+ TimeStampRequest request,
+ BigInteger serialNumber,
+ DateTime genTime)
+ {
+ DerObjectIdentifier digestAlgOID = new DerObjectIdentifier(request.MessageImprintAlgOid);
+
+ AlgorithmIdentifier algID = new AlgorithmIdentifier(digestAlgOID, DerNull.Instance);
+ MessageImprint messageImprint = new MessageImprint(algID, request.GetMessageImprintDigest());
+
+ Accuracy accuracy = null;
+ if (accuracySeconds > 0 || accuracyMillis > 0 || accuracyMicros > 0)
+ {
+ DerInteger seconds = null;
+ if (accuracySeconds > 0)
+ {
+ seconds = new DerInteger(accuracySeconds);
+ }
+
+ DerInteger millis = null;
+ if (accuracyMillis > 0)
+ {
+ millis = new DerInteger(accuracyMillis);
+ }
+
+ DerInteger micros = null;
+ if (accuracyMicros > 0)
+ {
+ micros = new DerInteger(accuracyMicros);
+ }
+
+ accuracy = new Accuracy(seconds, millis, micros);
+ }
+
+ DerBoolean derOrdering = null;
+ if (ordering)
+ {
+ derOrdering = DerBoolean.GetInstance(ordering);
+ }
+
+ DerInteger nonce = null;
+ if (request.Nonce != null)
+ {
+ nonce = new DerInteger(request.Nonce);
+ }
+
+ DerObjectIdentifier tsaPolicy = new DerObjectIdentifier(tsaPolicyOID);
+ if (request.ReqPolicy != null)
+ {
+ tsaPolicy = new DerObjectIdentifier(request.ReqPolicy);
+ }
+
+ TstInfo tstInfo = new TstInfo(tsaPolicy, messageImprint,
+ new DerInteger(serialNumber), new DerGeneralizedTime(genTime), accuracy,
+ derOrdering, nonce, tsa, request.Extensions);
+
+ try
+ {
+ CmsSignedDataGenerator signedDataGenerator = new CmsSignedDataGenerator();
+
+ byte[] derEncodedTstInfo = tstInfo.GetDerEncoded();
+
+ if (request.CertReq)
+ {
+ signedDataGenerator.AddCertificates(x509Certs);
+ }
+
+ signedDataGenerator.AddCrls(x509Crls);
+ signedDataGenerator.AddSigner(key, cert, digestOID, signedAttr, unsignedAttr);
+
+ CmsSignedData signedData = signedDataGenerator.Generate(
+ PkcsObjectIdentifiers.IdCTTstInfo.Id,
+ new CmsProcessableByteArray(derEncodedTstInfo),
+ true);
+
+ return new TimeStampToken(signedData);
+ }
+ catch (CmsException cmsEx)
+ {
+ throw new TspException("Error generating time-stamp token", cmsEx);
+ }
+ catch (IOException e)
+ {
+ throw new TspException("Exception encoding info", e);
+ }
+ catch (X509StoreException e)
+ {
+ throw new TspException("Exception handling CertStore", e);
+ }
+// catch (InvalidAlgorithmParameterException e)
+// {
+// throw new TspException("Exception handling CertStore CRLs", e);
+// }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampTokenGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampTokenGenerator.cs.meta
new file mode 100644
index 00000000..b2c1d5e8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampTokenGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 9d1991286d37694478ba89a7c392c9bb
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampTokenInfo.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampTokenInfo.cs
new file mode 100644
index 00000000..16d26df2
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampTokenInfo.cs
@@ -0,0 +1,111 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Tsp;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tsp
+{
+ public class TimeStampTokenInfo
+ {
+ private TstInfo tstInfo;
+ private DateTime genTime;
+
+ public TimeStampTokenInfo(
+ TstInfo tstInfo)
+ {
+ this.tstInfo = tstInfo;
+
+ try
+ {
+ this.genTime = tstInfo.GenTime.ToDateTime();
+ }
+ catch (Exception e)
+ {
+ throw new TspException("unable to parse genTime field: " + e.Message);
+ }
+ }
+
+ public bool IsOrdered
+ {
+ get { return tstInfo.Ordering.IsTrue; }
+ }
+
+ public Accuracy Accuracy
+ {
+ get { return tstInfo.Accuracy; }
+ }
+
+ public DateTime GenTime
+ {
+ get { return genTime; }
+ }
+
+ public GenTimeAccuracy GenTimeAccuracy
+ {
+ get
+ {
+ return this.Accuracy == null
+ ? null
+ : new GenTimeAccuracy(this.Accuracy);
+ }
+ }
+
+ public string Policy
+ {
+ get { return tstInfo.Policy.Id; }
+ }
+
+ public BigInteger SerialNumber
+ {
+ get { return tstInfo.SerialNumber.Value; }
+ }
+
+ public GeneralName Tsa
+ {
+ get { return tstInfo.Tsa; }
+ }
+
+ /**
+ * @return the nonce value, null if there isn't one.
+ */
+ public BigInteger Nonce
+ {
+ get
+ {
+ return tstInfo.Nonce == null
+ ? null
+ : tstInfo.Nonce.Value;
+ }
+ }
+
+ public AlgorithmIdentifier HashAlgorithm
+ {
+ get { return tstInfo.MessageImprint.HashAlgorithm; }
+ }
+
+ public string MessageImprintAlgOid
+ {
+ get { return tstInfo.MessageImprint.HashAlgorithm.Algorithm.Id; }
+ }
+
+ public byte[] GetMessageImprintDigest()
+ {
+ return tstInfo.MessageImprint.GetHashedMessage();
+ }
+
+ public byte[] GetEncoded()
+ {
+ return tstInfo.GetEncoded();
+ }
+
+ public TstInfo TstInfo
+ {
+ get { return tstInfo; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampTokenInfo.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampTokenInfo.cs.meta
new file mode 100644
index 00000000..e5b6969e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/tsp/TimeStampTokenInfo.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: bb197672beb7bd749971431ab1bb00bf
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util.meta
new file mode 100644
index 00000000..d3cc9ad7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: ba5cad752407f8545a6d90f346edc648
+folderAsset: yes
+DefaultImporter:
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Arrays.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Arrays.cs
new file mode 100644
index 00000000..0200ce8a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Arrays.cs
@@ -0,0 +1,729 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities
+{
+ /// General array utilities.
+ public abstract class Arrays
+ {
+ public static readonly byte[] EmptyBytes = new byte[0];
+ public static readonly int[] EmptyInts = new int[0];
+
+ public static bool AreAllZeroes(byte[] buf, int off, int len)
+ {
+ uint bits = 0;
+ for (int i = 0; i < len; ++i)
+ {
+ bits |= buf[off + i];
+ }
+ return bits == 0;
+ }
+
+ public static bool AreEqual(
+ bool[] a,
+ bool[] b)
+ {
+ if (a == b)
+ return true;
+
+ if (a == null || b == null)
+ return false;
+
+ return HaveSameContents(a, b);
+ }
+
+ public static bool AreEqual(
+ char[] a,
+ char[] b)
+ {
+ if (a == b)
+ return true;
+
+ if (a == null || b == null)
+ return false;
+
+ return HaveSameContents(a, b);
+ }
+
+ ///
+ /// Are two arrays equal.
+ ///
+ /// Left side.
+ /// Right side.
+ /// True if equal.
+ public static bool AreEqual(
+ byte[] a,
+ byte[] b)
+ {
+ if (a == b)
+ return true;
+
+ if (a == null || b == null)
+ return false;
+
+ return HaveSameContents(a, b);
+ }
+
+ [Obsolete("Use 'AreEqual' method instead")]
+ public static bool AreSame(
+ byte[] a,
+ byte[] b)
+ {
+ return AreEqual(a, b);
+ }
+
+ ///
+ /// A constant time equals comparison - does not terminate early if
+ /// test will fail.
+ ///
+ /// first array
+ /// second array
+ /// true if arrays equal, false otherwise.
+ public static bool ConstantTimeAreEqual(
+ byte[] a,
+ byte[] b)
+ {
+ int i = a.Length;
+ if (i != b.Length)
+ return false;
+ int cmp = 0;
+ while (i != 0)
+ {
+ --i;
+ cmp |= (a[i] ^ b[i]);
+ }
+ return cmp == 0;
+ }
+
+ public static bool AreEqual(
+ int[] a,
+ int[] b)
+ {
+ if (a == b)
+ return true;
+
+ if (a == null || b == null)
+ return false;
+
+ return HaveSameContents(a, b);
+ }
+
+ [CLSCompliantAttribute(false)]
+ public static bool AreEqual(uint[] a, uint[] b)
+ {
+ if (a == b)
+ return true;
+
+ if (a == null || b == null)
+ return false;
+
+ return HaveSameContents(a, b);
+ }
+
+ private static bool HaveSameContents(
+ bool[] a,
+ bool[] b)
+ {
+ int i = a.Length;
+ if (i != b.Length)
+ return false;
+ while (i != 0)
+ {
+ --i;
+ if (a[i] != b[i])
+ return false;
+ }
+ return true;
+ }
+
+ private static bool HaveSameContents(
+ char[] a,
+ char[] b)
+ {
+ int i = a.Length;
+ if (i != b.Length)
+ return false;
+ while (i != 0)
+ {
+ --i;
+ if (a[i] != b[i])
+ return false;
+ }
+ return true;
+ }
+
+ private static bool HaveSameContents(
+ byte[] a,
+ byte[] b)
+ {
+ int i = a.Length;
+ if (i != b.Length)
+ return false;
+ while (i != 0)
+ {
+ --i;
+ if (a[i] != b[i])
+ return false;
+ }
+ return true;
+ }
+
+ private static bool HaveSameContents(
+ int[] a,
+ int[] b)
+ {
+ int i = a.Length;
+ if (i != b.Length)
+ return false;
+ while (i != 0)
+ {
+ --i;
+ if (a[i] != b[i])
+ return false;
+ }
+ return true;
+ }
+
+ private static bool HaveSameContents(uint[] a, uint[] b)
+ {
+ int i = a.Length;
+ if (i != b.Length)
+ return false;
+ while (i != 0)
+ {
+ --i;
+ if (a[i] != b[i])
+ return false;
+ }
+ return true;
+ }
+
+ public static string ToString(
+ object[] a)
+ {
+ StringBuilder sb = new StringBuilder('[');
+ if (a.Length > 0)
+ {
+ sb.Append(a[0]);
+ for (int index = 1; index < a.Length; ++index)
+ {
+ sb.Append(", ").Append(a[index]);
+ }
+ }
+ sb.Append(']');
+ return sb.ToString();
+ }
+
+ public static int GetHashCode(byte[] data)
+ {
+ if (data == null)
+ {
+ return 0;
+ }
+
+ int i = data.Length;
+ int hc = i + 1;
+
+ while (--i >= 0)
+ {
+ hc *= 257;
+ hc ^= data[i];
+ }
+
+ return hc;
+ }
+
+ public static int GetHashCode(byte[] data, int off, int len)
+ {
+ if (data == null)
+ {
+ return 0;
+ }
+
+ int i = len;
+ int hc = i + 1;
+
+ while (--i >= 0)
+ {
+ hc *= 257;
+ hc ^= data[off + i];
+ }
+
+ return hc;
+ }
+
+ public static int GetHashCode(int[] data)
+ {
+ if (data == null)
+ return 0;
+
+ int i = data.Length;
+ int hc = i + 1;
+
+ while (--i >= 0)
+ {
+ hc *= 257;
+ hc ^= data[i];
+ }
+
+ return hc;
+ }
+
+ public static int GetHashCode(int[] data, int off, int len)
+ {
+ if (data == null)
+ return 0;
+
+ int i = len;
+ int hc = i + 1;
+
+ while (--i >= 0)
+ {
+ hc *= 257;
+ hc ^= data[off + i];
+ }
+
+ return hc;
+ }
+
+ [CLSCompliantAttribute(false)]
+ public static int GetHashCode(uint[] data)
+ {
+ if (data == null)
+ return 0;
+
+ int i = data.Length;
+ int hc = i + 1;
+
+ while (--i >= 0)
+ {
+ hc *= 257;
+ hc ^= (int)data[i];
+ }
+
+ return hc;
+ }
+
+ [CLSCompliantAttribute(false)]
+ public static int GetHashCode(uint[] data, int off, int len)
+ {
+ if (data == null)
+ return 0;
+
+ int i = len;
+ int hc = i + 1;
+
+ while (--i >= 0)
+ {
+ hc *= 257;
+ hc ^= (int)data[off + i];
+ }
+
+ return hc;
+ }
+
+ [CLSCompliantAttribute(false)]
+ public static int GetHashCode(ulong[] data)
+ {
+ if (data == null)
+ return 0;
+
+ int i = data.Length;
+ int hc = i + 1;
+
+ while (--i >= 0)
+ {
+ ulong di = data[i];
+ hc *= 257;
+ hc ^= (int)di;
+ hc *= 257;
+ hc ^= (int)(di >> 32);
+ }
+
+ return hc;
+ }
+
+ [CLSCompliantAttribute(false)]
+ public static int GetHashCode(ulong[] data, int off, int len)
+ {
+ if (data == null)
+ return 0;
+
+ int i = len;
+ int hc = i + 1;
+
+ while (--i >= 0)
+ {
+ ulong di = data[off + i];
+ hc *= 257;
+ hc ^= (int)di;
+ hc *= 257;
+ hc ^= (int)(di >> 32);
+ }
+
+ return hc;
+ }
+
+ public static byte[] Clone(
+ byte[] data)
+ {
+ return data == null ? null : (byte[])data.Clone();
+ }
+
+ public static byte[] Clone(
+ byte[] data,
+ byte[] existing)
+ {
+ if (data == null)
+ {
+ return null;
+ }
+ if ((existing == null) || (existing.Length != data.Length))
+ {
+ return Clone(data);
+ }
+ Array.Copy(data, 0, existing, 0, existing.Length);
+ return existing;
+ }
+
+ public static int[] Clone(
+ int[] data)
+ {
+ return data == null ? null : (int[])data.Clone();
+ }
+
+ internal static uint[] Clone(uint[] data)
+ {
+ return data == null ? null : (uint[])data.Clone();
+ }
+
+ public static long[] Clone(long[] data)
+ {
+ return data == null ? null : (long[])data.Clone();
+ }
+
+ [CLSCompliantAttribute(false)]
+ public static ulong[] Clone(
+ ulong[] data)
+ {
+ return data == null ? null : (ulong[]) data.Clone();
+ }
+
+ [CLSCompliantAttribute(false)]
+ public static ulong[] Clone(
+ ulong[] data,
+ ulong[] existing)
+ {
+ if (data == null)
+ {
+ return null;
+ }
+ if ((existing == null) || (existing.Length != data.Length))
+ {
+ return Clone(data);
+ }
+ Array.Copy(data, 0, existing, 0, existing.Length);
+ return existing;
+ }
+
+ public static bool Contains(byte[] a, byte n)
+ {
+ for (int i = 0; i < a.Length; ++i)
+ {
+ if (a[i] == n)
+ return true;
+ }
+ return false;
+ }
+
+ public static bool Contains(short[] a, short n)
+ {
+ for (int i = 0; i < a.Length; ++i)
+ {
+ if (a[i] == n)
+ return true;
+ }
+ return false;
+ }
+
+ public static bool Contains(int[] a, int n)
+ {
+ for (int i = 0; i < a.Length; ++i)
+ {
+ if (a[i] == n)
+ return true;
+ }
+ return false;
+ }
+
+ public static void Fill(
+ byte[] buf,
+ byte b)
+ {
+ int i = buf.Length;
+ while (i > 0)
+ {
+ buf[--i] = b;
+ }
+ }
+
+ public static void Fill(byte[] buf, int from, int to, byte b)
+ {
+ for (int i = from; i < to; ++i)
+ {
+ buf[i] = b;
+ }
+ }
+
+ public static byte[] CopyOf(byte[] data, int newLength)
+ {
+ byte[] tmp = new byte[newLength];
+ Array.Copy(data, 0, tmp, 0, System.Math.Min(newLength, data.Length));
+ return tmp;
+ }
+
+ public static char[] CopyOf(char[] data, int newLength)
+ {
+ char[] tmp = new char[newLength];
+ Array.Copy(data, 0, tmp, 0, System.Math.Min(newLength, data.Length));
+ return tmp;
+ }
+
+ public static int[] CopyOf(int[] data, int newLength)
+ {
+ int[] tmp = new int[newLength];
+ Array.Copy(data, 0, tmp, 0, System.Math.Min(newLength, data.Length));
+ return tmp;
+ }
+
+ public static long[] CopyOf(long[] data, int newLength)
+ {
+ long[] tmp = new long[newLength];
+ Array.Copy(data, 0, tmp, 0, System.Math.Min(newLength, data.Length));
+ return tmp;
+ }
+
+ public static BigInteger[] CopyOf(BigInteger[] data, int newLength)
+ {
+ BigInteger[] tmp = new BigInteger[newLength];
+ Array.Copy(data, 0, tmp, 0, System.Math.Min(newLength, data.Length));
+ return tmp;
+ }
+
+ /**
+ * Make a copy of a range of bytes from the passed in data array. The range can
+ * extend beyond the end of the input array, in which case the return array will
+ * be padded with zeroes.
+ *
+ * @param data the array from which the data is to be copied.
+ * @param from the start index at which the copying should take place.
+ * @param to the final index of the range (exclusive).
+ *
+ * @return a new byte array containing the range given.
+ */
+ public static byte[] CopyOfRange(byte[] data, int from, int to)
+ {
+ int newLength = GetLength(from, to);
+ byte[] tmp = new byte[newLength];
+ Array.Copy(data, from, tmp, 0, System.Math.Min(newLength, data.Length - from));
+ return tmp;
+ }
+
+ public static int[] CopyOfRange(int[] data, int from, int to)
+ {
+ int newLength = GetLength(from, to);
+ int[] tmp = new int[newLength];
+ Array.Copy(data, from, tmp, 0, System.Math.Min(newLength, data.Length - from));
+ return tmp;
+ }
+
+ public static long[] CopyOfRange(long[] data, int from, int to)
+ {
+ int newLength = GetLength(from, to);
+ long[] tmp = new long[newLength];
+ Array.Copy(data, from, tmp, 0, System.Math.Min(newLength, data.Length - from));
+ return tmp;
+ }
+
+ public static BigInteger[] CopyOfRange(BigInteger[] data, int from, int to)
+ {
+ int newLength = GetLength(from, to);
+ BigInteger[] tmp = new BigInteger[newLength];
+ Array.Copy(data, from, tmp, 0, System.Math.Min(newLength, data.Length - from));
+ return tmp;
+ }
+
+ private static int GetLength(int from, int to)
+ {
+ int newLength = to - from;
+ if (newLength < 0)
+ throw new ArgumentException(from + " > " + to);
+ return newLength;
+ }
+
+ public static byte[] Append(byte[] a, byte b)
+ {
+ if (a == null)
+ return new byte[] { b };
+
+ int length = a.Length;
+ byte[] result = new byte[length + 1];
+ Array.Copy(a, 0, result, 0, length);
+ result[length] = b;
+ return result;
+ }
+
+ public static short[] Append(short[] a, short b)
+ {
+ if (a == null)
+ return new short[] { b };
+
+ int length = a.Length;
+ short[] result = new short[length + 1];
+ Array.Copy(a, 0, result, 0, length);
+ result[length] = b;
+ return result;
+ }
+
+ public static int[] Append(int[] a, int b)
+ {
+ if (a == null)
+ return new int[] { b };
+
+ int length = a.Length;
+ int[] result = new int[length + 1];
+ Array.Copy(a, 0, result, 0, length);
+ result[length] = b;
+ return result;
+ }
+
+ public static byte[] Concatenate(byte[] a, byte[] b)
+ {
+ if (a == null)
+ return Clone(b);
+ if (b == null)
+ return Clone(a);
+
+ byte[] rv = new byte[a.Length + b.Length];
+ Array.Copy(a, 0, rv, 0, a.Length);
+ Array.Copy(b, 0, rv, a.Length, b.Length);
+ return rv;
+ }
+
+ public static byte[] ConcatenateAll(params byte[][] vs)
+ {
+ byte[][] nonNull = new byte[vs.Length][];
+ int count = 0;
+ int totalLength = 0;
+
+ for (int i = 0; i < vs.Length; ++i)
+ {
+ byte[] v = vs[i];
+ if (v != null)
+ {
+ nonNull[count++] = v;
+ totalLength += v.Length;
+ }
+ }
+
+ byte[] result = new byte[totalLength];
+ int pos = 0;
+
+ for (int j = 0; j < count; ++j)
+ {
+ byte[] v = nonNull[j];
+ Array.Copy(v, 0, result, pos, v.Length);
+ pos += v.Length;
+ }
+
+ return result;
+ }
+
+ public static int[] Concatenate(int[] a, int[] b)
+ {
+ if (a == null)
+ return Clone(b);
+ if (b == null)
+ return Clone(a);
+
+ int[] rv = new int[a.Length + b.Length];
+ Array.Copy(a, 0, rv, 0, a.Length);
+ Array.Copy(b, 0, rv, a.Length, b.Length);
+ return rv;
+ }
+
+ public static byte[] Prepend(byte[] a, byte b)
+ {
+ if (a == null)
+ return new byte[] { b };
+
+ int length = a.Length;
+ byte[] result = new byte[length + 1];
+ Array.Copy(a, 0, result, 1, length);
+ result[0] = b;
+ return result;
+ }
+
+ public static short[] Prepend(short[] a, short b)
+ {
+ if (a == null)
+ return new short[] { b };
+
+ int length = a.Length;
+ short[] result = new short[length + 1];
+ Array.Copy(a, 0, result, 1, length);
+ result[0] = b;
+ return result;
+ }
+
+ public static int[] Prepend(int[] a, int b)
+ {
+ if (a == null)
+ return new int[] { b };
+
+ int length = a.Length;
+ int[] result = new int[length + 1];
+ Array.Copy(a, 0, result, 1, length);
+ result[0] = b;
+ return result;
+ }
+
+ public static byte[] Reverse(byte[] a)
+ {
+ if (a == null)
+ return null;
+
+ int p1 = 0, p2 = a.Length;
+ byte[] result = new byte[p2];
+
+ while (--p2 >= 0)
+ {
+ result[p2] = a[p1++];
+ }
+
+ return result;
+ }
+
+ public static int[] Reverse(int[] a)
+ {
+ if (a == null)
+ return null;
+
+ int p1 = 0, p2 = a.Length;
+ int[] result = new int[p2];
+
+ while (--p2 >= 0)
+ {
+ result[p2] = a[p1++];
+ }
+
+ return result;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Arrays.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Arrays.cs.meta
new file mode 100644
index 00000000..0b64de1a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Arrays.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 5ba8c42c46160a54db30a3ddfae9ed76
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/BigIntegers.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/BigIntegers.cs
new file mode 100644
index 00000000..659648c5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/BigIntegers.cs
@@ -0,0 +1,99 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities
+{
+ /**
+ * BigInteger utilities.
+ */
+ public abstract class BigIntegers
+ {
+ private const int MaxIterations = 1000;
+
+ /**
+ * Return the passed in value as an unsigned byte array.
+ *
+ * @param value value to be converted.
+ * @return a byte array without a leading zero byte if present in the signed encoding.
+ */
+ public static byte[] AsUnsignedByteArray(
+ BigInteger n)
+ {
+ return n.ToByteArrayUnsigned();
+ }
+
+ /**
+ * Return the passed in value as an unsigned byte array of specified length, zero-extended as necessary.
+ *
+ * @param length desired length of result array.
+ * @param n value to be converted.
+ * @return a byte array of specified length, with leading zeroes as necessary given the size of n.
+ */
+ public static byte[] AsUnsignedByteArray(int length, BigInteger n)
+ {
+ byte[] bytes = n.ToByteArrayUnsigned();
+
+ if (bytes.Length > length)
+ throw new ArgumentException("standard length exceeded", "n");
+
+ if (bytes.Length == length)
+ return bytes;
+
+ byte[] tmp = new byte[length];
+ Array.Copy(bytes, 0, tmp, tmp.Length - bytes.Length, bytes.Length);
+ return tmp;
+ }
+
+ /**
+ * Return a random BigInteger not less than 'min' and not greater than 'max'
+ *
+ * @param min the least value that may be generated
+ * @param max the greatest value that may be generated
+ * @param random the source of randomness
+ * @return a random BigInteger value in the range [min,max]
+ */
+ public static BigInteger CreateRandomInRange(
+ BigInteger min,
+ BigInteger max,
+ // TODO Should have been just Random class
+ SecureRandom random)
+ {
+ int cmp = min.CompareTo(max);
+ if (cmp >= 0)
+ {
+ if (cmp > 0)
+ throw new ArgumentException("'min' may not be greater than 'max'");
+
+ return min;
+ }
+
+ if (min.BitLength > max.BitLength / 2)
+ {
+ return CreateRandomInRange(BigInteger.Zero, max.Subtract(min), random).Add(min);
+ }
+
+ for (int i = 0; i < MaxIterations; ++i)
+ {
+ BigInteger x = new BigInteger(max.BitLength, random);
+ if (x.CompareTo(min) >= 0 && x.CompareTo(max) <= 0)
+ {
+ return x;
+ }
+ }
+
+ // fall back to a faster (restricted) method
+ return new BigInteger(max.Subtract(min).BitLength - 1, random).Add(min);
+ }
+
+ public static int GetUnsignedByteLength(BigInteger n)
+ {
+ return (n.BitLength + 7) / 8;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/BigIntegers.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/BigIntegers.cs.meta
new file mode 100644
index 00000000..54f519bb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/BigIntegers.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ebdb832f8f30d6c44a1a40e88b4f3b17
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Enums.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Enums.cs
new file mode 100644
index 00000000..e48c588d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Enums.cs
@@ -0,0 +1,82 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Text;
+
+#if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE
+using System.Collections;
+using System.Reflection;
+#endif
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Date;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities
+{
+ internal abstract class Enums
+ {
+ internal static Enum GetEnumValue(System.Type enumType, string s)
+ {
+ if (!IsEnumType(enumType))
+ throw new ArgumentException("Not an enumeration type", "enumType");
+
+ // We only want to parse single named constants
+ if (s.Length > 0 && char.IsLetter(s[0]) && s.IndexOf(',') < 0)
+ {
+ s = s.Replace('-', '_');
+ s = s.Replace('/', '_');
+
+#if NETCF_1_0
+ FieldInfo field = enumType.GetField(s, BindingFlags.Static | BindingFlags.Public);
+ if (field != null)
+ {
+ return (Enum)field.GetValue(null);
+ }
+#else
+ return (Enum)Enum.Parse(enumType, s, false);
+#endif
+ }
+
+ throw new ArgumentException();
+ }
+
+ internal static Array GetEnumValues(System.Type enumType)
+ {
+ if (!IsEnumType(enumType))
+ throw new ArgumentException("Not an enumeration type", "enumType");
+
+#if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT
+ IList result = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ FieldInfo[] fields = enumType.GetFields(BindingFlags.Static | BindingFlags.Public);
+ foreach (FieldInfo field in fields)
+ {
+ // Note: Argument to GetValue() ignored since the fields are static,
+ // but Silverlight for Windows Phone throws exception if we pass null
+ result.Add(field.GetValue(enumType));
+ }
+ object[] arr = new object[result.Count];
+ result.CopyTo(arr, 0);
+ return arr;
+#else
+ return Enum.GetValues(enumType);
+#endif
+ }
+
+ internal static Enum GetArbitraryValue(System.Type enumType)
+ {
+ Array values = GetEnumValues(enumType);
+ int pos = (int)(DateTimeUtilities.CurrentUnixMs() & int.MaxValue) % values.Length;
+ return (Enum)values.GetValue(pos);
+ }
+
+ internal static bool IsEnumType(System.Type t)
+ {
+#if NEW_REFLECTION || NETFX_CORE
+ return t.GetTypeInfo().IsEnum;
+#else
+ return t.IsEnum;
+#endif
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Enums.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Enums.cs.meta
new file mode 100644
index 00000000..f2aea4f3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Enums.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 5bc960ec18e889148ae2e52c6be70ec4
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/IMemoable.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/IMemoable.cs
new file mode 100644
index 00000000..6fd47e04
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/IMemoable.cs
@@ -0,0 +1,33 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities
+{
+ public interface IMemoable
+ {
+ ///
+ /// Produce a copy of this object with its configuration and in its current state.
+ ///
+ ///
+ /// The returned object may be used simply to store the state, or may be used as a similar object
+ /// starting from the copied state.
+ ///
+ IMemoable Copy();
+
+ ///
+ /// Restore a copied object state into this object.
+ ///
+ ///
+ /// Implementations of this method should try to avoid or minimise memory allocation to perform the reset.
+ ///
+ /// an object originally {@link #copy() copied} from an object of the same type as this instance.
+ /// if the provided object is not of the correct type.
+ /// if the other parameter is in some other way invalid.
+ void Reset(IMemoable other);
+ }
+
+}
+
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/IMemoable.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/IMemoable.cs.meta
new file mode 100644
index 00000000..240b1f35
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/IMemoable.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: e5094da18f6285e498789845689aac6f
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Integers.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Integers.cs
new file mode 100644
index 00000000..6a538b76
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Integers.cs
@@ -0,0 +1,33 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities
+{
+ public abstract class Integers
+ {
+ public static int RotateLeft(int i, int distance)
+ {
+ return (i << distance) ^ (int)((uint)i >> -distance);
+ }
+
+ [CLSCompliantAttribute(false)]
+ public static uint RotateLeft(uint i, int distance)
+ {
+ return (i << distance) ^ (i >> -distance);
+ }
+
+ public static int RotateRight(int i, int distance)
+ {
+ return (int)((uint)i >> distance) ^ (i << -distance);
+ }
+
+ [CLSCompliantAttribute(false)]
+ public static uint RotateRight(uint i, int distance)
+ {
+ return (i >> distance) ^ (i << -distance);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Integers.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Integers.cs.meta
new file mode 100644
index 00000000..72b270d4
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Integers.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 3188e9987cc8be145a324b947c7e7475
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/MemoableResetException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/MemoableResetException.cs
new file mode 100644
index 00000000..9b5d14e8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/MemoableResetException.cs
@@ -0,0 +1,31 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities
+{
+ /**
+ * Exception to be thrown on a failure to reset an object implementing Memoable.
+ *
+ * The exception extends InvalidCastException to enable users to have a single handling case,
+ * only introducing specific handling of this one if required.
+ *
+ */
+ public class MemoableResetException
+ : InvalidCastException
+ {
+ /**
+ * Basic Constructor.
+ *
+ * @param msg message to be associated with this exception.
+ */
+ public MemoableResetException(string msg)
+ : base(msg)
+ {
+ }
+ }
+
+}
+
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/MemoableResetException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/MemoableResetException.cs.meta
new file mode 100644
index 00000000..e3d86045
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/MemoableResetException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 20a8024aade27594aacfebde1c7c76f3
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Platform.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Platform.cs
new file mode 100644
index 00000000..6450fe20
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Platform.cs
@@ -0,0 +1,233 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Globalization;
+using System.IO;
+using System.Text;
+
+#if SILVERLIGHT || PORTABLE || NETFX_CORE
+using System.Collections.Generic;
+#else
+using System.Collections;
+#endif
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities
+{
+ internal abstract class Platform
+ {
+ private static readonly CompareInfo InvariantCompareInfo = CultureInfo.InvariantCulture.CompareInfo;
+
+#if NETCF_1_0 || NETCF_2_0
+ private static string GetNewLine()
+ {
+ MemoryStream buf = new MemoryStream();
+ StreamWriter w = new StreamWriter(buf, Encoding.UTF8);
+ w.WriteLine();
+ Dispose(w);
+ byte[] bs = buf.ToArray();
+ return Encoding.UTF8.GetString(bs, 0, bs.Length);
+ }
+#else
+ private static string GetNewLine()
+ {
+ return Environment.NewLine;
+ }
+#endif
+
+ internal static bool EqualsIgnoreCase(string a, string b)
+ {
+#if PORTABLE || NETFX_CORE
+ return String.Equals(a, b, StringComparison.OrdinalIgnoreCase);
+#else
+ return ToUpperInvariant(a) == ToUpperInvariant(b);
+#endif
+ }
+
+#if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || (PORTABLE || NETFX_CORE && !DOTNET)
+ internal static string GetEnvironmentVariable(
+ string variable)
+ {
+ return null;
+ }
+#else
+ internal static string GetEnvironmentVariable(
+ string variable)
+ {
+ try
+ {
+ return Environment.GetEnvironmentVariable(variable);
+ }
+ catch (System.Security.SecurityException)
+ {
+ // We don't have the required permission to read this environment variable,
+ // which is fine, just act as if it's not set
+ return null;
+ }
+ }
+#endif
+
+#if NETCF_1_0
+ internal static Exception CreateNotImplementedException(
+ string message)
+ {
+ return new Exception("Not implemented: " + message);
+ }
+
+ internal static bool Equals(
+ object a,
+ object b)
+ {
+ return a == b || (a != null && b != null && a.Equals(b));
+ }
+#else
+ internal static Exception CreateNotImplementedException(
+ string message)
+ {
+ return new NotImplementedException(message);
+ }
+#endif
+
+#if SILVERLIGHT || PORTABLE || NETFX_CORE
+ internal static System.Collections.IList CreateArrayList()
+ {
+ return new List();
+ }
+ internal static System.Collections.IList CreateArrayList(int capacity)
+ {
+ return new List(capacity);
+ }
+ internal static System.Collections.IList CreateArrayList(System.Collections.ICollection collection)
+ {
+ System.Collections.IList result = new List(collection.Count);
+ foreach (object o in collection)
+ {
+ result.Add(o);
+ }
+ return result;
+ }
+ internal static System.Collections.IList CreateArrayList(System.Collections.IEnumerable collection)
+ {
+ System.Collections.IList result = new List();
+ foreach (object o in collection)
+ {
+ result.Add(o);
+ }
+ return result;
+ }
+ internal static System.Collections.IDictionary CreateHashtable()
+ {
+ return new Dictionary();
+ }
+ internal static System.Collections.IDictionary CreateHashtable(int capacity)
+ {
+ return new Dictionary(capacity);
+ }
+ internal static System.Collections.IDictionary CreateHashtable(System.Collections.IDictionary dictionary)
+ {
+ System.Collections.IDictionary result = new Dictionary(dictionary.Count);
+ foreach (System.Collections.DictionaryEntry entry in dictionary)
+ {
+ result.Add(entry.Key, entry.Value);
+ }
+ return result;
+ }
+#else
+ internal static System.Collections.IList CreateArrayList()
+ {
+ return new ArrayList();
+ }
+ internal static System.Collections.IList CreateArrayList(int capacity)
+ {
+ return new ArrayList(capacity);
+ }
+ internal static System.Collections.IList CreateArrayList(System.Collections.ICollection collection)
+ {
+ return new ArrayList(collection);
+ }
+ internal static System.Collections.IList CreateArrayList(System.Collections.IEnumerable collection)
+ {
+ ArrayList result = new ArrayList();
+ foreach (object o in collection)
+ {
+ result.Add(o);
+ }
+ return result;
+ }
+ internal static System.Collections.IDictionary CreateHashtable()
+ {
+ return new Hashtable();
+ }
+ internal static System.Collections.IDictionary CreateHashtable(int capacity)
+ {
+ return new Hashtable(capacity);
+ }
+ internal static System.Collections.IDictionary CreateHashtable(System.Collections.IDictionary dictionary)
+ {
+ return new Hashtable(dictionary);
+ }
+#endif
+
+ internal static string ToLowerInvariant(string s)
+ {
+#if PORTABLE || NETFX_CORE
+ return s.ToLowerInvariant();
+#else
+ return s.ToLower(CultureInfo.InvariantCulture);
+#endif
+ }
+
+ internal static string ToUpperInvariant(string s)
+ {
+#if PORTABLE || NETFX_CORE
+ return s.ToUpperInvariant();
+#else
+ return s.ToUpper(CultureInfo.InvariantCulture);
+#endif
+ }
+
+ internal static readonly string NewLine = GetNewLine();
+
+#if PORTABLE || NETFX_CORE
+ internal static void Dispose(IDisposable d)
+ {
+ d.Dispose();
+ }
+#else
+ internal static void Dispose(Stream s)
+ {
+ s.Close();
+ }
+ internal static void Dispose(TextWriter t)
+ {
+ t.Close();
+ }
+#endif
+
+ internal static int IndexOf(string source, string value)
+ {
+ return InvariantCompareInfo.IndexOf(source, value, CompareOptions.Ordinal);
+ }
+
+ internal static int LastIndexOf(string source, string value)
+ {
+ return InvariantCompareInfo.LastIndexOf(source, value, CompareOptions.Ordinal);
+ }
+
+ internal static bool StartsWith(string source, string prefix)
+ {
+ return InvariantCompareInfo.IsPrefix(source, prefix, CompareOptions.Ordinal);
+ }
+
+ internal static bool EndsWith(string source, string suffix)
+ {
+ return InvariantCompareInfo.IsSuffix(source, suffix, CompareOptions.Ordinal);
+ }
+
+ internal static string GetTypeName(object obj)
+ {
+ return obj.GetType().FullName;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Platform.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Platform.cs.meta
new file mode 100644
index 00000000..8013f2b5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Platform.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 34ac2529ba9563b4b95ceece9c95095a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Strings.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Strings.cs
new file mode 100644
index 00000000..0f6dee2a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Strings.cs
@@ -0,0 +1,107 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Text;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities
+{
+ /// General string utilities.
+ public abstract class Strings
+ {
+ internal static bool IsOneOf(string s, params string[] candidates)
+ {
+ foreach (string candidate in candidates)
+ {
+ if (s == candidate)
+ return true;
+ }
+ return false;
+ }
+
+ public static string FromByteArray(
+ byte[] bs)
+ {
+ char[] cs = new char[bs.Length];
+ for (int i = 0; i < cs.Length; ++i)
+ {
+ cs[i] = Convert.ToChar(bs[i]);
+ }
+ return new string(cs);
+ }
+
+ public static byte[] ToByteArray(
+ char[] cs)
+ {
+ byte[] bs = new byte[cs.Length];
+ for (int i = 0; i < bs.Length; ++i)
+ {
+ bs[i] = Convert.ToByte(cs[i]);
+ }
+ return bs;
+ }
+
+ public static byte[] ToByteArray(
+ string s)
+ {
+ byte[] bs = new byte[s.Length];
+ for (int i = 0; i < bs.Length; ++i)
+ {
+ bs[i] = Convert.ToByte(s[i]);
+ }
+ return bs;
+ }
+
+ public static string FromAsciiByteArray(
+ byte[] bytes)
+ {
+#if SILVERLIGHT || PORTABLE || NETFX_CORE
+ // TODO Check for non-ASCII bytes in input?
+ return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
+#else
+ return Encoding.ASCII.GetString(bytes, 0, bytes.Length);
+#endif
+ }
+
+ public static byte[] ToAsciiByteArray(
+ char[] cs)
+ {
+#if SILVERLIGHT || PORTABLE || NETFX_CORE
+ // TODO Check for non-ASCII characters in input?
+ return Encoding.UTF8.GetBytes(cs);
+#else
+ return Encoding.ASCII.GetBytes(cs);
+#endif
+ }
+
+ public static byte[] ToAsciiByteArray(
+ string s)
+ {
+#if SILVERLIGHT || PORTABLE || NETFX_CORE
+ // TODO Check for non-ASCII characters in input?
+ return Encoding.UTF8.GetBytes(s);
+#else
+ return Encoding.ASCII.GetBytes(s);
+#endif
+ }
+
+ public static string FromUtf8ByteArray(
+ byte[] bytes)
+ {
+ return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
+ }
+
+ public static byte[] ToUtf8ByteArray(
+ char[] cs)
+ {
+ return Encoding.UTF8.GetBytes(cs);
+ }
+
+ public static byte[] ToUtf8ByteArray(
+ string s)
+ {
+ return Encoding.UTF8.GetBytes(s);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Strings.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Strings.cs.meta
new file mode 100644
index 00000000..9c9bc239
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Strings.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 1102d66cf36a07545b4ef549eb96e85e
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Times.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Times.cs
new file mode 100644
index 00000000..284fc3a6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Times.cs
@@ -0,0 +1,18 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities
+{
+ public sealed class Times
+ {
+ private static long NanosecondsPerTick = 100L;
+
+ public static long NanoTime()
+ {
+ return DateTime.UtcNow.Ticks * NanosecondsPerTick;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Times.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Times.cs.meta
new file mode 100644
index 00000000..c10bfa7d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/Times.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0836244bbd72b0c439240b98b61f7c5b
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/TypeExtensions.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/TypeExtensions.cs
new file mode 100644
index 00000000..15fdce4a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/TypeExtensions.cs
@@ -0,0 +1,21 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+#if NEW_REFLECTION || NETFX_CORE
+
+using System;
+using System.Reflection;
+
+namespace Org.BouncyCastle
+{
+ internal static class TypeExtensions
+ {
+ public static bool IsInstanceOfType(this Type type, object instance)
+ {
+ return instance != null && type.GetTypeInfo().IsAssignableFrom(instance.GetType().GetTypeInfo());
+ }
+ }
+}
+
+#endif
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/TypeExtensions.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/TypeExtensions.cs.meta
new file mode 100644
index 00000000..9e1d35e1
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/TypeExtensions.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: cc84ea3a3830f114cbeeafb42707effe
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections.meta
new file mode 100644
index 00000000..31f173d7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 0b0797c2616cd4f4bbc6332490d85557
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/CollectionUtilities.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/CollectionUtilities.cs
new file mode 100644
index 00000000..de2b1b61
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/CollectionUtilities.cs
@@ -0,0 +1,79 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+#if UNITY_WSA && !UNITY_EDITOR && !ENABLE_IL2CPP
+using System.TypeFix;
+#endif
+using System;
+using System.Collections;
+using System.Text;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections
+{
+ public abstract class CollectionUtilities
+ {
+ public static void AddRange(IList to, IEnumerable range)
+ {
+ foreach (object o in range)
+ {
+ to.Add(o);
+ }
+ }
+
+ public static bool CheckElementsAreOfType(IEnumerable e, Type t)
+ {
+ foreach (object o in e)
+ {
+ if (!t.IsInstanceOfType(o))
+ return false;
+ }
+ return true;
+ }
+
+ public static IDictionary ReadOnly(IDictionary d)
+ {
+ return new UnmodifiableDictionaryProxy(d);
+ }
+
+ public static IList ReadOnly(IList l)
+ {
+ return new UnmodifiableListProxy(l);
+ }
+
+ public static ISet ReadOnly(ISet s)
+ {
+ return new UnmodifiableSetProxy(s);
+ }
+
+ public static object RequireNext(IEnumerator e)
+ {
+ if (!e.MoveNext())
+ throw new InvalidOperationException();
+
+ return e.Current;
+ }
+
+ public static string ToString(IEnumerable c)
+ {
+ StringBuilder sb = new StringBuilder("[");
+
+ IEnumerator e = c.GetEnumerator();
+
+ if (e.MoveNext())
+ {
+ sb.Append(e.Current.ToString());
+
+ while (e.MoveNext())
+ {
+ sb.Append(", ");
+ sb.Append(e.Current.ToString());
+ }
+ }
+
+ sb.Append(']');
+
+ return sb.ToString();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/CollectionUtilities.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/CollectionUtilities.cs.meta
new file mode 100644
index 00000000..4df1ae19
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/CollectionUtilities.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 4d30cc7795a67b547845658234e4bed0
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/EmptyEnumerable.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/EmptyEnumerable.cs
new file mode 100644
index 00000000..0cddf547
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/EmptyEnumerable.cs
@@ -0,0 +1,48 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections
+{
+ public sealed class EmptyEnumerable
+ : IEnumerable
+ {
+ public static readonly IEnumerable Instance = new EmptyEnumerable();
+
+ private EmptyEnumerable()
+ {
+ }
+
+ public IEnumerator GetEnumerator()
+ {
+ return EmptyEnumerator.Instance;
+ }
+ }
+
+ public sealed class EmptyEnumerator
+ : IEnumerator
+ {
+ public static readonly IEnumerator Instance = new EmptyEnumerator();
+
+ private EmptyEnumerator()
+ {
+ }
+
+ public bool MoveNext()
+ {
+ return false;
+ }
+
+ public void Reset()
+ {
+ }
+
+ public object Current
+ {
+ get { throw new InvalidOperationException("No elements"); }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/EmptyEnumerable.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/EmptyEnumerable.cs.meta
new file mode 100644
index 00000000..326f32f0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/EmptyEnumerable.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 9fe693b6994f69f4ab3719bf470e98d2
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/EnumerableProxy.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/EnumerableProxy.cs
new file mode 100644
index 00000000..562f380f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/EnumerableProxy.cs
@@ -0,0 +1,29 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections
+{
+ public sealed class EnumerableProxy
+ : IEnumerable
+ {
+ private readonly IEnumerable inner;
+
+ public EnumerableProxy(
+ IEnumerable inner)
+ {
+ if (inner == null)
+ throw new ArgumentNullException("inner");
+
+ this.inner = inner;
+ }
+
+ public IEnumerator GetEnumerator()
+ {
+ return inner.GetEnumerator();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/EnumerableProxy.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/EnumerableProxy.cs.meta
new file mode 100644
index 00000000..47339c88
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/EnumerableProxy.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 7473b1e62cdb7be449f354cbedddd3b5
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/HashSet.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/HashSet.cs
new file mode 100644
index 00000000..12c399b2
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/HashSet.cs
@@ -0,0 +1,103 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections
+{
+ public class HashSet
+ : ISet
+ {
+ private readonly IDictionary impl = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+
+ public HashSet()
+ {
+ }
+
+ public HashSet(IEnumerable s)
+ {
+ foreach (object o in s)
+ {
+ Add(o);
+ }
+ }
+
+ public virtual void Add(object o)
+ {
+ impl[o] = null;
+ }
+
+ public virtual void AddAll(IEnumerable e)
+ {
+ foreach (object o in e)
+ {
+ Add(o);
+ }
+ }
+
+ public virtual void Clear()
+ {
+ impl.Clear();
+ }
+
+ public virtual bool Contains(object o)
+ {
+ return impl.Contains(o);
+ }
+
+ public virtual void CopyTo(Array array, int index)
+ {
+ impl.Keys.CopyTo(array, index);
+ }
+
+ public virtual int Count
+ {
+ get { return impl.Count; }
+ }
+
+ public virtual IEnumerator GetEnumerator()
+ {
+ return impl.Keys.GetEnumerator();
+ }
+
+ public virtual bool IsEmpty
+ {
+ get { return impl.Count == 0; }
+ }
+
+ public virtual bool IsFixedSize
+ {
+ get { return impl.IsFixedSize; }
+ }
+
+ public virtual bool IsReadOnly
+ {
+ get { return impl.IsReadOnly; }
+ }
+
+ public virtual bool IsSynchronized
+ {
+ get { return impl.IsSynchronized; }
+ }
+
+ public virtual void Remove(object o)
+ {
+ impl.Remove(o);
+ }
+
+ public virtual void RemoveAll(IEnumerable e)
+ {
+ foreach (object o in e)
+ {
+ Remove(o);
+ }
+ }
+
+ public virtual object SyncRoot
+ {
+ get { return impl.SyncRoot; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/HashSet.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/HashSet.cs.meta
new file mode 100644
index 00000000..58836e7b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/HashSet.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 7324bf9bc59776949bf134abc958ddeb
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/ISet.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/ISet.cs
new file mode 100644
index 00000000..6ab03f9a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/ISet.cs
@@ -0,0 +1,23 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections
+{
+ public interface ISet
+ : ICollection
+ {
+ void Add(object o);
+ void AddAll(IEnumerable e);
+ void Clear();
+ bool Contains(object o);
+ bool IsEmpty { get; }
+ bool IsFixedSize { get; }
+ bool IsReadOnly { get; }
+ void Remove(object o);
+ void RemoveAll(IEnumerable e);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/ISet.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/ISet.cs.meta
new file mode 100644
index 00000000..3e9825dd
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/ISet.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: e2f3dcb73a056604e8efd46a0ba3875a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/LinkedDictionary.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/LinkedDictionary.cs
new file mode 100644
index 00000000..bb9b4fb6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/LinkedDictionary.cs
@@ -0,0 +1,182 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections
+{
+ public class LinkedDictionary
+ : IDictionary
+ {
+ internal readonly IDictionary hash = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ internal readonly IList keys = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+
+ public LinkedDictionary()
+ {
+ }
+
+ public virtual void Add(object k, object v)
+ {
+ hash.Add(k, v);
+ keys.Add(k);
+ }
+
+ public virtual void Clear()
+ {
+ hash.Clear();
+ keys.Clear();
+ }
+
+ public virtual bool Contains(object k)
+ {
+ return hash.Contains(k);
+ }
+
+ public virtual void CopyTo(Array array, int index)
+ {
+ foreach (object k in keys)
+ {
+ array.SetValue(hash[k], index++);
+ }
+ }
+
+ public virtual int Count
+ {
+ get { return hash.Count; }
+ }
+
+ IEnumerator IEnumerable.GetEnumerator()
+ {
+ return GetEnumerator();
+ }
+
+ public virtual IDictionaryEnumerator GetEnumerator()
+ {
+ return new LinkedDictionaryEnumerator(this);
+ }
+
+ public virtual void Remove(object k)
+ {
+ hash.Remove(k);
+ keys.Remove(k);
+ }
+
+ public virtual bool IsFixedSize
+ {
+ get { return false; }
+ }
+
+ public virtual bool IsReadOnly
+ {
+ get { return false; }
+ }
+
+ public virtual bool IsSynchronized
+ {
+ get { return false; }
+ }
+
+ public virtual object SyncRoot
+ {
+ get { return false; }
+ }
+
+ public virtual ICollection Keys
+ {
+ get { return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(keys); }
+ }
+
+ public virtual ICollection Values
+ {
+ // NB: Order has to be the same as for Keys property
+ get
+ {
+ IList values = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(keys.Count);
+ foreach (object k in keys)
+ {
+ values.Add(hash[k]);
+ }
+ return values;
+ }
+ }
+
+ public virtual object this[object k]
+ {
+ get
+ {
+ return hash[k];
+ }
+ set
+ {
+ if (!hash.Contains(k))
+ keys.Add(k);
+ hash[k] = value;
+ }
+ }
+ }
+
+ internal class LinkedDictionaryEnumerator : IDictionaryEnumerator
+ {
+ private readonly LinkedDictionary parent;
+ private int pos = -1;
+
+ internal LinkedDictionaryEnumerator(LinkedDictionary parent)
+ {
+ this.parent = parent;
+ }
+
+ public virtual object Current
+ {
+ get { return Entry; }
+ }
+
+ public virtual DictionaryEntry Entry
+ {
+ get
+ {
+ object k = CurrentKey;
+ return new DictionaryEntry(k, parent.hash[k]);
+ }
+ }
+
+ public virtual object Key
+ {
+ get
+ {
+ return CurrentKey;
+ }
+ }
+
+ public virtual bool MoveNext()
+ {
+ if (pos >= parent.keys.Count)
+ return false;
+ return ++pos < parent.keys.Count;
+ }
+
+ public virtual void Reset()
+ {
+ this.pos = -1;
+ }
+
+ public virtual object Value
+ {
+ get
+ {
+ return parent.hash[CurrentKey];
+ }
+ }
+
+ private object CurrentKey
+ {
+ get
+ {
+ if (pos < 0 || pos >= parent.keys.Count)
+ throw new InvalidOperationException();
+ return parent.keys[pos];
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/LinkedDictionary.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/LinkedDictionary.cs.meta
new file mode 100644
index 00000000..4edadcc9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/LinkedDictionary.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 1c21a553327fa1d4aadd4151e30aa090
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableDictionary.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableDictionary.cs
new file mode 100644
index 00000000..3a00746a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableDictionary.cs
@@ -0,0 +1,68 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections
+{
+ public abstract class UnmodifiableDictionary
+ : IDictionary
+ {
+ protected UnmodifiableDictionary()
+ {
+ }
+
+ public virtual void Add(object k, object v)
+ {
+ throw new NotSupportedException();
+ }
+
+ public virtual void Clear()
+ {
+ throw new NotSupportedException();
+ }
+
+ public abstract bool Contains(object k);
+
+ public abstract void CopyTo(Array array, int index);
+
+ public abstract int Count { get; }
+
+ IEnumerator IEnumerable.GetEnumerator()
+ {
+ return GetEnumerator();
+ }
+
+ public abstract IDictionaryEnumerator GetEnumerator();
+
+ public virtual void Remove(object k)
+ {
+ throw new NotSupportedException();
+ }
+
+ public abstract bool IsFixedSize { get; }
+
+ public virtual bool IsReadOnly
+ {
+ get { return true; }
+ }
+
+ public abstract bool IsSynchronized { get; }
+
+ public abstract object SyncRoot { get; }
+
+ public abstract ICollection Keys { get; }
+
+ public abstract ICollection Values { get; }
+
+ public virtual object this[object k]
+ {
+ get { return GetValue(k); }
+ set { throw new NotSupportedException(); }
+ }
+
+ protected abstract object GetValue(object k);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableDictionary.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableDictionary.cs.meta
new file mode 100644
index 00000000..5626da19
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableDictionary.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 44fabc8f92d114147b94a895ef74ca4e
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableDictionaryProxy.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableDictionaryProxy.cs
new file mode 100644
index 00000000..3e344e76
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableDictionaryProxy.cs
@@ -0,0 +1,70 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections
+{
+ public class UnmodifiableDictionaryProxy
+ : UnmodifiableDictionary
+ {
+ private readonly IDictionary d;
+
+ public UnmodifiableDictionaryProxy(IDictionary d)
+ {
+ this.d = d;
+ }
+
+ public override bool Contains(object k)
+ {
+ return d.Contains(k);
+ }
+
+ public override void CopyTo(Array array, int index)
+ {
+ d.CopyTo(array, index);
+ }
+
+ public override int Count
+ {
+ get { return d.Count; }
+ }
+
+ public override IDictionaryEnumerator GetEnumerator()
+ {
+ return d.GetEnumerator();
+ }
+
+ public override bool IsFixedSize
+ {
+ get { return d.IsFixedSize; }
+ }
+
+ public override bool IsSynchronized
+ {
+ get { return d.IsSynchronized; }
+ }
+
+ public override object SyncRoot
+ {
+ get { return d.SyncRoot; }
+ }
+
+ public override ICollection Keys
+ {
+ get { return d.Keys; }
+ }
+
+ public override ICollection Values
+ {
+ get { return d.Values; }
+ }
+
+ protected override object GetValue(object k)
+ {
+ return d[k];
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableDictionaryProxy.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableDictionaryProxy.cs.meta
new file mode 100644
index 00000000..efc33897
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableDictionaryProxy.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 2fdbffa9353f147479271e1cac8fc8e9
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableList.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableList.cs
new file mode 100644
index 00000000..c8c49fc2
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableList.cs
@@ -0,0 +1,71 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections
+{
+ public abstract class UnmodifiableList
+ : IList
+ {
+ protected UnmodifiableList()
+ {
+ }
+
+ public virtual int Add(object o)
+ {
+ throw new NotSupportedException();
+ }
+
+ public virtual void Clear()
+ {
+ throw new NotSupportedException();
+ }
+
+ public abstract bool Contains(object o);
+
+ public abstract void CopyTo(Array array, int index);
+
+ public abstract int Count { get; }
+
+ public abstract IEnumerator GetEnumerator();
+
+ public abstract int IndexOf(object o);
+
+ public virtual void Insert(int i, object o)
+ {
+ throw new NotSupportedException();
+ }
+
+ public abstract bool IsFixedSize { get; }
+
+ public virtual bool IsReadOnly
+ {
+ get { return true; }
+ }
+
+ public abstract bool IsSynchronized { get; }
+
+ public virtual void Remove(object o)
+ {
+ throw new NotSupportedException();
+ }
+
+ public virtual void RemoveAt(int i)
+ {
+ throw new NotSupportedException();
+ }
+
+ public abstract object SyncRoot { get; }
+
+ public virtual object this[int i]
+ {
+ get { return GetValue(i); }
+ set { throw new NotSupportedException(); }
+ }
+
+ protected abstract object GetValue(int i);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableList.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableList.cs.meta
new file mode 100644
index 00000000..454da692
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableList.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 5da823f6add0e6e4281f31de3d3b8d7b
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableListProxy.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableListProxy.cs
new file mode 100644
index 00000000..66793bb3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableListProxy.cs
@@ -0,0 +1,65 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections
+{
+ public class UnmodifiableListProxy
+ : UnmodifiableList
+ {
+ private readonly IList l;
+
+ public UnmodifiableListProxy(IList l)
+ {
+ this.l = l;
+ }
+
+ public override bool Contains(object o)
+ {
+ return l.Contains(o);
+ }
+
+ public override void CopyTo(Array array, int index)
+ {
+ l.CopyTo(array, index);
+ }
+
+ public override int Count
+ {
+ get { return l.Count; }
+ }
+
+ public override IEnumerator GetEnumerator()
+ {
+ return l.GetEnumerator();
+ }
+
+ public override int IndexOf(object o)
+ {
+ return l.IndexOf(o);
+ }
+
+ public override bool IsFixedSize
+ {
+ get { return l.IsFixedSize; }
+ }
+
+ public override bool IsSynchronized
+ {
+ get { return l.IsSynchronized; }
+ }
+
+ public override object SyncRoot
+ {
+ get { return l.SyncRoot; }
+ }
+
+ protected override object GetValue(int i)
+ {
+ return l[i];
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableListProxy.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableListProxy.cs.meta
new file mode 100644
index 00000000..ef5c3499
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableListProxy.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 25fcbd1ae6e6fd6408ec969e9dc8e092
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableSet.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableSet.cs
new file mode 100644
index 00000000..66d223b3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableSet.cs
@@ -0,0 +1,63 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections
+{
+ public abstract class UnmodifiableSet
+ : ISet
+ {
+ protected UnmodifiableSet()
+ {
+ }
+
+ public virtual void Add(object o)
+ {
+ throw new NotSupportedException();
+ }
+
+ public virtual void AddAll(IEnumerable e)
+ {
+ throw new NotSupportedException();
+ }
+
+ public virtual void Clear()
+ {
+ throw new NotSupportedException();
+ }
+
+ public abstract bool Contains(object o);
+
+ public abstract void CopyTo(Array array, int index);
+
+ public abstract int Count { get; }
+
+ public abstract IEnumerator GetEnumerator();
+
+ public abstract bool IsEmpty { get; }
+
+ public abstract bool IsFixedSize { get; }
+
+ public virtual bool IsReadOnly
+ {
+ get { return true; }
+ }
+
+ public abstract bool IsSynchronized { get; }
+
+ public abstract object SyncRoot { get; }
+
+ public virtual void Remove(object o)
+ {
+ throw new NotSupportedException();
+ }
+
+ public virtual void RemoveAll(IEnumerable e)
+ {
+ throw new NotSupportedException();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableSet.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableSet.cs.meta
new file mode 100644
index 00000000..b6f89697
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableSet.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 3e945481d510ca240a15c744d33ddfba
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableSetProxy.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableSetProxy.cs
new file mode 100644
index 00000000..f3367ce9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableSetProxy.cs
@@ -0,0 +1,60 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections
+{
+ public class UnmodifiableSetProxy
+ : UnmodifiableSet
+ {
+ private readonly ISet s;
+
+ public UnmodifiableSetProxy (ISet s)
+ {
+ this.s = s;
+ }
+
+ public override bool Contains(object o)
+ {
+ return s.Contains(o);
+ }
+
+ public override void CopyTo(Array array, int index)
+ {
+ s.CopyTo(array, index);
+ }
+
+ public override int Count
+ {
+ get { return s.Count; }
+ }
+
+ public override IEnumerator GetEnumerator()
+ {
+ return s.GetEnumerator();
+ }
+
+ public override bool IsEmpty
+ {
+ get { return s.IsEmpty; }
+ }
+
+ public override bool IsFixedSize
+ {
+ get { return s.IsFixedSize; }
+ }
+
+ public override bool IsSynchronized
+ {
+ get { return s.IsSynchronized; }
+ }
+
+ public override object SyncRoot
+ {
+ get { return s.SyncRoot; }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableSetProxy.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableSetProxy.cs.meta
new file mode 100644
index 00000000..6e9cf2cf
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/collections/UnmodifiableSetProxy.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 21db2580c1539f14a9f2aaa4f1c777a9
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/date.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/date.meta
new file mode 100644
index 00000000..bb7a509a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/date.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 519a28f7f784fe741926e76c222b9da5
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/date/DateTimeObject.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/date/DateTimeObject.cs
new file mode 100644
index 00000000..2dff70cb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/date/DateTimeObject.cs
@@ -0,0 +1,29 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Date
+{
+ public sealed class DateTimeObject
+ {
+ private readonly DateTime dt;
+
+ public DateTimeObject(
+ DateTime dt)
+ {
+ this.dt = dt;
+ }
+
+ public DateTime Value
+ {
+ get { return dt; }
+ }
+
+ public override string ToString()
+ {
+ return dt.ToString();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/date/DateTimeObject.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/date/DateTimeObject.cs.meta
new file mode 100644
index 00000000..137a6150
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/date/DateTimeObject.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 98e7fe4e769121b419a4d266709cd137
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/date/DateTimeUtilities.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/date/DateTimeUtilities.cs
new file mode 100644
index 00000000..be931933
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/date/DateTimeUtilities.cs
@@ -0,0 +1,51 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Date
+{
+ public class DateTimeUtilities
+ {
+ public static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1);
+
+ private DateTimeUtilities()
+ {
+ }
+
+ ///
+ /// Return the number of milliseconds since the Unix epoch (1 Jan., 1970 UTC) for a given DateTime value.
+ ///
+ /// A UTC DateTime value not before epoch.
+ /// Number of whole milliseconds after epoch.
+ /// 'dateTime' is before epoch.
+ public static long DateTimeToUnixMs(
+ DateTime dateTime)
+ {
+ if (dateTime.CompareTo(UnixEpoch) < 0)
+ throw new ArgumentException("DateTime value may not be before the epoch", "dateTime");
+
+ return (dateTime.Ticks - UnixEpoch.Ticks) / TimeSpan.TicksPerMillisecond;
+ }
+
+ ///
+ /// Create a DateTime value from the number of milliseconds since the Unix epoch (1 Jan., 1970 UTC).
+ ///
+ /// Number of milliseconds since the epoch.
+ /// A UTC DateTime value
+ public static DateTime UnixMsToDateTime(
+ long unixMs)
+ {
+ return new DateTime(unixMs * TimeSpan.TicksPerMillisecond + UnixEpoch.Ticks);
+ }
+
+ ///
+ /// Return the current number of milliseconds since the Unix epoch (1 Jan., 1970 UTC).
+ ///
+ public static long CurrentUnixMs()
+ {
+ return DateTimeToUnixMs(DateTime.UtcNow);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/date/DateTimeUtilities.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/date/DateTimeUtilities.cs.meta
new file mode 100644
index 00000000..0f2ca7fc
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/date/DateTimeUtilities.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 85931186ecac6fa43a89af5ddc60b835
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders.meta
new file mode 100644
index 00000000..ecc759a9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: a1c695eec32cfe44ba8bb5c6b6230161
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/Base64.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/Base64.cs
new file mode 100644
index 00000000..22898626
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/Base64.cs
@@ -0,0 +1,124 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+using System.Text;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders
+{
+ public sealed class Base64
+ {
+ private Base64()
+ {
+ }
+
+ public static string ToBase64String(
+ byte[] data)
+ {
+ return Convert.ToBase64String(data, 0, data.Length);
+ }
+
+ public static string ToBase64String(
+ byte[] data,
+ int off,
+ int length)
+ {
+ return Convert.ToBase64String(data, off, length);
+ }
+
+ /**
+ * encode the input data producing a base 64 encoded byte array.
+ *
+ * @return a byte array containing the base 64 encoded data.
+ */
+ public static byte[] Encode(
+ byte[] data)
+ {
+ return Encode(data, 0, data.Length);
+ }
+
+ /**
+ * encode the input data producing a base 64 encoded byte array.
+ *
+ * @return a byte array containing the base 64 encoded data.
+ */
+ public static byte[] Encode(
+ byte[] data,
+ int off,
+ int length)
+ {
+ string s = Convert.ToBase64String(data, off, length);
+ return Strings.ToAsciiByteArray(s);
+ }
+
+ /**
+ * Encode the byte data to base 64 writing it to the given output stream.
+ *
+ * @return the number of bytes produced.
+ */
+ public static int Encode(
+ byte[] data,
+ Stream outStream)
+ {
+ byte[] encoded = Encode(data);
+ outStream.Write(encoded, 0, encoded.Length);
+ return encoded.Length;
+ }
+
+ /**
+ * Encode the byte data to base 64 writing it to the given output stream.
+ *
+ * @return the number of bytes produced.
+ */
+ public static int Encode(
+ byte[] data,
+ int off,
+ int length,
+ Stream outStream)
+ {
+ byte[] encoded = Encode(data, off, length);
+ outStream.Write(encoded, 0, encoded.Length);
+ return encoded.Length;
+ }
+
+ /**
+ * decode the base 64 encoded input data. It is assumed the input data is valid.
+ *
+ * @return a byte array representing the decoded data.
+ */
+ public static byte[] Decode(
+ byte[] data)
+ {
+ string s = Strings.FromAsciiByteArray(data);
+ return Convert.FromBase64String(s);
+ }
+
+ /**
+ * decode the base 64 encoded string data - whitespace will be ignored.
+ *
+ * @return a byte array representing the decoded data.
+ */
+ public static byte[] Decode(
+ string data)
+ {
+ return Convert.FromBase64String(data);
+ }
+
+ /**
+ * decode the base 64 encoded string data writing it to the given output stream,
+ * whitespace characters will be ignored.
+ *
+ * @return the number of bytes produced.
+ */
+ public static int Decode(
+ string data,
+ Stream outStream)
+ {
+ byte[] decoded = Decode(data);
+ outStream.Write(decoded, 0, decoded.Length);
+ return decoded.Length;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/Base64.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/Base64.cs.meta
new file mode 100644
index 00000000..3d41fa92
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/Base64.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 2d6f9d60f7dc61d48babd61d65e4a234
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/Base64Encoder.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/Base64Encoder.cs
new file mode 100644
index 00000000..b7cb7776
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/Base64Encoder.cs
@@ -0,0 +1,331 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders
+{
+ public class Base64Encoder
+ : IEncoder
+ {
+ protected readonly byte[] encodingTable =
+ {
+ (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
+ (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
+ (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
+ (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
+ (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
+ (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
+ (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
+ (byte)'v',
+ (byte)'w', (byte)'x', (byte)'y', (byte)'z',
+ (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6',
+ (byte)'7', (byte)'8', (byte)'9',
+ (byte)'+', (byte)'/'
+ };
+
+ protected byte padding = (byte)'=';
+
+ /*
+ * set up the decoding table.
+ */
+ protected readonly byte[] decodingTable = new byte[128];
+
+ protected void InitialiseDecodingTable()
+ {
+ Arrays.Fill(decodingTable, (byte)0xff);
+
+ for (int i = 0; i < encodingTable.Length; i++)
+ {
+ decodingTable[encodingTable[i]] = (byte)i;
+ }
+ }
+
+ public Base64Encoder()
+ {
+ InitialiseDecodingTable();
+ }
+
+ /**
+ * encode the input data producing a base 64 output stream.
+ *
+ * @return the number of bytes produced.
+ */
+ public int Encode(
+ byte[] data,
+ int off,
+ int length,
+ Stream outStream)
+ {
+ int modulus = length % 3;
+ int dataLength = (length - modulus);
+ int a1, a2, a3;
+
+ for (int i = off; i < off + dataLength; i += 3)
+ {
+ a1 = data[i] & 0xff;
+ a2 = data[i + 1] & 0xff;
+ a3 = data[i + 2] & 0xff;
+
+ outStream.WriteByte(encodingTable[(int) ((uint) a1 >> 2) & 0x3f]);
+ outStream.WriteByte(encodingTable[((a1 << 4) | (int) ((uint) a2 >> 4)) & 0x3f]);
+ outStream.WriteByte(encodingTable[((a2 << 2) | (int) ((uint) a3 >> 6)) & 0x3f]);
+ outStream.WriteByte(encodingTable[a3 & 0x3f]);
+ }
+
+ /*
+ * process the tail end.
+ */
+ int b1, b2, b3;
+ int d1, d2;
+
+ switch (modulus)
+ {
+ case 0: /* nothing left to do */
+ break;
+ case 1:
+ d1 = data[off + dataLength] & 0xff;
+ b1 = (d1 >> 2) & 0x3f;
+ b2 = (d1 << 4) & 0x3f;
+
+ outStream.WriteByte(encodingTable[b1]);
+ outStream.WriteByte(encodingTable[b2]);
+ outStream.WriteByte(padding);
+ outStream.WriteByte(padding);
+ break;
+ case 2:
+ d1 = data[off + dataLength] & 0xff;
+ d2 = data[off + dataLength + 1] & 0xff;
+
+ b1 = (d1 >> 2) & 0x3f;
+ b2 = ((d1 << 4) | (d2 >> 4)) & 0x3f;
+ b3 = (d2 << 2) & 0x3f;
+
+ outStream.WriteByte(encodingTable[b1]);
+ outStream.WriteByte(encodingTable[b2]);
+ outStream.WriteByte(encodingTable[b3]);
+ outStream.WriteByte(padding);
+ break;
+ }
+
+ return (dataLength / 3) * 4 + ((modulus == 0) ? 0 : 4);
+ }
+
+ private bool ignore(
+ char c)
+ {
+ return (c == '\n' || c =='\r' || c == '\t' || c == ' ');
+ }
+
+ /**
+ * decode the base 64 encoded byte data writing it to the given output stream,
+ * whitespace characters will be ignored.
+ *
+ * @return the number of bytes produced.
+ */
+ public int Decode(
+ byte[] data,
+ int off,
+ int length,
+ Stream outStream)
+ {
+ byte b1, b2, b3, b4;
+ int outLen = 0;
+
+ int end = off + length;
+
+ while (end > off)
+ {
+ if (!ignore((char)data[end - 1]))
+ {
+ break;
+ }
+
+ end--;
+ }
+
+ int i = off;
+ int finish = end - 4;
+
+ i = nextI(data, i, finish);
+
+ while (i < finish)
+ {
+ b1 = decodingTable[data[i++]];
+
+ i = nextI(data, i, finish);
+
+ b2 = decodingTable[data[i++]];
+
+ i = nextI(data, i, finish);
+
+ b3 = decodingTable[data[i++]];
+
+ i = nextI(data, i, finish);
+
+ b4 = decodingTable[data[i++]];
+
+ if ((b1 | b2 | b3 | b4) >= 0x80)
+ throw new IOException("invalid characters encountered in base64 data");
+
+ outStream.WriteByte((byte)((b1 << 2) | (b2 >> 4)));
+ outStream.WriteByte((byte)((b2 << 4) | (b3 >> 2)));
+ outStream.WriteByte((byte)((b3 << 6) | b4));
+
+ outLen += 3;
+
+ i = nextI(data, i, finish);
+ }
+
+ outLen += decodeLastBlock(outStream, (char)data[end - 4], (char)data[end - 3], (char)data[end - 2], (char)data[end - 1]);
+
+ return outLen;
+ }
+
+ private int nextI(
+ byte[] data,
+ int i,
+ int finish)
+ {
+ while ((i < finish) && ignore((char)data[i]))
+ {
+ i++;
+ }
+ return i;
+ }
+
+ /**
+ * decode the base 64 encoded string data writing it to the given output stream,
+ * whitespace characters will be ignored.
+ *
+ * @return the number of bytes produced.
+ */
+ public int DecodeString(
+ string data,
+ Stream outStream)
+ {
+ // Platform Implementation
+// byte[] bytes = Convert.FromBase64String(data);
+// outStream.Write(bytes, 0, bytes.Length);
+// return bytes.Length;
+
+ byte b1, b2, b3, b4;
+ int length = 0;
+
+ int end = data.Length;
+
+ while (end > 0)
+ {
+ if (!ignore(data[end - 1]))
+ {
+ break;
+ }
+
+ end--;
+ }
+
+ int i = 0;
+ int finish = end - 4;
+
+ i = nextI(data, i, finish);
+
+ while (i < finish)
+ {
+ b1 = decodingTable[data[i++]];
+
+ i = nextI(data, i, finish);
+
+ b2 = decodingTable[data[i++]];
+
+ i = nextI(data, i, finish);
+
+ b3 = decodingTable[data[i++]];
+
+ i = nextI(data, i, finish);
+
+ b4 = decodingTable[data[i++]];
+
+ if ((b1 | b2 | b3 | b4) >= 0x80)
+ throw new IOException("invalid characters encountered in base64 data");
+
+ outStream.WriteByte((byte)((b1 << 2) | (b2 >> 4)));
+ outStream.WriteByte((byte)((b2 << 4) | (b3 >> 2)));
+ outStream.WriteByte((byte)((b3 << 6) | b4));
+
+ length += 3;
+
+ i = nextI(data, i, finish);
+ }
+
+ length += decodeLastBlock(outStream, data[end - 4], data[end - 3], data[end - 2], data[end - 1]);
+
+ return length;
+ }
+
+ private int decodeLastBlock(
+ Stream outStream,
+ char c1,
+ char c2,
+ char c3,
+ char c4)
+ {
+ if (c3 == padding)
+ {
+ if (c4 != padding)
+ throw new IOException("invalid characters encountered at end of base64 data");
+
+ byte b1 = decodingTable[c1];
+ byte b2 = decodingTable[c2];
+
+ if ((b1 | b2) >= 0x80)
+ throw new IOException("invalid characters encountered at end of base64 data");
+
+ outStream.WriteByte((byte)((b1 << 2) | (b2 >> 4)));
+
+ return 1;
+ }
+
+ if (c4 == padding)
+ {
+ byte b1 = decodingTable[c1];
+ byte b2 = decodingTable[c2];
+ byte b3 = decodingTable[c3];
+
+ if ((b1 | b2 | b3) >= 0x80)
+ throw new IOException("invalid characters encountered at end of base64 data");
+
+ outStream.WriteByte((byte)((b1 << 2) | (b2 >> 4)));
+ outStream.WriteByte((byte)((b2 << 4) | (b3 >> 2)));
+
+ return 2;
+ }
+
+ {
+ byte b1 = decodingTable[c1];
+ byte b2 = decodingTable[c2];
+ byte b3 = decodingTable[c3];
+ byte b4 = decodingTable[c4];
+
+ if ((b1 | b2 | b3 | b4) >= 0x80)
+ throw new IOException("invalid characters encountered at end of base64 data");
+
+ outStream.WriteByte((byte)((b1 << 2) | (b2 >> 4)));
+ outStream.WriteByte((byte)((b2 << 4) | (b3 >> 2)));
+ outStream.WriteByte((byte)((b3 << 6) | b4));
+
+ return 3;
+ }
+ }
+
+ private int nextI(string data, int i, int finish)
+ {
+ while ((i < finish) && ignore(data[i]))
+ {
+ i++;
+ }
+ return i;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/Base64Encoder.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/Base64Encoder.cs.meta
new file mode 100644
index 00000000..82aff3b0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/Base64Encoder.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: f905b3d88fa2c734fb7553270ac7e0b3
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/BufferedDecoder.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/BufferedDecoder.cs
new file mode 100644
index 00000000..9f72a9a6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/BufferedDecoder.cs
@@ -0,0 +1,121 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders
+{
+ ///
+ /// A buffering class to allow translation from one format to another to
+ /// be done in discrete chunks.
+ ///
+ public class BufferedDecoder
+ {
+ internal byte[] buffer;
+ internal int bufOff;
+
+ internal ITranslator translator;
+
+ ///
+ /// Create a buffered Decoder.
+ ///
+ /// The translater to use.
+ /// The size of the buffer.
+ public BufferedDecoder(
+ ITranslator translator,
+ int bufferSize)
+ {
+ this.translator = translator;
+
+ if ((bufferSize % translator.GetEncodedBlockSize()) != 0)
+ {
+ throw new ArgumentException("buffer size not multiple of input block size");
+ }
+
+ buffer = new byte[bufferSize];
+// bufOff = 0;
+ }
+
+ ///
+ /// Process one byte of data.
+ ///
+ /// Data in.
+ /// Byte array for the output.
+ /// The offset in the output byte array to start writing from.
+ /// The amount of output bytes.
+ public int ProcessByte(
+ byte input,
+ byte[] output,
+ int outOff)
+ {
+ int resultLen = 0;
+
+ buffer[bufOff++] = input;
+
+ if (bufOff == buffer.Length)
+ {
+ resultLen = translator.Decode(buffer, 0, buffer.Length, output, outOff);
+ bufOff = 0;
+ }
+
+ return resultLen;
+ }
+
+
+ ///
+ /// Process data from a byte array.
+ ///
+ /// The input data.
+ /// Start position within input data array.
+ /// Amount of data to process from input data array.
+ /// Array to store output.
+ /// Position in output array to start writing from.
+ /// The amount of output bytes.
+ public int ProcessBytes(
+ byte[] input,
+ int inOff,
+ int len,
+ byte[] outBytes,
+ int outOff)
+ {
+ if (len < 0)
+ {
+ throw new ArgumentException("Can't have a negative input length!");
+ }
+
+ int resultLen = 0;
+ int gapLen = buffer.Length - bufOff;
+
+ if (len > gapLen)
+ {
+ Array.Copy(input, inOff, buffer, bufOff, gapLen);
+
+ resultLen += translator.Decode(buffer, 0, buffer.Length, outBytes, outOff);
+
+ bufOff = 0;
+
+ len -= gapLen;
+ inOff += gapLen;
+ outOff += resultLen;
+
+ int chunkSize = len - (len % buffer.Length);
+
+ resultLen += translator.Decode(input, inOff, chunkSize, outBytes, outOff);
+
+ len -= chunkSize;
+ inOff += chunkSize;
+ }
+
+ if (len != 0)
+ {
+ Array.Copy(input, inOff, buffer, bufOff, len);
+
+ bufOff += len;
+ }
+
+ return resultLen;
+ }
+ }
+
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/BufferedDecoder.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/BufferedDecoder.cs.meta
new file mode 100644
index 00000000..1692e3fa
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/BufferedDecoder.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: f6c49427e416a0845b216c1bc698f79c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/BufferedEncoder.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/BufferedEncoder.cs
new file mode 100644
index 00000000..e7c94efb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/BufferedEncoder.cs
@@ -0,0 +1,121 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders
+{
+ ///
+ /// A class that allows encoding of data using a specific encoder to be processed in chunks.
+ ///
+ public class BufferedEncoder
+ {
+ internal byte[] Buffer;
+ internal int bufOff;
+
+ internal ITranslator translator;
+
+
+ ///
+ /// Create.
+ ///
+ /// The translator to use.
+ /// Size of the chunks.
+ public BufferedEncoder(
+ ITranslator translator,
+ int bufferSize)
+ {
+ this.translator = translator;
+
+ if ((bufferSize % translator.GetEncodedBlockSize()) != 0)
+ {
+ throw new ArgumentException("buffer size not multiple of input block size");
+ }
+
+ Buffer = new byte[bufferSize];
+// bufOff = 0;
+ }
+
+
+ ///
+ /// Process one byte of data.
+ ///
+ /// The byte.
+ /// An array to store output in.
+ /// Offset within output array to start writing from.
+ ///
+ public int ProcessByte(
+ byte input,
+ byte[] outBytes,
+ int outOff)
+ {
+ int resultLen = 0;
+
+ Buffer[bufOff++] = input;
+
+ if (bufOff == Buffer.Length)
+ {
+ resultLen = translator.Encode(Buffer, 0, Buffer.Length, outBytes, outOff);
+ bufOff = 0;
+ }
+
+ return resultLen;
+ }
+
+ ///
+ /// Process data from a byte array.
+ ///
+ /// Input data Byte array containing data to be processed.
+ /// Start position within input data array.
+ /// Amount of input data to be processed.
+ /// Output data array.
+ /// Offset within output data array to start writing to.
+ /// The amount of data written.
+ public int ProcessBytes(
+ byte[] input,
+ int inOff,
+ int len,
+ byte[] outBytes,
+ int outOff)
+ {
+ if (len < 0)
+ {
+ throw new ArgumentException("Can't have a negative input length!");
+ }
+
+ int resultLen = 0;
+ int gapLen = Buffer.Length - bufOff;
+
+ if (len > gapLen)
+ {
+ Array.Copy(input, inOff, Buffer, bufOff, gapLen);
+
+ resultLen += translator.Encode(Buffer, 0, Buffer.Length, outBytes, outOff);
+
+ bufOff = 0;
+
+ len -= gapLen;
+ inOff += gapLen;
+ outOff += resultLen;
+
+ int chunkSize = len - (len % Buffer.Length);
+
+ resultLen += translator.Encode(input, inOff, chunkSize, outBytes, outOff);
+
+ len -= chunkSize;
+ inOff += chunkSize;
+ }
+
+ if (len != 0)
+ {
+ Array.Copy(input, inOff, Buffer, bufOff, len);
+
+ bufOff += len;
+ }
+
+ return resultLen;
+ }
+ }
+
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/BufferedEncoder.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/BufferedEncoder.cs.meta
new file mode 100644
index 00000000..36956819
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/BufferedEncoder.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 53ece357fad218446b6823b06ffea94d
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/Hex.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/Hex.cs
new file mode 100644
index 00000000..7d695266
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/Hex.cs
@@ -0,0 +1,134 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+using System.Text;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders
+{
+ ///
+ /// Class to decode and encode Hex.
+ ///
+ public sealed class Hex
+ {
+ private static readonly IEncoder encoder = new HexEncoder();
+
+ private Hex()
+ {
+ }
+
+ public static string ToHexString(
+ byte[] data)
+ {
+ return ToHexString(data, 0, data.Length);
+ }
+
+ public static string ToHexString(
+ byte[] data,
+ int off,
+ int length)
+ {
+ byte[] hex = Encode(data, off, length);
+ return Strings.FromAsciiByteArray(hex);
+ }
+
+ /**
+ * encode the input data producing a Hex encoded byte array.
+ *
+ * @return a byte array containing the Hex encoded data.
+ */
+ public static byte[] Encode(
+ byte[] data)
+ {
+ return Encode(data, 0, data.Length);
+ }
+
+ /**
+ * encode the input data producing a Hex encoded byte array.
+ *
+ * @return a byte array containing the Hex encoded data.
+ */
+ public static byte[] Encode(
+ byte[] data,
+ int off,
+ int length)
+ {
+ MemoryStream bOut = new MemoryStream(length * 2);
+
+ encoder.Encode(data, off, length, bOut);
+
+ return bOut.ToArray();
+ }
+
+ /**
+ * Hex encode the byte data writing it to the given output stream.
+ *
+ * @return the number of bytes produced.
+ */
+ public static int Encode(
+ byte[] data,
+ Stream outStream)
+ {
+ return encoder.Encode(data, 0, data.Length, outStream);
+ }
+
+ /**
+ * Hex encode the byte data writing it to the given output stream.
+ *
+ * @return the number of bytes produced.
+ */
+ public static int Encode(
+ byte[] data,
+ int off,
+ int length,
+ Stream outStream)
+ {
+ return encoder.Encode(data, off, length, outStream);
+ }
+
+ /**
+ * decode the Hex encoded input data. It is assumed the input data is valid.
+ *
+ * @return a byte array representing the decoded data.
+ */
+ public static byte[] Decode(
+ byte[] data)
+ {
+ MemoryStream bOut = new MemoryStream((data.Length + 1) / 2);
+
+ encoder.Decode(data, 0, data.Length, bOut);
+
+ return bOut.ToArray();
+ }
+
+ /**
+ * decode the Hex encoded string data - whitespace will be ignored.
+ *
+ * @return a byte array representing the decoded data.
+ */
+ public static byte[] Decode(
+ string data)
+ {
+ MemoryStream bOut = new MemoryStream((data.Length + 1) / 2);
+
+ encoder.DecodeString(data, bOut);
+
+ return bOut.ToArray();
+ }
+
+ /**
+ * decode the Hex encoded string data writing it to the given output stream,
+ * whitespace characters will be ignored.
+ *
+ * @return the number of bytes produced.
+ */
+ public static int Decode(
+ string data,
+ Stream outStream)
+ {
+ return encoder.DecodeString(data, outStream);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/Hex.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/Hex.cs.meta
new file mode 100644
index 00000000..2748cccb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/Hex.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 5ed222e1db807254592957eb36667273
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/HexEncoder.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/HexEncoder.cs
new file mode 100644
index 00000000..9fd07a43
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/HexEncoder.cs
@@ -0,0 +1,180 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders
+{
+ public class HexEncoder
+ : IEncoder
+ {
+ protected readonly byte[] encodingTable =
+ {
+ (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7',
+ (byte)'8', (byte)'9', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f'
+ };
+
+ /*
+ * set up the decoding table.
+ */
+ protected readonly byte[] decodingTable = new byte[128];
+
+ protected void InitialiseDecodingTable()
+ {
+ Arrays.Fill(decodingTable, (byte)0xff);
+
+ for (int i = 0; i < encodingTable.Length; i++)
+ {
+ decodingTable[encodingTable[i]] = (byte)i;
+ }
+
+ decodingTable['A'] = decodingTable['a'];
+ decodingTable['B'] = decodingTable['b'];
+ decodingTable['C'] = decodingTable['c'];
+ decodingTable['D'] = decodingTable['d'];
+ decodingTable['E'] = decodingTable['e'];
+ decodingTable['F'] = decodingTable['f'];
+ }
+
+ public HexEncoder()
+ {
+ InitialiseDecodingTable();
+ }
+
+ /**
+ * encode the input data producing a Hex output stream.
+ *
+ * @return the number of bytes produced.
+ */
+ public int Encode(
+ byte[] data,
+ int off,
+ int length,
+ Stream outStream)
+ {
+ for (int i = off; i < (off + length); i++)
+ {
+ int v = data[i];
+
+ outStream.WriteByte(encodingTable[v >> 4]);
+ outStream.WriteByte(encodingTable[v & 0xf]);
+ }
+
+ return length * 2;
+ }
+
+ private static bool Ignore(char c)
+ {
+ return c == '\n' || c =='\r' || c == '\t' || c == ' ';
+ }
+
+ /**
+ * decode the Hex encoded byte data writing it to the given output stream,
+ * whitespace characters will be ignored.
+ *
+ * @return the number of bytes produced.
+ */
+ public int Decode(
+ byte[] data,
+ int off,
+ int length,
+ Stream outStream)
+ {
+ byte b1, b2;
+ int outLen = 0;
+ int end = off + length;
+
+ while (end > off)
+ {
+ if (!Ignore((char)data[end - 1]))
+ {
+ break;
+ }
+
+ end--;
+ }
+
+ int i = off;
+ while (i < end)
+ {
+ while (i < end && Ignore((char)data[i]))
+ {
+ i++;
+ }
+
+ b1 = decodingTable[data[i++]];
+
+ while (i < end && Ignore((char)data[i]))
+ {
+ i++;
+ }
+
+ b2 = decodingTable[data[i++]];
+
+ if ((b1 | b2) >= 0x80)
+ throw new IOException("invalid characters encountered in Hex data");
+
+ outStream.WriteByte((byte)((b1 << 4) | b2));
+
+ outLen++;
+ }
+
+ return outLen;
+ }
+
+ /**
+ * decode the Hex encoded string data writing it to the given output stream,
+ * whitespace characters will be ignored.
+ *
+ * @return the number of bytes produced.
+ */
+ public int DecodeString(
+ string data,
+ Stream outStream)
+ {
+ byte b1, b2;
+ int length = 0;
+
+ int end = data.Length;
+
+ while (end > 0)
+ {
+ if (!Ignore(data[end - 1]))
+ {
+ break;
+ }
+
+ end--;
+ }
+
+ int i = 0;
+ while (i < end)
+ {
+ while (i < end && Ignore(data[i]))
+ {
+ i++;
+ }
+
+ b1 = decodingTable[data[i++]];
+
+ while (i < end && Ignore(data[i]))
+ {
+ i++;
+ }
+
+ b2 = decodingTable[data[i++]];
+
+ if ((b1 | b2) >= 0x80)
+ throw new IOException("invalid characters encountered in Hex data");
+
+ outStream.WriteByte((byte)((b1 << 4) | b2));
+
+ length++;
+ }
+
+ return length;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/HexEncoder.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/HexEncoder.cs.meta
new file mode 100644
index 00000000..d585633d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/HexEncoder.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 05d0f6c3caab0a549b8c1067b01bcbb2
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/HexTranslator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/HexTranslator.cs
new file mode 100644
index 00000000..c2d218df
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/HexTranslator.cs
@@ -0,0 +1,112 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders
+{
+ ///
+ /// A hex translator.
+ ///
+ public class HexTranslator : ITranslator
+ {
+ private static readonly byte[] hexTable =
+ {
+ (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7',
+ (byte)'8', (byte)'9', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f'
+ };
+
+ ///
+ /// Return encoded block size.
+ ///
+ /// 2
+ public int GetEncodedBlockSize()
+ {
+ return 2;
+ }
+
+ ///
+ /// Encode some data.
+ ///
+ /// Input data array.
+ /// Start position within input data array.
+ /// The amount of data to process.
+ /// The output data array.
+ /// The offset within the output data array to start writing from.
+ /// Amount of data encoded.
+ public int Encode(
+ byte[] input,
+ int inOff,
+ int length,
+ byte[] outBytes,
+ int outOff)
+ {
+ for (int i = 0, j = 0; i < length; i++, j += 2)
+ {
+ outBytes[outOff + j] = hexTable[(input[inOff] >> 4) & 0x0f];
+ outBytes[outOff + j + 1] = hexTable[input[inOff] & 0x0f];
+
+ inOff++;
+ }
+
+ return length * 2;
+ }
+
+ ///
+ /// Returns the decoded block size.
+ ///
+ /// 1
+ public int GetDecodedBlockSize()
+ {
+ return 1;
+ }
+
+ ///
+ /// Decode data from a byte array.
+ ///
+ /// The input data array.
+ /// Start position within input data array.
+ /// The amounty of data to process.
+ /// The output data array.
+ /// The position within the output data array to start writing from.
+ /// The amount of data written.
+ public int Decode(
+ byte[] input,
+ int inOff,
+ int length,
+ byte[] outBytes,
+ int outOff)
+ {
+ int halfLength = length / 2;
+ byte left, right;
+ for (int i = 0; i < halfLength; i++)
+ {
+ left = input[inOff + i * 2];
+ right = input[inOff + i * 2 + 1];
+
+ if (left < (byte)'a')
+ {
+ outBytes[outOff] = (byte)((left - '0') << 4);
+ }
+ else
+ {
+ outBytes[outOff] = (byte)((left - 'a' + 10) << 4);
+ }
+ if (right < (byte)'a')
+ {
+ outBytes[outOff] += (byte)(right - '0');
+ }
+ else
+ {
+ outBytes[outOff] += (byte)(right - 'a' + 10);
+ }
+
+ outOff++;
+ }
+
+ return halfLength;
+ }
+ }
+
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/HexTranslator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/HexTranslator.cs.meta
new file mode 100644
index 00000000..38b3100b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/HexTranslator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a4cfe8d15199522458337f90de553550
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/IEncoder.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/IEncoder.cs
new file mode 100644
index 00000000..80fc0a5d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/IEncoder.cs
@@ -0,0 +1,22 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders
+{
+ /**
+ * Encode and decode byte arrays (typically from binary to 7-bit ASCII
+ * encodings).
+ */
+ public interface IEncoder
+ {
+ int Encode(byte[] data, int off, int length, Stream outStream);
+
+ int Decode(byte[] data, int off, int length, Stream outStream);
+
+ int DecodeString(string data, Stream outStream);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/IEncoder.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/IEncoder.cs.meta
new file mode 100644
index 00000000..928cc8f3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/IEncoder.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 2e240a99386c56d4c833831f5247b554
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/Translator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/Translator.cs
new file mode 100644
index 00000000..fc3c50ad
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/Translator.cs
@@ -0,0 +1,23 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders
+{
+ ///
+ /// Translator interface.
+ ///
+ public interface ITranslator
+ {
+ int GetEncodedBlockSize();
+
+ int Encode(byte[] input, int inOff, int length, byte[] outBytes, int outOff);
+
+ int GetDecodedBlockSize();
+
+ int Decode(byte[] input, int inOff, int length, byte[] outBytes, int outOff);
+ }
+
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/Translator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/Translator.cs.meta
new file mode 100644
index 00000000..78ceb015
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/Translator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: fd4d0e7a77106f047a8aab6380c5e046
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/UrlBase64.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/UrlBase64.cs
new file mode 100644
index 00000000..b065d8a1
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/UrlBase64.cs
@@ -0,0 +1,131 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders
+{
+ /**
+ * Convert binary data to and from UrlBase64 encoding. This is identical to
+ * Base64 encoding, except that the padding character is "." and the other
+ * non-alphanumeric characters are "-" and "_" instead of "+" and "/".
+ *
+ * The purpose of UrlBase64 encoding is to provide a compact encoding of binary
+ * data that is safe for use as an URL parameter. Base64 encoding does not
+ * produce encoded values that are safe for use in URLs, since "/" can be
+ * interpreted as a path delimiter; "+" is the encoded form of a space; and
+ * "=" is used to separate a name from the corresponding value in an URL
+ * parameter.
+ *
+ */
+ public class UrlBase64
+ {
+ private static readonly IEncoder encoder = new UrlBase64Encoder();
+
+ /**
+ * Encode the input data producing a URL safe base 64 encoded byte array.
+ *
+ * @return a byte array containing the URL safe base 64 encoded data.
+ */
+ public static byte[] Encode(
+ byte[] data)
+ {
+ MemoryStream bOut = new MemoryStream();
+
+ try
+ {
+ encoder.Encode(data, 0, data.Length, bOut);
+ }
+ catch (IOException e)
+ {
+ throw new Exception("exception encoding URL safe base64 string: " + e.Message, e);
+ }
+
+ return bOut.ToArray();
+ }
+
+ /**
+ * Encode the byte data writing it to the given output stream.
+ *
+ * @return the number of bytes produced.
+ */
+ public static int Encode(
+ byte[] data,
+ Stream outStr)
+ {
+ return encoder.Encode(data, 0, data.Length, outStr);
+ }
+
+ /**
+ * Decode the URL safe base 64 encoded input data - white space will be ignored.
+ *
+ * @return a byte array representing the decoded data.
+ */
+ public static byte[] Decode(
+ byte[] data)
+ {
+ MemoryStream bOut = new MemoryStream();
+
+ try
+ {
+ encoder.Decode(data, 0, data.Length, bOut);
+ }
+ catch (IOException e)
+ {
+ throw new Exception("exception decoding URL safe base64 string: " + e.Message, e);
+ }
+
+ return bOut.ToArray();
+ }
+
+ /**
+ * decode the URL safe base 64 encoded byte data writing it to the given output stream,
+ * whitespace characters will be ignored.
+ *
+ * @return the number of bytes produced.
+ */
+ public static int Decode(
+ byte[] data,
+ Stream outStr)
+ {
+ return encoder.Decode(data, 0, data.Length, outStr);
+ }
+
+ /**
+ * decode the URL safe base 64 encoded string data - whitespace will be ignored.
+ *
+ * @return a byte array representing the decoded data.
+ */
+ public static byte[] Decode(
+ string data)
+ {
+ MemoryStream bOut = new MemoryStream();
+
+ try
+ {
+ encoder.DecodeString(data, bOut);
+ }
+ catch (IOException e)
+ {
+ throw new Exception("exception decoding URL safe base64 string: " + e.Message, e);
+ }
+
+ return bOut.ToArray();
+ }
+
+ /**
+ * Decode the URL safe base 64 encoded string data writing it to the given output stream,
+ * whitespace characters will be ignored.
+ *
+ * @return the number of bytes produced.
+ */
+ public static int Decode(
+ string data,
+ Stream outStr)
+ {
+ return encoder.DecodeString(data, outStr);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/UrlBase64.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/UrlBase64.cs.meta
new file mode 100644
index 00000000..65dc9004
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/UrlBase64.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 3b90f1cc819741c42aa20ee7dee4e85a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/UrlBase64Encoder.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/UrlBase64Encoder.cs
new file mode 100644
index 00000000..1a9961cc
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/UrlBase64Encoder.cs
@@ -0,0 +1,35 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders
+{
+ /**
+ * Convert binary data to and from UrlBase64 encoding. This is identical to
+ * Base64 encoding, except that the padding character is "." and the other
+ * non-alphanumeric characters are "-" and "_" instead of "+" and "/".
+ *
+ * The purpose of UrlBase64 encoding is to provide a compact encoding of binary
+ * data that is safe for use as an URL parameter. Base64 encoding does not
+ * produce encoded values that are safe for use in URLs, since "/" can be
+ * interpreted as a path delimiter; "+" is the encoded form of a space; and
+ * "=" is used to separate a name from the corresponding value in an URL
+ * parameter.
+ *
+ */
+ public class UrlBase64Encoder
+ : Base64Encoder
+ {
+ public UrlBase64Encoder()
+ {
+ encodingTable[encodingTable.Length - 2] = (byte) '-';
+ encodingTable[encodingTable.Length - 1] = (byte) '_';
+ padding = (byte) '.';
+ // we must re-create the decoding table with the new encoded values.
+ InitialiseDecodingTable();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/UrlBase64Encoder.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/UrlBase64Encoder.cs.meta
new file mode 100644
index 00000000..538c1eb7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/encoders/UrlBase64Encoder.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 39a7d129d5716d94db71754607e15ec5
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io.meta
new file mode 100644
index 00000000..d963f375
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 8d0ebd9539721c34daaadeafccd8ed9d
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/BaseInputStream.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/BaseInputStream.cs
new file mode 100644
index 00000000..024694f3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/BaseInputStream.cs
@@ -0,0 +1,68 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Diagnostics;
+using System.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO
+{
+ public abstract class BaseInputStream : Stream
+ {
+ private bool closed;
+
+ public sealed override bool CanRead { get { return !closed; } }
+ public sealed override bool CanSeek { get { return false; } }
+ public sealed override bool CanWrite { get { return false; } }
+
+#if PORTABLE || NETFX_CORE
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ closed = true;
+ }
+ base.Dispose(disposing);
+ }
+#else
+ public override void Close()
+ {
+ closed = true;
+ base.Close();
+ }
+#endif
+
+ public sealed override void Flush() {}
+ public sealed override long Length { get { throw new NotSupportedException(); } }
+ public sealed override long Position
+ {
+ get { throw new NotSupportedException(); }
+ set { throw new NotSupportedException(); }
+ }
+
+ public override int Read(byte[] buffer, int offset, int count)
+ {
+ int pos = offset;
+ try
+ {
+ int end = offset + count;
+ while (pos < end)
+ {
+ int b = ReadByte();
+ if (b == -1) break;
+ buffer[pos++] = (byte) b;
+ }
+ }
+ catch (IOException)
+ {
+ if (pos == offset) throw;
+ }
+ return pos - offset;
+ }
+
+ public sealed override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); }
+ public sealed override void SetLength(long value) { throw new NotSupportedException(); }
+ public sealed override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/BaseInputStream.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/BaseInputStream.cs.meta
new file mode 100644
index 00000000..f860ae92
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/BaseInputStream.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 6c55c7018496d63408687d3da511e3ea
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/BaseOutputStream.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/BaseOutputStream.cs
new file mode 100644
index 00000000..5536de25
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/BaseOutputStream.cs
@@ -0,0 +1,73 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Diagnostics;
+using System.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO
+{
+ public abstract class BaseOutputStream : Stream
+ {
+ private bool closed;
+
+ public sealed override bool CanRead { get { return false; } }
+ public sealed override bool CanSeek { get { return false; } }
+ public sealed override bool CanWrite { get { return !closed; } }
+
+#if PORTABLE || NETFX_CORE
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ closed = true;
+ }
+ base.Dispose(disposing);
+ }
+#else
+ public override void Close()
+ {
+ closed = true;
+ base.Close();
+ }
+#endif
+
+ public override void Flush() { }
+ public sealed override long Length { get { throw new NotSupportedException(); } }
+ public sealed override long Position
+ {
+ get { throw new NotSupportedException(); }
+ set { throw new NotSupportedException(); }
+ }
+ public sealed override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); }
+ public sealed override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); }
+ public sealed override void SetLength(long value) { throw new NotSupportedException(); }
+
+ public override void Write(byte[] buffer, int offset, int count)
+ {
+ Debug.Assert(buffer != null);
+ Debug.Assert(0 <= offset && offset <= buffer.Length);
+ Debug.Assert(count >= 0);
+
+ int end = offset + count;
+
+ Debug.Assert(0 <= end && end <= buffer.Length);
+
+ for (int i = offset; i < end; ++i)
+ {
+ this.WriteByte(buffer[i]);
+ }
+ }
+
+ public virtual void Write(params byte[] buffer)
+ {
+ Write(buffer, 0, buffer.Length);
+ }
+
+ public override void WriteByte(byte b)
+ {
+ Write(new byte[]{ b }, 0, 1);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/BaseOutputStream.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/BaseOutputStream.cs.meta
new file mode 100644
index 00000000..ff2cd329
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/BaseOutputStream.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 8a6aa30f111ed30408694c452b3e0947
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/FilterStream.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/FilterStream.cs
new file mode 100644
index 00000000..4fe84862
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/FilterStream.cs
@@ -0,0 +1,82 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO
+{
+ public class FilterStream : Stream
+ {
+ public FilterStream(Stream s)
+ {
+ this.s = s;
+ }
+ public override bool CanRead
+ {
+ get { return s.CanRead; }
+ }
+ public override bool CanSeek
+ {
+ get { return s.CanSeek; }
+ }
+ public override bool CanWrite
+ {
+ get { return s.CanWrite; }
+ }
+ public override long Length
+ {
+ get { return s.Length; }
+ }
+ public override long Position
+ {
+ get { return s.Position; }
+ set { s.Position = value; }
+ }
+#if PORTABLE || NETFX_CORE
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(s);
+ }
+ base.Dispose(disposing);
+ }
+#else
+ public override void Close()
+ {
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(s);
+ base.Close();
+ }
+#endif
+ public override void Flush()
+ {
+ s.Flush();
+ }
+ public override long Seek(long offset, SeekOrigin origin)
+ {
+ return s.Seek(offset, origin);
+ }
+ public override void SetLength(long value)
+ {
+ s.SetLength(value);
+ }
+ public override int Read(byte[] buffer, int offset, int count)
+ {
+ return s.Read(buffer, offset, count);
+ }
+ public override int ReadByte()
+ {
+ return s.ReadByte();
+ }
+ public override void Write(byte[] buffer, int offset, int count)
+ {
+ s.Write(buffer, offset, count);
+ }
+ public override void WriteByte(byte value)
+ {
+ s.WriteByte(value);
+ }
+ protected readonly Stream s;
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/FilterStream.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/FilterStream.cs.meta
new file mode 100644
index 00000000..4c41df04
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/FilterStream.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 3fce67f814432d848a840ddec287f366
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/NullOutputStream.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/NullOutputStream.cs
new file mode 100644
index 00000000..3dc5c89b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/NullOutputStream.cs
@@ -0,0 +1,22 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO
+{
+ internal class NullOutputStream
+ : BaseOutputStream
+ {
+ public override void WriteByte(byte b)
+ {
+ // do nothing
+ }
+
+ public override void Write(byte[] buffer, int offset, int count)
+ {
+ // do nothing
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/NullOutputStream.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/NullOutputStream.cs.meta
new file mode 100644
index 00000000..2a6b930c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/NullOutputStream.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: e1ee11a15bc038f4993c637d576ef943
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/PushbackStream.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/PushbackStream.cs
new file mode 100644
index 00000000..85b666bc
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/PushbackStream.cs
@@ -0,0 +1,56 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO
+{
+ public class PushbackStream
+ : FilterStream
+ {
+ private int buf = -1;
+
+ public PushbackStream(
+ Stream s)
+ : base(s)
+ {
+ }
+
+ public override int ReadByte()
+ {
+ if (buf != -1)
+ {
+ int tmp = buf;
+ buf = -1;
+ return tmp;
+ }
+
+ return base.ReadByte();
+ }
+
+ public override int Read(byte[] buffer, int offset, int count)
+ {
+ if (buf != -1 && count > 0)
+ {
+ // TODO Can this case be made more efficient?
+ buffer[offset] = (byte) buf;
+ buf = -1;
+ return 1;
+ }
+
+ return base.Read(buffer, offset, count);
+ }
+
+ public virtual void Unread(int b)
+ {
+ if (buf != -1)
+ throw new InvalidOperationException("Can only push back one byte");
+
+ buf = b & 0xFF;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/PushbackStream.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/PushbackStream.cs.meta
new file mode 100644
index 00000000..bca52c14
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/PushbackStream.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 43f5f3bf52001c342945b5bb8fd8fa9f
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/StreamOverflowException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/StreamOverflowException.cs
new file mode 100644
index 00000000..97218c17
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/StreamOverflowException.cs
@@ -0,0 +1,34 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO
+{
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class StreamOverflowException
+ : IOException
+ {
+ public StreamOverflowException()
+ : base()
+ {
+ }
+
+ public StreamOverflowException(
+ string message)
+ : base(message)
+ {
+ }
+
+ public StreamOverflowException(
+ string message,
+ Exception exception)
+ : base(message, exception)
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/StreamOverflowException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/StreamOverflowException.cs.meta
new file mode 100644
index 00000000..fa266080
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/StreamOverflowException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: f9bebbf770f250c4ab5bd25ef8f384a7
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/Streams.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/Streams.cs
new file mode 100644
index 00000000..e8a4916f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/Streams.cs
@@ -0,0 +1,129 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO
+{
+ public sealed class Streams
+ {
+ private const int BufferSize = 512;
+
+ private Streams()
+ {
+ }
+
+ public static void Drain(Stream inStr)
+ {
+ byte[] bs = new byte[BufferSize];
+ while (inStr.Read(bs, 0, bs.Length) > 0)
+ {
+ }
+ }
+
+ public static byte[] ReadAll(Stream inStr)
+ {
+ MemoryStream buf = new MemoryStream();
+ PipeAll(inStr, buf);
+ return buf.ToArray();
+ }
+
+ public static byte[] ReadAllLimited(Stream inStr, int limit)
+ {
+ MemoryStream buf = new MemoryStream();
+ PipeAllLimited(inStr, limit, buf);
+ return buf.ToArray();
+ }
+
+ public static int ReadFully(Stream inStr, byte[] buf)
+ {
+ return ReadFully(inStr, buf, 0, buf.Length);
+ }
+
+ public static int ReadFully(Stream inStr, byte[] buf, int off, int len)
+ {
+ int totalRead = 0;
+ while (totalRead < len)
+ {
+ int numRead = inStr.Read(buf, off + totalRead, len - totalRead);
+ if (numRead < 1)
+ break;
+ totalRead += numRead;
+ }
+ return totalRead;
+ }
+
+ public static void PipeAll(Stream inStr, Stream outStr)
+ {
+ byte[] bs = new byte[BufferSize];
+ int numRead;
+ while ((numRead = inStr.Read(bs, 0, bs.Length)) > 0)
+ {
+ outStr.Write(bs, 0, numRead);
+ }
+ }
+
+ ///
+ /// Pipe all bytes from inStr to outStr, throwing StreamFlowException if greater
+ /// than limit bytes in inStr.
+ ///
+ ///
+ /// A
+ ///
+ ///
+ /// A
+ ///
+ ///
+ /// A
+ ///
+ /// The number of bytes actually transferred, if not greater than limit
+ ///
+ public static long PipeAllLimited(Stream inStr, long limit, Stream outStr)
+ {
+ byte[] bs = new byte[BufferSize];
+ long total = 0;
+ int numRead;
+ while ((numRead = inStr.Read(bs, 0, bs.Length)) > 0)
+ {
+ if ((limit - total) < numRead)
+ throw new StreamOverflowException("Data Overflow");
+ total += numRead;
+ outStr.Write(bs, 0, numRead);
+ }
+ return total;
+ }
+
+ ///
+ public static void WriteBufTo(MemoryStream buf, Stream output)
+ {
+ buf.WriteTo(output);
+ }
+
+ ///
+ public static int WriteBufTo(MemoryStream buf, byte[] output, int offset)
+ {
+#if PORTABLE || NETFX_CORE
+ byte[] bytes = buf.ToArray();
+ bytes.CopyTo(output, offset);
+ return bytes.Length;
+#else
+ int size = (int)buf.Length;
+ buf.WriteTo(new MemoryStream(output, offset, size, true));
+ return size;
+#endif
+ }
+
+ public static void WriteZeroes(Stream outStr, long count)
+ {
+ byte[] zeroes = new byte[BufferSize];
+ while (count > BufferSize)
+ {
+ outStr.Write(zeroes, 0, BufferSize);
+ count -= BufferSize;
+ }
+ outStr.Write(zeroes, 0, (int)count);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/Streams.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/Streams.cs.meta
new file mode 100644
index 00000000..8924fc4e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/Streams.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 7009443e85a87f4499c540687b6cb8c4
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/TeeInputStream.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/TeeInputStream.cs
new file mode 100644
index 00000000..1f0d169e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/TeeInputStream.cs
@@ -0,0 +1,68 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Diagnostics;
+using System.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO
+{
+ public class TeeInputStream
+ : BaseInputStream
+ {
+ private readonly Stream input, tee;
+
+ public TeeInputStream(Stream input, Stream tee)
+ {
+ Debug.Assert(input.CanRead);
+ Debug.Assert(tee.CanWrite);
+
+ this.input = input;
+ this.tee = tee;
+ }
+
+#if PORTABLE || NETFX_CORE
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(input);
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(tee);
+ }
+ base.Dispose(disposing);
+ }
+#else
+ public override void Close()
+ {
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(input);
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(tee);
+ base.Close();
+ }
+#endif
+
+ public override int Read(byte[] buf, int off, int len)
+ {
+ int i = input.Read(buf, off, len);
+
+ if (i > 0)
+ {
+ tee.Write(buf, off, i);
+ }
+
+ return i;
+ }
+
+ public override int ReadByte()
+ {
+ int i = input.ReadByte();
+
+ if (i >= 0)
+ {
+ tee.WriteByte((byte)i);
+ }
+
+ return i;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/TeeInputStream.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/TeeInputStream.cs.meta
new file mode 100644
index 00000000..a6ab6270
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/TeeInputStream.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ae88e55e5d7dac54aa31654c14619f10
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/TeeOutputStream.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/TeeOutputStream.cs
new file mode 100644
index 00000000..c19eb288
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/TeeOutputStream.cs
@@ -0,0 +1,56 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Diagnostics;
+using System.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO
+{
+ public class TeeOutputStream
+ : BaseOutputStream
+ {
+ private readonly Stream output, tee;
+
+ public TeeOutputStream(Stream output, Stream tee)
+ {
+ Debug.Assert(output.CanWrite);
+ Debug.Assert(tee.CanWrite);
+
+ this.output = output;
+ this.tee = tee;
+ }
+
+#if PORTABLE || NETFX_CORE
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(output);
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(tee);
+ }
+ base.Dispose(disposing);
+ }
+#else
+ public override void Close()
+ {
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(output);
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(tee);
+ base.Close();
+ }
+#endif
+
+ public override void Write(byte[] buffer, int offset, int count)
+ {
+ output.Write(buffer, offset, count);
+ tee.Write(buffer, offset, count);
+ }
+
+ public override void WriteByte(byte b)
+ {
+ output.WriteByte(b);
+ tee.WriteByte(b);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/TeeOutputStream.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/TeeOutputStream.cs.meta
new file mode 100644
index 00000000..a2c47db6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/TeeOutputStream.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 94d20141b69679e4293e7365906dbe4b
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem.meta
new file mode 100644
index 00000000..64312356
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: facfbd283a257c247b7788a4852da32a
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemGenerationException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemGenerationException.cs
new file mode 100644
index 00000000..aac38dc0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemGenerationException.cs
@@ -0,0 +1,33 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO.Pem
+{
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class PemGenerationException
+ : Exception
+ {
+ public PemGenerationException()
+ : base()
+ {
+ }
+
+ public PemGenerationException(
+ string message)
+ : base(message)
+ {
+ }
+
+ public PemGenerationException(
+ string message,
+ Exception exception)
+ : base(message, exception)
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemGenerationException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemGenerationException.cs.meta
new file mode 100644
index 00000000..f8c7e60a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemGenerationException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: d64f3f17b41a69c4e9f8146e9a630aa6
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemHeader.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemHeader.cs
new file mode 100644
index 00000000..062df710
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemHeader.cs
@@ -0,0 +1,59 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO.Pem
+{
+ public class PemHeader
+ {
+ private string name;
+ private string val;
+
+ public PemHeader(string name, string val)
+ {
+ this.name = name;
+ this.val = val;
+ }
+
+ public virtual string Name
+ {
+ get { return name; }
+ }
+
+ public virtual string Value
+ {
+ get { return val; }
+ }
+
+ public override int GetHashCode()
+ {
+ return GetHashCode(this.name) + 31 * GetHashCode(this.val);
+ }
+
+ public override bool Equals(object obj)
+ {
+ if (obj == this)
+ return true;
+
+ if (!(obj is PemHeader))
+ return false;
+
+ PemHeader other = (PemHeader)obj;
+
+ return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(this.name, other.name)
+ && BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(this.val, other.val);
+ }
+
+ private int GetHashCode(string s)
+ {
+ if (s == null)
+ {
+ return 1;
+ }
+
+ return s.GetHashCode();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemHeader.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemHeader.cs.meta
new file mode 100644
index 00000000..5c0d2f1d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemHeader.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 6145fa38ebb0c79458ea0c15c317525d
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemObject.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemObject.cs
new file mode 100644
index 00000000..5d7b1dc2
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemObject.cs
@@ -0,0 +1,51 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO.Pem
+{
+ public class PemObject
+ : PemObjectGenerator
+ {
+ private string type;
+ private IList headers;
+ private byte[] content;
+
+ public PemObject(string type, byte[] content)
+ : this(type, BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(), content)
+ {
+ }
+
+ public PemObject(String type, IList headers, byte[] content)
+ {
+ this.type = type;
+ this.headers = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(headers);
+ this.content = content;
+ }
+
+ public string Type
+ {
+ get { return type; }
+ }
+
+ public IList Headers
+ {
+ get { return headers; }
+ }
+
+ public byte[] Content
+ {
+ get { return content; }
+ }
+
+ public PemObject Generate()
+ {
+ return this;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemObject.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemObject.cs.meta
new file mode 100644
index 00000000..3c0c8e0c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemObject.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: dd96e7dbd869965419cb9e8ee3aad2ec
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemObjectGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemObjectGenerator.cs
new file mode 100644
index 00000000..d2cfd8e2
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemObjectGenerator.cs
@@ -0,0 +1,17 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO.Pem
+{
+ public interface PemObjectGenerator
+ {
+ ///
+ /// A
+ ///
+ ///
+ PemObject Generate();
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemObjectGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemObjectGenerator.cs.meta
new file mode 100644
index 00000000..12f1a17a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemObjectGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ae784c7acdea52e429e2586f22f7d6ec
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemObjectParser.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemObjectParser.cs
new file mode 100644
index 00000000..ab465a49
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemObjectParser.cs
@@ -0,0 +1,21 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO.Pem
+{
+ public interface PemObjectParser
+ {
+ ///
+ /// A
+ ///
+ ///
+ /// A
+ ///
+ ///
+ object ParseObject(PemObject obj);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemObjectParser.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemObjectParser.cs.meta
new file mode 100644
index 00000000..71255e2e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemObjectParser.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 0ed04d49054ba1445bb5b1c03b5cc613
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemReader.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemReader.cs
new file mode 100644
index 00000000..197a7c9e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemReader.cs
@@ -0,0 +1,100 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO.Pem
+{
+ public class PemReader
+ {
+ private const string BeginString = "-----BEGIN ";
+ private const string EndString = "-----END ";
+
+ private readonly TextReader reader;
+
+ public PemReader(TextReader reader)
+ {
+ if (reader == null)
+ throw new ArgumentNullException("reader");
+
+ this.reader = reader;
+ }
+
+ public TextReader Reader
+ {
+ get { return reader; }
+ }
+
+ ///
+ /// A
+ ///
+ ///
+ public PemObject ReadPemObject()
+ {
+ string line = reader.ReadLine();
+
+ if (line != null && BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(line, BeginString))
+ {
+ line = line.Substring(BeginString.Length);
+ int index = line.IndexOf('-');
+ string type = line.Substring(0, index);
+
+ if (index > 0)
+ return LoadObject(type);
+ }
+
+ return null;
+ }
+
+ private PemObject LoadObject(string type)
+ {
+ string endMarker = EndString + type;
+ IList headers = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ StringBuilder buf = new StringBuilder();
+
+ string line;
+ while ((line = reader.ReadLine()) != null
+ && BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.IndexOf(line, endMarker) == -1)
+ {
+ int colonPos = line.IndexOf(':');
+
+ if (colonPos == -1)
+ {
+ buf.Append(line.Trim());
+ }
+ else
+ {
+ // Process field
+ string fieldName = line.Substring(0, colonPos).Trim();
+
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(fieldName, "X-"))
+ {
+ fieldName = fieldName.Substring(2);
+ }
+
+ string fieldValue = line.Substring(colonPos + 1).Trim();
+
+ headers.Add(new PemHeader(fieldName, fieldValue));
+ }
+ }
+
+ if (line == null)
+ {
+ throw new IOException(endMarker + " not found");
+ }
+
+ if (buf.Length % 4 != 0)
+ {
+ throw new IOException("base64 data appears to be truncated");
+ }
+
+ return new PemObject(type, headers, Base64.Decode(buf.ToString()));
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemReader.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemReader.cs.meta
new file mode 100644
index 00000000..088a495a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemReader.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: f26fdb1978588c94ba940413500381e6
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemWriter.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemWriter.cs
new file mode 100644
index 00000000..7074a049
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemWriter.cs
@@ -0,0 +1,124 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO.Pem
+{
+ /**
+ * A generic PEM writer, based on RFC 1421
+ */
+ public class PemWriter
+ {
+ private const int LineLength = 64;
+
+ private readonly TextWriter writer;
+ private readonly int nlLength;
+ private char[] buf = new char[LineLength];
+
+ /**
+ * Base constructor.
+ *
+ * @param out output stream to use.
+ */
+ public PemWriter(TextWriter writer)
+ {
+ if (writer == null)
+ throw new ArgumentNullException("writer");
+
+ this.writer = writer;
+ this.nlLength = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.NewLine.Length;
+ }
+
+ public TextWriter Writer
+ {
+ get { return writer; }
+ }
+
+ /**
+ * Return the number of bytes or characters required to contain the
+ * passed in object if it is PEM encoded.
+ *
+ * @param obj pem object to be output
+ * @return an estimate of the number of bytes
+ */
+ public int GetOutputSize(PemObject obj)
+ {
+ // BEGIN and END boundaries.
+ int size = (2 * (obj.Type.Length + 10 + nlLength)) + 6 + 4;
+
+ if (obj.Headers.Count > 0)
+ {
+ foreach (PemHeader header in obj.Headers)
+ {
+ size += header.Name.Length + ": ".Length + header.Value.Length + nlLength;
+ }
+
+ size += nlLength;
+ }
+
+ // base64 encoding
+ int dataLen = ((obj.Content.Length + 2) / 3) * 4;
+
+ size += dataLen + (((dataLen + LineLength - 1) / LineLength) * nlLength);
+
+ return size;
+ }
+
+ public void WriteObject(PemObjectGenerator objGen)
+ {
+ PemObject obj = objGen.Generate();
+
+ WritePreEncapsulationBoundary(obj.Type);
+
+ if (obj.Headers.Count > 0)
+ {
+ foreach (PemHeader header in obj.Headers)
+ {
+ writer.Write(header.Name);
+ writer.Write(": ");
+ writer.WriteLine(header.Value);
+ }
+
+ writer.WriteLine();
+ }
+
+ WriteEncoded(obj.Content);
+ WritePostEncapsulationBoundary(obj.Type);
+ }
+
+ private void WriteEncoded(byte[] bytes)
+ {
+ bytes = Base64.Encode(bytes);
+
+ for (int i = 0; i < bytes.Length; i += buf.Length)
+ {
+ int index = 0;
+ while (index != buf.Length)
+ {
+ if ((i + index) >= bytes.Length)
+ break;
+
+ buf[index] = (char)bytes[i + index];
+ index++;
+ }
+ writer.WriteLine(buf, 0, index);
+ }
+ }
+
+ private void WritePreEncapsulationBoundary(string type)
+ {
+ writer.WriteLine("-----BEGIN " + type + "-----");
+ }
+
+ private void WritePostEncapsulationBoundary(string type)
+ {
+ writer.WriteLine("-----END " + type + "-----");
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemWriter.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemWriter.cs.meta
new file mode 100644
index 00000000..b2fc9fa9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/io/pem/PemWriter.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 32f18cc53c19448418b7b334997da7a4
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/net.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/net.meta
new file mode 100644
index 00000000..59e27680
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/net.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: ef95faa5f016dcf42829616d382ec0fd
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/net/IPAddress.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/net/IPAddress.cs
new file mode 100644
index 00000000..e5a501c8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/net/IPAddress.cs
@@ -0,0 +1,201 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Globalization;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Net
+{
+ public class IPAddress
+ {
+ /**
+ * Validate the given IPv4 or IPv6 address.
+ *
+ * @param address the IP address as a string.
+ *
+ * @return true if a valid address, false otherwise
+ */
+ public static bool IsValid(
+ string address)
+ {
+ return IsValidIPv4(address) || IsValidIPv6(address);
+ }
+
+ /**
+ * Validate the given IPv4 or IPv6 address and netmask.
+ *
+ * @param address the IP address as a string.
+ *
+ * @return true if a valid address with netmask, false otherwise
+ */
+ public static bool IsValidWithNetMask(
+ string address)
+ {
+ return IsValidIPv4WithNetmask(address) || IsValidIPv6WithNetmask(address);
+ }
+
+ /**
+ * Validate the given IPv4 address.
+ *
+ * @param address the IP address as a string.
+ *
+ * @return true if a valid IPv4 address, false otherwise
+ */
+ public static bool IsValidIPv4(
+ string address)
+ {
+ try
+ {
+ return unsafeIsValidIPv4(address);
+ }
+ catch (FormatException) {}
+ catch (OverflowException) {}
+ return false;
+ }
+
+ private static bool unsafeIsValidIPv4(
+ string address)
+ {
+ if (address.Length == 0)
+ return false;
+
+ int octets = 0;
+ string temp = address + ".";
+
+ int pos;
+ int start = 0;
+ while (start < temp.Length
+ && (pos = temp.IndexOf('.', start)) > start)
+ {
+ if (octets == 4)
+ return false;
+
+ string octetStr = temp.Substring(start, pos - start);
+ int octet = Int32.Parse(octetStr);
+
+ if (octet < 0 || octet > 255)
+ return false;
+
+ start = pos + 1;
+ octets++;
+ }
+
+ return octets == 4;
+ }
+
+ public static bool IsValidIPv4WithNetmask(
+ string address)
+ {
+ int index = address.IndexOf('/');
+ string mask = address.Substring(index + 1);
+
+ return (index > 0) && IsValidIPv4(address.Substring(0, index))
+ && (IsValidIPv4(mask) || IsMaskValue(mask, 32));
+ }
+
+ public static bool IsValidIPv6WithNetmask(
+ string address)
+ {
+ int index = address.IndexOf('/');
+ string mask = address.Substring(index + 1);
+
+ return (index > 0) && (IsValidIPv6(address.Substring(0, index))
+ && (IsValidIPv6(mask) || IsMaskValue(mask, 128)));
+ }
+
+ private static bool IsMaskValue(
+ string component,
+ int size)
+ {
+ int val = Int32.Parse(component);
+ try
+ {
+ return val >= 0 && val <= size;
+ }
+ catch (FormatException) {}
+ catch (OverflowException) {}
+ return false;
+ }
+
+ /**
+ * Validate the given IPv6 address.
+ *
+ * @param address the IP address as a string.
+ *
+ * @return true if a valid IPv4 address, false otherwise
+ */
+ public static bool IsValidIPv6(
+ string address)
+ {
+ try
+ {
+ return unsafeIsValidIPv6(address);
+ }
+ catch (FormatException) {}
+ catch (OverflowException) {}
+ return false;
+ }
+
+ private static bool unsafeIsValidIPv6(
+ string address)
+ {
+ if (address.Length == 0)
+ {
+ return false;
+ }
+
+ int octets = 0;
+
+ string temp = address + ":";
+ bool doubleColonFound = false;
+ int pos;
+ int start = 0;
+ while (start < temp.Length
+ && (pos = temp.IndexOf(':', start)) >= start)
+ {
+ if (octets == 8)
+ {
+ return false;
+ }
+
+ if (start != pos)
+ {
+ string value = temp.Substring(start, pos - start);
+
+ if (pos == (temp.Length - 1) && value.IndexOf('.') > 0)
+ {
+ if (!IsValidIPv4(value))
+ {
+ return false;
+ }
+
+ octets++; // add an extra one as address covers 2 words.
+ }
+ else
+ {
+ string octetStr = temp.Substring(start, pos - start);
+ int octet = Int32.Parse(octetStr, NumberStyles.AllowHexSpecifier);
+
+ if (octet < 0 || octet > 0xffff)
+ return false;
+ }
+ }
+ else
+ {
+ if (pos != 1 && pos != temp.Length - 1 && doubleColonFound)
+ {
+ return false;
+ }
+ doubleColonFound = true;
+ }
+ start = pos + 1;
+ octets++;
+ }
+
+ return octets == 8 || doubleColonFound;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/net/IPAddress.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/net/IPAddress.cs.meta
new file mode 100644
index 00000000..00fbfebc
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/net/IPAddress.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c829f456cc2252e4da1989ca55f8c0b8
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib.meta
new file mode 100644
index 00000000..7218d6d8
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 4d3c9d4702c5ca34fa5b819f8f2c5850
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/Adler32.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/Adler32.cs
new file mode 100644
index 00000000..422d2674
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/Adler32.cs
@@ -0,0 +1,92 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+/*
+ * $Id: Adler32.cs,v 1.1 2006-07-31 13:59:25 bouncy Exp $
+ *
+Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the distribution.
+
+ 3. The names of the authors may not be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
+INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
+INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/*
+ * This program is based on zlib-1.1.3, so all credit should go authors
+ * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
+ * and contributors of zlib.
+ */
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Zlib {
+
+ internal sealed class Adler32{
+
+ // largest prime smaller than 65536
+ private const int BASE=65521;
+ // NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
+ private const int NMAX=5552;
+
+ internal long adler32(long adler, byte[] buf, int index, int len){
+ if(buf == null){ return 1L; }
+
+ long s1=adler&0xffff;
+ long s2=(adler>>16)&0xffff;
+ int k;
+
+ while(len > 0) {
+ k=len=16){
+ s1+=buf[index++]&0xff; s2+=s1;
+ s1+=buf[index++]&0xff; s2+=s1;
+ s1+=buf[index++]&0xff; s2+=s1;
+ s1+=buf[index++]&0xff; s2+=s1;
+ s1+=buf[index++]&0xff; s2+=s1;
+ s1+=buf[index++]&0xff; s2+=s1;
+ s1+=buf[index++]&0xff; s2+=s1;
+ s1+=buf[index++]&0xff; s2+=s1;
+ s1+=buf[index++]&0xff; s2+=s1;
+ s1+=buf[index++]&0xff; s2+=s1;
+ s1+=buf[index++]&0xff; s2+=s1;
+ s1+=buf[index++]&0xff; s2+=s1;
+ s1+=buf[index++]&0xff; s2+=s1;
+ s1+=buf[index++]&0xff; s2+=s1;
+ s1+=buf[index++]&0xff; s2+=s1;
+ s1+=buf[index++]&0xff; s2+=s1;
+ k-=16;
+ }
+ if(k!=0){
+ do{
+ s1+=buf[index++]&0xff; s2+=s1;
+ }
+ while(--k!=0);
+ }
+ s1%=BASE;
+ s2%=BASE;
+ }
+ return (s2<<16)|s1;
+ }
+
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/Adler32.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/Adler32.cs.meta
new file mode 100644
index 00000000..2b21780f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/Adler32.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 2cfff793e226e3941b78bc3b1d5a873b
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/Deflate.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/Deflate.cs
new file mode 100644
index 00000000..f960f482
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/Deflate.cs
@@ -0,0 +1,1644 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+/*
+ * $Id: Deflate.cs,v 1.2 2008-05-10 09:35:40 bouncy Exp $
+ *
+Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the distribution.
+
+ 3. The names of the authors may not be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
+INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
+INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/*
+ * This program is based on zlib-1.1.3, so all credit should go authors
+ * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
+ * and contributors of zlib.
+ */
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Zlib {
+
+ public sealed class Deflate{
+
+ private const int MAX_MEM_LEVEL=9;
+
+ private const int Z_DEFAULT_COMPRESSION=-1;
+
+ private const int MAX_WBITS=15; // 32K LZ77 window
+ private const int DEF_MEM_LEVEL=8;
+
+ internal class Config{
+ internal int good_length; // reduce lazy search above this match length
+ internal int max_lazy; // do not perform lazy search above this match length
+ internal int nice_length; // quit search above this match length
+ internal int max_chain;
+ internal int func;
+ internal Config(int good_length, int max_lazy,
+ int nice_length, int max_chain, int func){
+ this.good_length=good_length;
+ this.max_lazy=max_lazy;
+ this.nice_length=nice_length;
+ this.max_chain=max_chain;
+ this.func=func;
+ }
+ }
+
+ private const int STORED=0;
+ private const int FAST=1;
+ private const int SLOW=2;
+ private static readonly Config[] config_table;
+
+ static Deflate(){
+ config_table=new Config[10];
+ // good lazy nice chain
+ config_table[0]=new Config(0, 0, 0, 0, STORED);
+ config_table[1]=new Config(4, 4, 8, 4, FAST);
+ config_table[2]=new Config(4, 5, 16, 8, FAST);
+ config_table[3]=new Config(4, 6, 32, 32, FAST);
+
+ config_table[4]=new Config(4, 4, 16, 16, SLOW);
+ config_table[5]=new Config(8, 16, 32, 32, SLOW);
+ config_table[6]=new Config(8, 16, 128, 128, SLOW);
+ config_table[7]=new Config(8, 32, 128, 256, SLOW);
+ config_table[8]=new Config(32, 128, 258, 1024, SLOW);
+ config_table[9]=new Config(32, 258, 258, 4096, SLOW);
+ }
+
+ private static readonly String[] z_errmsg = {
+ "need dictionary", // Z_NEED_DICT 2
+ "stream end", // Z_STREAM_END 1
+ "", // Z_OK 0
+ "file error", // Z_ERRNO (-1)
+ "stream error", // Z_STREAM_ERROR (-2)
+ "data error", // Z_DATA_ERROR (-3)
+ "insufficient memory", // Z_MEM_ERROR (-4)
+ "buffer error", // Z_BUF_ERROR (-5)
+ "incompatible version",// Z_VERSION_ERROR (-6)
+ ""
+ };
+
+ // block not completed, need more input or more output
+ private const int NeedMore=0;
+
+ // block flush performed
+ private const int BlockDone=1;
+
+ // finish started, need only more output at next deflate
+ private const int FinishStarted=2;
+
+ // finish done, accept no more input or output
+ private const int FinishDone=3;
+
+ // preset dictionary flag in zlib header
+ private const int PRESET_DICT=0x20;
+
+ private const int Z_FILTERED=1;
+ private const int Z_HUFFMAN_ONLY=2;
+ private const int Z_DEFAULT_STRATEGY=0;
+
+ private const int Z_NO_FLUSH=0;
+ private const int Z_PARTIAL_FLUSH=1;
+ private const int Z_SYNC_FLUSH=2;
+ private const int Z_FULL_FLUSH=3;
+ private const int Z_FINISH=4;
+
+ private const int Z_OK=0;
+ private const int Z_STREAM_END=1;
+ private const int Z_NEED_DICT=2;
+ private const int Z_ERRNO=-1;
+ private const int Z_STREAM_ERROR=-2;
+ private const int Z_DATA_ERROR=-3;
+ private const int Z_MEM_ERROR=-4;
+ private const int Z_BUF_ERROR=-5;
+ private const int Z_VERSION_ERROR=-6;
+
+ private const int INIT_STATE=42;
+ private const int BUSY_STATE=113;
+ private const int FINISH_STATE=666;
+
+ // The deflate compression method
+ private const int Z_DEFLATED=8;
+
+ private const int STORED_BLOCK=0;
+ private const int STATIC_TREES=1;
+ private const int DYN_TREES=2;
+
+ // The three kinds of block type
+ private const int Z_BINARY=0;
+ private const int Z_ASCII=1;
+ private const int Z_UNKNOWN=2;
+
+ private const int Buf_size=8*2;
+
+ // repeat previous bit length 3-6 times (2 bits of repeat count)
+ private const int REP_3_6=16;
+
+ // repeat a zero length 3-10 times (3 bits of repeat count)
+ private const int REPZ_3_10=17;
+
+ // repeat a zero length 11-138 times (7 bits of repeat count)
+ private const int REPZ_11_138=18;
+
+ private const int MIN_MATCH=3;
+ private const int MAX_MATCH=258;
+ private const int MIN_LOOKAHEAD=(MAX_MATCH+MIN_MATCH+1);
+
+ private const int MAX_BITS=15;
+ private const int D_CODES=30;
+ private const int BL_CODES=19;
+ private const int LENGTH_CODES=29;
+ private const int LITERALS=256;
+ private const int L_CODES=(LITERALS+1+LENGTH_CODES);
+ private const int HEAP_SIZE=(2*L_CODES+1);
+
+ private const int END_BLOCK=256;
+
+ internal ZStream strm; // pointer back to this zlib stream
+ internal int status; // as the name implies
+ internal byte[] pending_buf; // output still pending
+ internal int pending_buf_size; // size of pending_buf
+ internal int pending_out; // next pending byte to output to the stream
+ internal int pending; // nb of bytes in the pending buffer
+ internal int noheader; // suppress zlib header and adler32
+ internal byte data_type; // UNKNOWN, BINARY or ASCII
+ internal byte method; // STORED (for zip only) or DEFLATED
+ internal int last_flush; // value of flush param for previous deflate call
+
+ internal int w_size; // LZ77 window size (32K by default)
+ internal int w_bits; // log2(w_size) (8..16)
+ internal int w_mask; // w_size - 1
+
+ internal byte[] window;
+ // Sliding window. Input bytes are read into the second half of the window,
+ // and move to the first half later to keep a dictionary of at least wSize
+ // bytes. With this organization, matches are limited to a distance of
+ // wSize-MAX_MATCH bytes, but this ensures that IO is always
+ // performed with a length multiple of the block size. Also, it limits
+ // the window size to 64K, which is quite useful on MSDOS.
+ // To do: use the user input buffer as sliding window.
+
+ internal int window_size;
+ // Actual size of window: 2*wSize, except when the user input buffer
+ // is directly used as sliding window.
+
+ internal short[] prev;
+ // Link to older string with same hash index. To limit the size of this
+ // array to 64K, this link is maintained only for the last 32K strings.
+ // An index in this array is thus a window index modulo 32K.
+
+ internal short[] head; // Heads of the hash chains or NIL.
+
+ internal int ins_h; // hash index of string to be inserted
+ internal int hash_size; // number of elements in hash table
+ internal int hash_bits; // log2(hash_size)
+ internal int hash_mask; // hash_size-1
+
+ // Number of bits by which ins_h must be shifted at each input
+ // step. It must be such that after MIN_MATCH steps, the oldest
+ // byte no longer takes part in the hash key, that is:
+ // hash_shift * MIN_MATCH >= hash_bits
+ internal int hash_shift;
+
+ // Window position at the beginning of the current output block. Gets
+ // negative when the window is moved backwards.
+
+ internal int block_start;
+
+ internal int match_length; // length of best match
+ internal int prev_match; // previous match
+ internal int match_available; // set if previous match exists
+ internal int strstart; // start of string to insert
+ internal int match_start; // start of matching string
+ internal int lookahead; // number of valid bytes ahead in window
+
+ // Length of the best match at previous step. Matches not greater than this
+ // are discarded. This is used in the lazy match evaluation.
+ internal int prev_length;
+
+ // To speed up deflation, hash chains are never searched beyond this
+ // length. A higher limit improves compression ratio but degrades the speed.
+ internal int max_chain_length;
+
+ // Attempt to find a better match only when the current match is strictly
+ // smaller than this value. This mechanism is used only for compression
+ // levels >= 4.
+ internal int max_lazy_match;
+
+ // Insert new strings in the hash table only if the match length is not
+ // greater than this length. This saves time but degrades compression.
+ // max_insert_length is used only for compression levels <= 3.
+
+ internal int level; // compression level (1..9)
+ internal int strategy; // favor or force Huffman coding
+
+ // Use a faster search when the previous match is longer than this
+ internal int good_match;
+
+ // Stop searching when current match exceeds this
+ internal int nice_match;
+
+ internal short[] dyn_ltree; // literal and length tree
+ internal short[] dyn_dtree; // distance tree
+ internal short[] bl_tree; // Huffman tree for bit lengths
+
+ internal ZTree l_desc=new ZTree(); // desc for literal tree
+ internal ZTree d_desc=new ZTree(); // desc for distance tree
+ internal ZTree bl_desc=new ZTree(); // desc for bit length tree
+
+ // number of codes at each bit length for an optimal tree
+ internal short[] bl_count=new short[MAX_BITS+1];
+
+ // heap used to build the Huffman trees
+ internal int[] heap=new int[2*L_CODES+1];
+
+ internal int heap_len; // number of elements in the heap
+ internal int heap_max; // element of largest frequency
+ // The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
+ // The same heap array is used to build all trees.
+
+ // Depth of each subtree used as tie breaker for trees of equal frequency
+ internal byte[] depth=new byte[2*L_CODES+1];
+
+ internal int l_buf; // index for literals or lengths */
+
+ // Size of match buffer for literals/lengths. There are 4 reasons for
+ // limiting lit_bufsize to 64K:
+ // - frequencies can be kept in 16 bit counters
+ // - if compression is not successful for the first block, all input
+ // data is still in the window so we can still emit a stored block even
+ // when input comes from standard input. (This can also be done for
+ // all blocks if lit_bufsize is not greater than 32K.)
+ // - if compression is not successful for a file smaller than 64K, we can
+ // even emit a stored file instead of a stored block (saving 5 bytes).
+ // This is applicable only for zip (not gzip or zlib).
+ // - creating new Huffman trees less frequently may not provide fast
+ // adaptation to changes in the input data statistics. (Take for
+ // example a binary file with poorly compressible code followed by
+ // a highly compressible string table.) Smaller buffer sizes give
+ // fast adaptation but have of course the overhead of transmitting
+ // trees more frequently.
+ // - I can't count above 4
+ internal int lit_bufsize;
+
+ internal int last_lit; // running index in l_buf
+
+ // Buffer for distances. To simplify the code, d_buf and l_buf have
+ // the same number of elements. To use different lengths, an extra flag
+ // array would be necessary.
+
+ internal int d_buf; // index of pendig_buf
+
+ internal int opt_len; // bit length of current block with optimal trees
+ internal int static_len; // bit length of current block with static trees
+ internal int matches; // number of string matches in current block
+ internal int last_eob_len; // bit length of EOB code for last block
+
+ // Output buffer. bits are inserted starting at the bottom (least
+ // significant bits).
+ internal uint bi_buf;
+
+ // Number of valid bits in bi_buf. All bits above the last valid bit
+ // are always zero.
+ internal int bi_valid;
+
+ internal Deflate(){
+ dyn_ltree=new short[HEAP_SIZE*2];
+ dyn_dtree=new short[(2*D_CODES+1)*2]; // distance tree
+ bl_tree=new short[(2*BL_CODES+1)*2]; // Huffman tree for bit lengths
+ }
+
+ internal void lm_init() {
+ window_size=2*w_size;
+
+ head[hash_size-1]=0;
+ for(int i=0; i= 3; max_blindex--) {
+ if (bl_tree[ZTree.bl_order[max_blindex]*2+1] != 0) break;
+ }
+ // Update opt_len to include the bit length tree and counts
+ opt_len += 3*(max_blindex+1) + 5+5+4;
+
+ return max_blindex;
+ }
+
+
+ // Send the header for a block using dynamic Huffman trees: the counts, the
+ // lengths of the bit length codes, the literal tree and the distance tree.
+ // IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
+ internal void send_all_trees(int lcodes, int dcodes, int blcodes){
+ int rank; // index in bl_order
+
+ send_bits(lcodes-257, 5); // not +255 as stated in appnote.txt
+ send_bits(dcodes-1, 5);
+ send_bits(blcodes-4, 4); // not -3 as stated in appnote.txt
+ for (rank = 0; rank < blcodes; rank++) {
+ send_bits(bl_tree[ZTree.bl_order[rank]*2+1], 3);
+ }
+ send_tree(dyn_ltree, lcodes-1); // literal tree
+ send_tree(dyn_dtree, dcodes-1); // distance tree
+ }
+
+ // Send a literal or distance tree in compressed form, using the codes in
+ // bl_tree.
+ internal void send_tree (short[] tree,// the tree to be sent
+ int max_code // and its largest code of non zero frequency
+ ){
+ int n; // iterates over all tree elements
+ int prevlen = -1; // last emitted length
+ int curlen; // length of current code
+ int nextlen = tree[0*2+1]; // length of next code
+ int count = 0; // repeat count of the current code
+ int max_count = 7; // max repeat count
+ int min_count = 4; // min repeat count
+
+ if (nextlen == 0){ max_count = 138; min_count = 3; }
+
+ for (n = 0; n <= max_code; n++) {
+ curlen = nextlen; nextlen = tree[(n+1)*2+1];
+ if(++count < max_count && curlen == nextlen) {
+ continue;
+ }
+ else if(count < min_count) {
+ do { send_code(curlen, bl_tree); } while (--count != 0);
+ }
+ else if(curlen != 0){
+ if(curlen != prevlen){
+ send_code(curlen, bl_tree); count--;
+ }
+ send_code(REP_3_6, bl_tree);
+ send_bits(count-3, 2);
+ }
+ else if(count <= 10){
+ send_code(REPZ_3_10, bl_tree);
+ send_bits(count-3, 3);
+ }
+ else{
+ send_code(REPZ_11_138, bl_tree);
+ send_bits(count-11, 7);
+ }
+ count = 0; prevlen = curlen;
+ if(nextlen == 0){
+ max_count = 138; min_count = 3;
+ }
+ else if(curlen == nextlen){
+ max_count = 6; min_count = 3;
+ }
+ else{
+ max_count = 7; min_count = 4;
+ }
+ }
+ }
+
+ // Output a byte on the stream.
+ // IN assertion: there is enough room in pending_buf.
+ internal void put_byte(byte[] p, int start, int len){
+ System.Array.Copy(p, start, pending_buf, pending, len);
+ pending+=len;
+ }
+
+ internal void put_byte(byte c){
+ pending_buf[pending++]=c;
+ }
+ internal void put_short(int w) {
+ pending_buf[pending++]=(byte)(w/*&0xff*/);
+ pending_buf[pending++]=(byte)(w>>8);
+ }
+ internal void putShortMSB(int b){
+ pending_buf[pending++]=(byte)(b>>8);
+ pending_buf[pending++]=(byte)(b/*&0xff*/);
+ }
+
+ internal void send_code(int c, short[] tree){
+ int c2=c*2;
+ send_bits((tree[c2]&0xffff), (tree[c2+1]&0xffff));
+ }
+
+ internal void send_bits(int val, int length){
+ if (bi_valid > Buf_size - length) {
+ bi_buf |= (uint)(val << bi_valid);
+ pending_buf[pending++]=(byte)(bi_buf/*&0xff*/);
+ pending_buf[pending++]=(byte)(bi_buf>>8);
+ bi_buf = ((uint)val) >> (Buf_size - bi_valid);
+ bi_valid += length - Buf_size;
+ } else {
+ bi_buf |= (uint)(val << bi_valid);
+ bi_valid += length;
+ }
+// int len = length;
+// if (bi_valid > (int)Buf_size - len) {
+// int val = value;
+// // bi_buf |= (val << bi_valid);
+// bi_buf = (short)((ushort)bi_buf | (ushort)((val << bi_valid)&0xffff));
+// put_short(bi_buf);
+// bi_buf = (short)(((uint)val) >> (Buf_size - bi_valid));
+// bi_valid += len - Buf_size;
+// } else {
+// // bi_buf |= (value) << bi_valid;
+// bi_buf = (short)((ushort)bi_buf | (ushort)(((value) << bi_valid)&0xffff));
+// bi_valid += len;
+// }
+ }
+
+ // Send one empty static block to give enough lookahead for inflate.
+ // This takes 10 bits, of which 7 may remain in the bit buffer.
+ // The current inflate code requires 9 bits of lookahead. If the
+ // last two codes for the previous block (real code plus EOB) were coded
+ // on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
+ // the last real code. In this case we send two empty static blocks instead
+ // of one. (There are no problems if the previous block is stored or fixed.)
+ // To simplify the code, we assume the worst case of last real code encoded
+ // on one bit only.
+ internal void _tr_align(){
+ send_bits(STATIC_TREES<<1, 3);
+ send_code(END_BLOCK, StaticTree.static_ltree);
+
+ bi_flush();
+
+ // Of the 10 bits for the empty block, we have already sent
+ // (10 - bi_valid) bits. The lookahead for the last real code (before
+ // the EOB of the previous block) was thus at least one plus the length
+ // of the EOB plus what we have just sent of the empty static block.
+ if (1 + last_eob_len + 10 - bi_valid < 9) {
+ send_bits(STATIC_TREES<<1, 3);
+ send_code(END_BLOCK, StaticTree.static_ltree);
+ bi_flush();
+ }
+ last_eob_len = 7;
+ }
+
+
+ // Save the match info and tally the frequency counts. Return true if
+ // the current block must be flushed.
+ internal bool _tr_tally (int dist, // distance of matched string
+ int lc // match length-MIN_MATCH or unmatched char (if dist==0)
+ ){
+
+ pending_buf[d_buf+last_lit*2] = (byte)(dist>>8);
+ pending_buf[d_buf+last_lit*2+1] = (byte)dist;
+
+ pending_buf[l_buf+last_lit] = (byte)lc; last_lit++;
+
+ if (dist == 0) {
+ // lc is the unmatched char
+ dyn_ltree[lc*2]++;
+ }
+ else {
+ matches++;
+ // Here, lc is the match length - MIN_MATCH
+ dist--; // dist = match distance - 1
+ dyn_ltree[(ZTree._length_code[lc]+LITERALS+1)*2]++;
+ dyn_dtree[ZTree.d_code(dist)*2]++;
+ }
+
+ if ((last_lit & 0x1fff) == 0 && level > 2) {
+ // Compute an upper bound for the compressed length
+ int out_length = last_lit*8;
+ int in_length = strstart - block_start;
+ int dcode;
+ for (dcode = 0; dcode < D_CODES; dcode++) {
+ out_length += (int)((int)dyn_dtree[dcode*2] *
+ (5L+ZTree.extra_dbits[dcode]));
+ }
+ out_length >>= 3;
+ if ((matches < (last_lit/2)) && out_length < in_length/2) return true;
+ }
+
+ return (last_lit == lit_bufsize-1);
+ // We avoid equality with lit_bufsize because of wraparound at 64K
+ // on 16 bit machines and because stored blocks are restricted to
+ // 64K-1 bytes.
+ }
+
+ // Send the block data compressed using the given Huffman trees
+ internal void compress_block(short[] ltree, short[] dtree){
+ int dist; // distance of matched string
+ int lc; // match length or unmatched char (if dist == 0)
+ int lx = 0; // running index in l_buf
+ int code; // the code to send
+ int extra; // number of extra bits to send
+
+ if (last_lit != 0){
+ do{
+ dist=((pending_buf[d_buf+lx*2]<<8)&0xff00)|
+ (pending_buf[d_buf+lx*2+1]&0xff);
+ lc=(pending_buf[l_buf+lx])&0xff; lx++;
+
+ if(dist == 0){
+ send_code(lc, ltree); // send a literal byte
+ }
+ else{
+ // Here, lc is the match length - MIN_MATCH
+ code = ZTree._length_code[lc];
+
+ send_code(code+LITERALS+1, ltree); // send the length code
+ extra = ZTree.extra_lbits[code];
+ if(extra != 0){
+ lc -= ZTree.base_length[code];
+ send_bits(lc, extra); // send the extra length bits
+ }
+ dist--; // dist is now the match distance - 1
+ code = ZTree.d_code(dist);
+
+ send_code(code, dtree); // send the distance code
+ extra = ZTree.extra_dbits[code];
+ if (extra != 0) {
+ dist -= ZTree.base_dist[code];
+ send_bits(dist, extra); // send the extra distance bits
+ }
+ } // literal or match pair ?
+
+ // Check that the overlay between pending_buf and d_buf+l_buf is ok:
+ }
+ while (lx < last_lit);
+ }
+
+ send_code(END_BLOCK, ltree);
+ last_eob_len = ltree[END_BLOCK*2+1];
+ }
+
+ // Set the data type to ASCII or BINARY, using a crude approximation:
+ // binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise.
+ // IN assertion: the fields freq of dyn_ltree are set and the total of all
+ // frequencies does not exceed 64K (to fit in an int on 16 bit machines).
+ internal void set_data_type(){
+ int n = 0;
+ int ascii_freq = 0;
+ int bin_freq = 0;
+ while(n<7){ bin_freq += dyn_ltree[n*2]; n++;}
+ while(n<128){ ascii_freq += dyn_ltree[n*2]; n++;}
+ while(n (ascii_freq >> 2) ? Z_BINARY : Z_ASCII);
+ }
+
+ // Flush the bit buffer, keeping at most 7 bits in it.
+ internal void bi_flush(){
+ if (bi_valid == 16) {
+ pending_buf[pending++]=(byte)(bi_buf/*&0xff*/);
+ pending_buf[pending++]=(byte)(bi_buf>>8);
+ bi_buf=0;
+ bi_valid=0;
+ }
+ else if (bi_valid >= 8) {
+ pending_buf[pending++]=(byte)(bi_buf);
+ bi_buf>>=8;
+ bi_buf &= 0x00ff;
+ bi_valid-=8;
+ }
+ }
+
+ // Flush the bit buffer and align the output on a byte boundary
+ internal void bi_windup(){
+ if (bi_valid > 8) {
+ pending_buf[pending++]=(byte)(bi_buf);
+ pending_buf[pending++]=(byte)(bi_buf>>8);
+ } else if (bi_valid > 0) {
+ pending_buf[pending++]=(byte)(bi_buf);
+ }
+ bi_buf = 0;
+ bi_valid = 0;
+ }
+
+ // Copy a stored block, storing first the length and its
+ // one's complement if requested.
+ internal void copy_block(int buf, // the input data
+ int len, // its length
+ bool header // true if block header must be written
+ ){
+ //int index=0;
+ bi_windup(); // align on byte boundary
+ last_eob_len = 8; // enough lookahead for inflate
+
+ if (header) {
+ put_short((short)len);
+ put_short((short)~len);
+ }
+
+ // while(len--!=0) {
+ // put_byte(window[buf+index]);
+ // index++;
+ // }
+ put_byte(window, buf, len);
+ }
+
+ internal void flush_block_only(bool eof){
+ _tr_flush_block(block_start>=0 ? block_start : -1,
+ strstart-block_start,
+ eof);
+ block_start=strstart;
+ strm.flush_pending();
+ }
+
+ // Copy without compression as much as possible from the input stream, return
+ // the current block state.
+ // This function does not insert new strings in the dictionary since
+ // uncompressible data is probably not useful. This function is used
+ // only for the level=0 compression option.
+ // NOTE: this function should be optimized to avoid extra copying from
+ // window to pending_buf.
+ internal int deflate_stored(int flush){
+ // Stored blocks are limited to 0xffff bytes, pending_buf is limited
+ // to pending_buf_size, and each stored block has a 5 byte header:
+
+ int max_block_size = 0xffff;
+ int max_start;
+
+ if(max_block_size > pending_buf_size - 5) {
+ max_block_size = pending_buf_size - 5;
+ }
+
+ // Copy as much as possible from input to output:
+ while(true){
+ // Fill the window as much as possible:
+ if(lookahead<=1){
+ fill_window();
+ if(lookahead==0 && flush==Z_NO_FLUSH) return NeedMore;
+ if(lookahead==0) break; // flush the current block
+ }
+
+ strstart+=lookahead;
+ lookahead=0;
+
+ // Emit a stored block if pending_buf will be full:
+ max_start=block_start+max_block_size;
+ if(strstart==0|| strstart>=max_start) {
+ // strstart == 0 is possible when wraparound on 16-bit machine
+ lookahead = (int)(strstart-max_start);
+ strstart = (int)max_start;
+
+ flush_block_only(false);
+ if(strm.avail_out==0) return NeedMore;
+
+ }
+
+ // Flush if we may have to slide, otherwise block_start may become
+ // negative and the data will be gone:
+ if(strstart-block_start >= w_size-MIN_LOOKAHEAD) {
+ flush_block_only(false);
+ if(strm.avail_out==0) return NeedMore;
+ }
+ }
+
+ flush_block_only(flush == Z_FINISH);
+ if(strm.avail_out==0)
+ return (flush == Z_FINISH) ? FinishStarted : NeedMore;
+
+ return flush == Z_FINISH ? FinishDone : BlockDone;
+ }
+
+ // Send a stored block
+ internal void _tr_stored_block(int buf, // input block
+ int stored_len, // length of input block
+ bool eof // true if this is the last block for a file
+ ){
+ send_bits((STORED_BLOCK<<1)+(eof?1:0), 3); // send block type
+ copy_block(buf, stored_len, true); // with header
+ }
+
+ // Determine the best encoding for the current block: dynamic trees, static
+ // trees or store, and output the encoded block to the zip file.
+ internal void _tr_flush_block(int buf, // input block, or NULL if too old
+ int stored_len, // length of input block
+ bool eof // true if this is the last block for a file
+ ) {
+ int opt_lenb, static_lenb;// opt_len and static_len in bytes
+ int max_blindex = 0; // index of last bit length code of non zero freq
+
+ // Build the Huffman trees unless a stored block is forced
+ if(level > 0) {
+ // Check if the file is ascii or binary
+ if(data_type == Z_UNKNOWN) set_data_type();
+
+ // Construct the literal and distance trees
+ l_desc.build_tree(this);
+
+ d_desc.build_tree(this);
+
+ // At this point, opt_len and static_len are the total bit lengths of
+ // the compressed block data, excluding the tree representations.
+
+ // Build the bit length tree for the above two trees, and get the index
+ // in bl_order of the last bit length code to send.
+ max_blindex=build_bl_tree();
+
+ // Determine the best encoding. Compute first the block length in bytes
+ opt_lenb=(opt_len+3+7)>>3;
+ static_lenb=(static_len+3+7)>>3;
+
+ if(static_lenb<=opt_lenb) opt_lenb=static_lenb;
+ }
+ else {
+ opt_lenb=static_lenb=stored_len+5; // force a stored block
+ }
+
+ if(stored_len+4<=opt_lenb && buf != -1){
+ // 4: two words for the lengths
+ // The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
+ // Otherwise we can't have processed more than WSIZE input bytes since
+ // the last block flush, because compression would have been
+ // successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
+ // transform a block into a stored block.
+ _tr_stored_block(buf, stored_len, eof);
+ }
+ else if(static_lenb == opt_lenb){
+ send_bits((STATIC_TREES<<1)+(eof?1:0), 3);
+ compress_block(StaticTree.static_ltree, StaticTree.static_dtree);
+ }
+ else{
+ send_bits((DYN_TREES<<1)+(eof?1:0), 3);
+ send_all_trees(l_desc.max_code+1, d_desc.max_code+1, max_blindex+1);
+ compress_block(dyn_ltree, dyn_dtree);
+ }
+
+ // The above check is made mod 2^32, for files larger than 512 MB
+ // and uLong implemented on 32 bits.
+
+ init_block();
+
+ if(eof){
+ bi_windup();
+ }
+ }
+
+ // Fill the window when the lookahead becomes insufficient.
+ // Updates strstart and lookahead.
+ //
+ // IN assertion: lookahead < MIN_LOOKAHEAD
+ // OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
+ // At least one byte has been read, or avail_in == 0; reads are
+ // performed for at least two bytes (required for the zip translate_eol
+ // option -- not supported here).
+ internal void fill_window(){
+ int n, m;
+ int p;
+ int more; // Amount of free space at the end of the window.
+
+ do{
+ more = (window_size-lookahead-strstart);
+
+ // Deal with !@#$% 64K limit:
+ if(more==0 && strstart==0 && lookahead==0){
+ more = w_size;
+ }
+ else if(more==-1) {
+ // Very unlikely, but possible on 16 bit machine if strstart == 0
+ // and lookahead == 1 (input done one byte at time)
+ more--;
+
+ // If the window is almost full and there is insufficient lookahead,
+ // move the upper half to the lower one to make room in the upper half.
+ }
+ else if(strstart >= w_size+ w_size-MIN_LOOKAHEAD) {
+ System.Array.Copy(window, w_size, window, 0, w_size);
+ match_start-=w_size;
+ strstart-=w_size; // we now have strstart >= MAX_DIST
+ block_start-=w_size;
+
+ // Slide the hash table (could be avoided with 32 bit values
+ // at the expense of memory usage). We slide even when level == 0
+ // to keep the hash table consistent if we switch back to level > 0
+ // later. (Using level 0 permanently is not an optimal usage of
+ // zlib, so we don't care about this pathological case.)
+
+ n = hash_size;
+ p=n;
+ do {
+ m = (head[--p]&0xffff);
+ head[p]=(short)(m>=w_size ? (m-w_size) : 0);
+ }
+ while (--n != 0);
+
+ n = w_size;
+ p = n;
+ do {
+ m = (prev[--p]&0xffff);
+ prev[p] = (short)(m >= w_size ? (m-w_size) : 0);
+ // If n is not on any hash chain, prev[n] is garbage but
+ // its value will never be used.
+ }
+ while (--n!=0);
+ more += w_size;
+ }
+
+ if (strm.avail_in == 0) return;
+
+ // If there was no sliding:
+ // strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
+ // more == window_size - lookahead - strstart
+ // => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
+ // => more >= window_size - 2*WSIZE + 2
+ // In the BIG_MEM or MMAP case (not yet supported),
+ // window_size == input_size + MIN_LOOKAHEAD &&
+ // strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
+ // Otherwise, window_size == 2*WSIZE so more >= 2.
+ // If there was sliding, more >= WSIZE. So in all cases, more >= 2.
+
+ n = strm.read_buf(window, strstart + lookahead, more);
+ lookahead += n;
+
+ // Initialize the hash value now that we have some input:
+ if(lookahead >= MIN_MATCH) {
+ ins_h = window[strstart]&0xff;
+ ins_h=(((ins_h)<= MIN_MATCH){
+ ins_h=(((ins_h)<=MIN_MATCH){
+ // check_match(strstart, match_start, match_length);
+
+ bflush=_tr_tally(strstart-match_start, match_length-MIN_MATCH);
+
+ lookahead -= match_length;
+
+ // Insert new strings in the hash table only if the match length
+ // is not too large. This saves time but degrades compression.
+ if(match_length <= max_lazy_match &&
+ lookahead >= MIN_MATCH) {
+ match_length--; // string at strstart already in hash table
+ do{
+ strstart++;
+
+ ins_h=((ins_h<= MIN_MATCH) {
+ ins_h=(((ins_h)< 4096))) {
+
+ // If prev_match is also MIN_MATCH, match_start is garbage
+ // but we will ignore the current match anyway.
+ match_length = MIN_MATCH-1;
+ }
+ }
+
+ // If there was a match at the previous step and the current
+ // match is not better, output the previous match:
+ if(prev_length >= MIN_MATCH && match_length <= prev_length) {
+ int max_insert = strstart + lookahead - MIN_MATCH;
+ // Do not insert strings in hash table beyond this.
+
+ // check_match(strstart-1, prev_match, prev_length);
+
+ bflush=_tr_tally(strstart-1-prev_match, prev_length - MIN_MATCH);
+
+ // Insert in hash table all strings up to the end of the match.
+ // strstart-1 and strstart are already inserted. If there is not
+ // enough lookahead, the last two strings are not inserted in
+ // the hash table.
+ lookahead -= prev_length-1;
+ prev_length -= 2;
+ do{
+ if(++strstart <= max_insert) {
+ ins_h=(((ins_h)<(w_size-MIN_LOOKAHEAD) ?
+ strstart-(w_size-MIN_LOOKAHEAD) : 0;
+ int nice_match=this.nice_match;
+
+ // Stop when cur_match becomes <= limit. To simplify the code,
+ // we prevent matches with the string of window index 0.
+
+ int wmask = w_mask;
+
+ int strend = strstart + MAX_MATCH;
+ byte scan_end1 = window[scan+best_len-1];
+ byte scan_end = window[scan+best_len];
+
+ // The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
+ // It is easy to get rid of this optimization if necessary.
+
+ // Do not waste too much time if we already have a good match:
+ if (prev_length >= good_match) {
+ chain_length >>= 2;
+ }
+
+ // Do not look for matches beyond the end of the input. This is necessary
+ // to make deflate deterministic.
+ if (nice_match > lookahead) nice_match = lookahead;
+
+ do {
+ match = cur_match;
+
+ // Skip to next match if the match length cannot increase
+ // or if the match length is less than 2:
+ if (window[match+best_len] != scan_end ||
+ window[match+best_len-1] != scan_end1 ||
+ window[match] != window[scan] ||
+ window[++match] != window[scan+1]) continue;
+
+ // The check at best_len-1 can be removed because it will be made
+ // again later. (This heuristic is not always a win.)
+ // It is not necessary to compare scan[2] and match[2] since they
+ // are always equal when the other bytes match, given that
+ // the hash keys are equal and that HASH_BITS >= 8.
+ scan += 2; match++;
+
+ // We check for insufficient lookahead only every 8th comparison;
+ // the 256th check will be made at strstart+258.
+ do {
+ } while (window[++scan] == window[++match] &&
+ window[++scan] == window[++match] &&
+ window[++scan] == window[++match] &&
+ window[++scan] == window[++match] &&
+ window[++scan] == window[++match] &&
+ window[++scan] == window[++match] &&
+ window[++scan] == window[++match] &&
+ window[++scan] == window[++match] &&
+ scan < strend);
+
+ len = MAX_MATCH - (int)(strend - scan);
+ scan = strend - MAX_MATCH;
+
+ if(len>best_len) {
+ match_start = cur_match;
+ best_len = len;
+ if (len >= nice_match) break;
+ scan_end1 = window[scan+best_len-1];
+ scan_end = window[scan+best_len];
+ }
+
+ } while ((cur_match = (prev[cur_match & wmask]&0xffff)) > limit
+ && --chain_length != 0);
+
+ if (best_len <= lookahead) return best_len;
+ return lookahead;
+ }
+
+ internal int deflateInit(ZStream strm, int level, int bits){
+ return deflateInit2(strm, level, Z_DEFLATED, bits, DEF_MEM_LEVEL,
+ Z_DEFAULT_STRATEGY);
+ }
+ internal int deflateInit(ZStream strm, int level){
+ return deflateInit(strm, level, MAX_WBITS);
+ }
+ internal int deflateInit2(ZStream strm, int level, int method, int windowBits,
+ int memLevel, int strategy){
+ int noheader = 0;
+ // byte[] my_version=ZLIB_VERSION;
+
+ //
+ // if (version == null || version[0] != my_version[0]
+ // || stream_size != sizeof(z_stream)) {
+ // return Z_VERSION_ERROR;
+ // }
+
+ strm.msg = null;
+
+ if (level == Z_DEFAULT_COMPRESSION) level = 6;
+
+ if (windowBits < 0) { // undocumented feature: suppress zlib header
+ noheader = 1;
+ windowBits = -windowBits;
+ }
+
+ if (memLevel < 1 || memLevel > MAX_MEM_LEVEL ||
+ method != Z_DEFLATED ||
+ windowBits < 9 || windowBits > 15 || level < 0 || level > 9 ||
+ strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
+ return Z_STREAM_ERROR;
+ }
+
+ strm.dstate = (Deflate)this;
+
+ this.noheader = noheader;
+ w_bits = windowBits;
+ w_size = 1 << w_bits;
+ w_mask = w_size - 1;
+
+ hash_bits = memLevel + 7;
+ hash_size = 1 << hash_bits;
+ hash_mask = hash_size - 1;
+ hash_shift = ((hash_bits+MIN_MATCH-1)/MIN_MATCH);
+
+ window = new byte[w_size*2];
+ prev = new short[w_size];
+ head = new short[hash_size];
+
+ lit_bufsize = 1 << (memLevel + 6); // 16K elements by default
+
+ // We overlay pending_buf and d_buf+l_buf. This works since the average
+ // output size for (length,distance) codes is <= 24 bits.
+ pending_buf = new byte[lit_bufsize*4];
+ pending_buf_size = lit_bufsize*4;
+
+ d_buf = lit_bufsize/2;
+ l_buf = (1+2)*lit_bufsize;
+
+ this.level = level;
+
+ //System.out.println("level="+level);
+
+ this.strategy = strategy;
+ this.method = (byte)method;
+
+ return deflateReset(strm);
+ }
+
+ internal int deflateReset(ZStream strm){
+ strm.total_in = strm.total_out = 0;
+ strm.msg = null; //
+ strm.data_type = Z_UNKNOWN;
+
+ pending = 0;
+ pending_out = 0;
+
+ if(noheader < 0) {
+ noheader = 0; // was set to -1 by deflate(..., Z_FINISH);
+ }
+ status = (noheader!=0) ? BUSY_STATE : INIT_STATE;
+ strm.adler=strm._adler.adler32(0, null, 0, 0);
+
+ last_flush = Z_NO_FLUSH;
+
+ tr_init();
+ lm_init();
+ return Z_OK;
+ }
+
+ internal int deflateEnd(){
+ if(status!=INIT_STATE && status!=BUSY_STATE && status!=FINISH_STATE){
+ return Z_STREAM_ERROR;
+ }
+ // Deallocate in reverse order of allocations:
+ pending_buf=null;
+ head=null;
+ prev=null;
+ window=null;
+ // free
+ // dstate=null;
+ return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
+ }
+
+ internal int deflateParams(ZStream strm, int _level, int _strategy){
+ int err=Z_OK;
+
+ if(_level == Z_DEFAULT_COMPRESSION){
+ _level = 6;
+ }
+ if(_level < 0 || _level > 9 ||
+ _strategy < 0 || _strategy > Z_HUFFMAN_ONLY) {
+ return Z_STREAM_ERROR;
+ }
+
+ if(config_table[level].func!=config_table[_level].func &&
+ strm.total_in != 0) {
+ // Flush the last buffer:
+ err = strm.deflate(Z_PARTIAL_FLUSH);
+ }
+
+ if(level != _level) {
+ level = _level;
+ max_lazy_match = config_table[level].max_lazy;
+ good_match = config_table[level].good_length;
+ nice_match = config_table[level].nice_length;
+ max_chain_length = config_table[level].max_chain;
+ }
+ strategy = _strategy;
+ return err;
+ }
+
+ internal int deflateSetDictionary (ZStream strm, byte[] dictionary, int dictLength){
+ int length = dictLength;
+ int index=0;
+
+ if(dictionary == null || status != INIT_STATE)
+ return Z_STREAM_ERROR;
+
+ strm.adler=strm._adler.adler32(strm.adler, dictionary, 0, dictLength);
+
+ if(length < MIN_MATCH) return Z_OK;
+ if(length > w_size-MIN_LOOKAHEAD){
+ length = w_size-MIN_LOOKAHEAD;
+ index=dictLength-length; // use the tail of the dictionary
+ }
+ System.Array.Copy(dictionary, index, window, 0, length);
+ strstart = length;
+ block_start = length;
+
+ // Insert all strings in the hash table (except for the last two bytes).
+ // s->lookahead stays null, so s->ins_h will be recomputed at the next
+ // call of fill_window.
+
+ ins_h = window[0]&0xff;
+ ins_h=(((ins_h)<Z_FINISH || flush<0){
+ return Z_STREAM_ERROR;
+ }
+
+ if(strm.next_out == null ||
+ (strm.next_in == null && strm.avail_in != 0) ||
+ (status == FINISH_STATE && flush != Z_FINISH)) {
+ strm.msg=z_errmsg[Z_NEED_DICT-(Z_STREAM_ERROR)];
+ return Z_STREAM_ERROR;
+ }
+ if(strm.avail_out == 0){
+ strm.msg=z_errmsg[Z_NEED_DICT-(Z_BUF_ERROR)];
+ return Z_BUF_ERROR;
+ }
+
+ this.strm = strm; // just in case
+ old_flush = last_flush;
+ last_flush = flush;
+
+ // Write the zlib header
+ if(status == INIT_STATE) {
+ int header = (Z_DEFLATED+((w_bits-8)<<4))<<8;
+ int level_flags=((level-1)&0xff)>>1;
+
+ if(level_flags>3) level_flags=3;
+ header |= (level_flags<<6);
+ if(strstart!=0) header |= PRESET_DICT;
+ header+=31-(header % 31);
+
+ status=BUSY_STATE;
+ putShortMSB(header);
+
+
+ // Save the adler32 of the preset dictionary:
+ if(strstart!=0){
+ putShortMSB((int)(strm.adler>>16));
+ putShortMSB((int)(strm.adler&0xffff));
+ }
+ strm.adler=strm._adler.adler32(0, null, 0, 0);
+ }
+
+ // Flush as much pending output as possible
+ if(pending != 0) {
+ strm.flush_pending();
+ if(strm.avail_out == 0) {
+ //System.out.println(" avail_out==0");
+ // Since avail_out is 0, deflate will be called again with
+ // more output space, but possibly with both pending and
+ // avail_in equal to zero. There won't be anything to do,
+ // but this is not an error situation so make sure we
+ // return OK instead of BUF_ERROR at next call of deflate:
+ last_flush = -1;
+ return Z_OK;
+ }
+
+ // Make sure there is something to do and avoid duplicate consecutive
+ // flushes. For repeated and useless calls with Z_FINISH, we keep
+ // returning Z_STREAM_END instead of Z_BUFF_ERROR.
+ }
+ else if(strm.avail_in==0 && flush <= old_flush &&
+ flush != Z_FINISH) {
+ strm.msg=z_errmsg[Z_NEED_DICT-(Z_BUF_ERROR)];
+ return Z_BUF_ERROR;
+ }
+
+ // User must not provide more input after the first FINISH:
+ if(status == FINISH_STATE && strm.avail_in != 0) {
+ strm.msg=z_errmsg[Z_NEED_DICT-(Z_BUF_ERROR)];
+ return Z_BUF_ERROR;
+ }
+
+ // Start a new block or continue the current one.
+ if(strm.avail_in!=0 || lookahead!=0 ||
+ (flush != Z_NO_FLUSH && status != FINISH_STATE)) {
+ int bstate=-1;
+ switch(config_table[level].func){
+ case STORED:
+ bstate = deflate_stored(flush);
+ break;
+ case FAST:
+ bstate = deflate_fast(flush);
+ break;
+ case SLOW:
+ bstate = deflate_slow(flush);
+ break;
+ default:
+ break;
+ }
+
+ if (bstate==FinishStarted || bstate==FinishDone) {
+ status = FINISH_STATE;
+ }
+ if (bstate==NeedMore || bstate==FinishStarted) {
+ if(strm.avail_out == 0) {
+ last_flush = -1; // avoid BUF_ERROR next call, see above
+ }
+ return Z_OK;
+ // If flush != Z_NO_FLUSH && avail_out == 0, the next call
+ // of deflate should use the same flush parameter to make sure
+ // that the flush is complete. So we don't have to output an
+ // empty block here, this will be done at next call. This also
+ // ensures that for a very small output buffer, we emit at most
+ // one empty block.
+ }
+
+ if (bstate==BlockDone) {
+ if(flush == Z_PARTIAL_FLUSH) {
+ _tr_align();
+ }
+ else { // FULL_FLUSH or SYNC_FLUSH
+ _tr_stored_block(0, 0, false);
+ // For a full flush, this empty block will be recognized
+ // as a special marker by inflate_sync().
+ if(flush == Z_FULL_FLUSH) {
+ //state.head[s.hash_size-1]=0;
+ for(int i=0; i>16));
+ putShortMSB((int)(strm.adler&0xffff));
+ strm.flush_pending();
+
+ // If avail_out is zero, the application will call deflate again
+ // to flush the rest.
+ noheader = -1; // write the trailer only once!
+ return pending != 0 ? Z_OK : Z_STREAM_END;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/Deflate.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/Deflate.cs.meta
new file mode 100644
index 00000000..57f333d0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/Deflate.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: d29c091390e4c924b9c9cd53bc19b4e9
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/InfBlocks.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/InfBlocks.cs
new file mode 100644
index 00000000..e8de2035
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/InfBlocks.cs
@@ -0,0 +1,622 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+/*
+ * $Id: InfBlocks.cs,v 1.2 2008-05-10 09:35:40 bouncy Exp $
+ *
+Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the distribution.
+
+ 3. The names of the authors may not be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
+INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
+INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/*
+ * This program is based on zlib-1.1.3, so all credit should go authors
+ * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
+ * and contributors of zlib.
+ */
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Zlib {
+
+ internal sealed class InfBlocks{
+ private const int MANY=1440;
+
+ // And'ing with mask[n] masks the lower n bits
+ private static readonly int[] inflate_mask = {
+ 0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000f,
+ 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 0x000001ff,
+ 0x000003ff, 0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff,
+ 0x00007fff, 0x0000ffff
+ };
+
+ // Table for deflate from PKZIP's appnote.txt.
+ static readonly int[] border = { // Order of the bit length code lengths
+ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
+ };
+
+ private const int Z_OK=0;
+ private const int Z_STREAM_END=1;
+ private const int Z_NEED_DICT=2;
+ private const int Z_ERRNO=-1;
+ private const int Z_STREAM_ERROR=-2;
+ private const int Z_DATA_ERROR=-3;
+ private const int Z_MEM_ERROR=-4;
+ private const int Z_BUF_ERROR=-5;
+ private const int Z_VERSION_ERROR=-6;
+
+ private const int TYPE=0; // get type bits (3, including end bit)
+ private const int LENS=1; // get lengths for stored
+ private const int STORED=2;// processing stored block
+ private const int TABLE=3; // get table lengths
+ private const int BTREE=4; // get bit lengths tree for a dynamic block
+ private const int DTREE=5; // get length, distance trees for a dynamic block
+ private const int CODES=6; // processing fixed or dynamic block
+ private const int DRY=7; // output remaining window bytes
+ private const int DONE=8; // finished last block, done
+ private const int BAD=9; // ot a data error--stuck here
+
+ internal int mode; // current inflate_block mode
+
+ internal int left; // if STORED, bytes left to copy
+
+ internal int table; // table lengths (14 bits)
+ internal int index; // index into blens (or border)
+ internal int[] blens; // bit lengths of codes
+ internal int[] bb=new int[1]; // bit length tree depth
+ internal int[] tb=new int[1]; // bit length decoding tree
+
+ internal InfCodes codes=new InfCodes(); // if CODES, current state
+
+ int last; // true if this block is the last block
+
+ // mode independent information
+ internal int bitk; // bits in bit buffer
+ internal int bitb; // bit buffer
+ internal int[] hufts; // single malloc for tree space
+ internal byte[] window; // sliding window
+ internal int end; // one byte after sliding window
+ internal int read; // window read pointer
+ internal int write; // window write pointer
+ internal Object checkfn; // check function
+ internal long check; // check on output
+
+ internal InfTree inftree=new InfTree();
+
+ internal InfBlocks(ZStream z, Object checkfn, int w){
+ hufts=new int[MANY*3];
+ window=new byte[w];
+ end=w;
+ this.checkfn = checkfn;
+ mode = TYPE;
+ reset(z, null);
+ }
+
+ internal void reset(ZStream z, long[] c){
+ if(c!=null) c[0]=check;
+ if(mode==BTREE || mode==DTREE){
+ }
+ if(mode==CODES){
+ codes.free(z);
+ }
+ mode=TYPE;
+ bitk=0;
+ bitb=0;
+ read=write=0;
+
+ if(checkfn != null)
+ z.adler=check=z._adler.adler32(0L, null, 0, 0);
+ }
+
+ internal int proc(ZStream z, int r){
+ int t; // temporary storage
+ int b; // bit buffer
+ int k; // bits in bit buffer
+ int p; // input data pointer
+ int n; // bytes available there
+ int q; // output window write pointer
+ int m; { // bytes to end of window or read pointer
+
+ // copy input/output information to locals (UPDATE macro restores)
+ p=z.next_in_index;n=z.avail_in;b=bitb;k=bitk;} {
+ q=write;m=(int)(q> 1){
+ case 0: { // stored
+ b>>=(3);k-=(3);}
+ t = k & 7; { // go to byte boundary
+
+ b>>=(t);k-=(t);}
+ mode = LENS; // get length of stored block
+ break;
+ case 1: { // fixed
+ int[] bl=new int[1];
+ int[] bd=new int[1];
+ int[][] tl=new int[1][];
+ int[][] td=new int[1][];
+
+ InfTree.inflate_trees_fixed(bl, bd, tl, td, z);
+ codes.init(bl[0], bd[0], tl[0], 0, td[0], 0, z);
+ } {
+
+ b>>=(3);k-=(3);}
+
+ mode = CODES;
+ break;
+ case 2: { // dynamic
+
+ b>>=(3);k-=(3);}
+
+ mode = TABLE;
+ break;
+ case 3: { // illegal
+
+ b>>=(3);k-=(3);}
+ mode = BAD;
+ z.msg = "invalid block type";
+ r = Z_DATA_ERROR;
+
+ bitb=b; bitk=k;
+ z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
+ write=q;
+ return inflate_flush(z,r);
+ }
+ break;
+ case LENS:
+
+ while(k<(32)){
+ if(n!=0){
+ r=Z_OK;
+ }
+ else{
+ bitb=b; bitk=k;
+ z.avail_in=n;
+ z.total_in+=p-z.next_in_index;z.next_in_index=p;
+ write=q;
+ return inflate_flush(z,r);
+ };
+ n--;
+ b|=(z.next_in[p++]&0xff)<> 16) & 0xffff) != (b & 0xffff)){
+ mode = BAD;
+ z.msg = "invalid stored block lengths";
+ r = Z_DATA_ERROR;
+
+ bitb=b; bitk=k;
+ z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
+ write=q;
+ return inflate_flush(z,r);
+ }
+ left = (b & 0xffff);
+ b = k = 0; // dump bits
+ mode = left!=0 ? STORED : (last!=0 ? DRY : TYPE);
+ break;
+ case STORED:
+ if (n == 0){
+ bitb=b; bitk=k;
+ z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
+ write=q;
+ return inflate_flush(z,r);
+ }
+
+ if(m==0){
+ if(q==end&&read!=0){
+ q=0; m=(int)(qn) t = n;
+ if(t>m) t = m;
+ System.Array.Copy(z.next_in, p, window, q, t);
+ p += t; n -= t;
+ q += t; m -= t;
+ if ((left -= t) != 0)
+ break;
+ mode = last!=0 ? DRY : TYPE;
+ break;
+ case TABLE:
+
+ while(k<(14)){
+ if(n!=0){
+ r=Z_OK;
+ }
+ else{
+ bitb=b; bitk=k;
+ z.avail_in=n;
+ z.total_in+=p-z.next_in_index;z.next_in_index=p;
+ write=q;
+ return inflate_flush(z,r);
+ };
+ n--;
+ b|=(z.next_in[p++]&0xff)< 29 || ((t >> 5) & 0x1f) > 29) {
+ mode = BAD;
+ z.msg = "too many length or distance symbols";
+ r = Z_DATA_ERROR;
+
+ bitb=b; bitk=k;
+ z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
+ write=q;
+ return inflate_flush(z,r);
+ }
+ t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f);
+ if(blens==null || blens.Length>=(14);k-=(14);}
+
+ index = 0;
+ mode = BTREE;
+ goto case BTREE;
+ case BTREE:
+ while (index < 4 + (table >> 10)){
+ while(k<(3)){
+ if(n!=0){
+ r=Z_OK;
+ }
+ else{
+ bitb=b; bitk=k;
+ z.avail_in=n;
+ z.total_in+=p-z.next_in_index;z.next_in_index=p;
+ write=q;
+ return inflate_flush(z,r);
+ };
+ n--;
+ b|=(z.next_in[p++]&0xff)<>=(3);k-=(3);}
+ }
+
+ while(index < 19){
+ blens[border[index++]] = 0;
+ }
+
+ bb[0] = 7;
+ t = inftree.inflate_trees_bits(blens, bb, tb, hufts, z);
+ if (t != Z_OK){
+ r = t;
+ if (r == Z_DATA_ERROR){
+ blens=null;
+ mode = BAD;
+ }
+
+ bitb=b; bitk=k;
+ z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
+ write=q;
+ return inflate_flush(z,r);
+ }
+
+ index = 0;
+ mode = DTREE;
+ goto case DTREE;
+ case DTREE:
+ while (true){
+ t = table;
+ if(!(index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f))){
+ break;
+ }
+
+ int i, j, c;
+
+ t = bb[0];
+
+ while(k<(t)){
+ if(n!=0){
+ r=Z_OK;
+ }
+ else{
+ bitb=b; bitk=k;
+ z.avail_in=n;
+ z.total_in+=p-z.next_in_index;z.next_in_index=p;
+ write=q;
+ return inflate_flush(z,r);
+ };
+ n--;
+ b|=(z.next_in[p++]&0xff)<>=(t);k-=(t);
+ blens[index++] = c;
+ }
+ else { // c == 16..18
+ i = c == 18 ? 7 : c - 14;
+ j = c == 18 ? 11 : 3;
+
+ while(k<(t+i)){
+ if(n!=0){
+ r=Z_OK;
+ }
+ else{
+ bitb=b; bitk=k;
+ z.avail_in=n;
+ z.total_in+=p-z.next_in_index;z.next_in_index=p;
+ write=q;
+ return inflate_flush(z,r);
+ };
+ n--;
+ b|=(z.next_in[p++]&0xff)<>=(t);k-=(t);
+
+ j += (b & inflate_mask[i]);
+
+ b>>=(i);k-=(i);
+
+ i = index;
+ t = table;
+ if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) ||
+ (c == 16 && i < 1)){
+ blens=null;
+ mode = BAD;
+ z.msg = "invalid bit length repeat";
+ r = Z_DATA_ERROR;
+
+ bitb=b; bitk=k;
+ z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
+ write=q;
+ return inflate_flush(z,r);
+ }
+
+ c = c == 16 ? blens[i-1] : 0;
+ do{
+ blens[i++] = c;
+ }
+ while (--j!=0);
+ index = i;
+ }
+ }
+
+ tb[0]=-1; {
+ int[] bl=new int[1];
+ int[] bd=new int[1];
+ int[] tl=new int[1];
+ int[] td=new int[1];
+ bl[0] = 9; // must be <= 9 for lookahead assumptions
+ bd[0] = 6; // must be <= 9 for lookahead assumptions
+
+ t = table;
+ t = inftree.inflate_trees_dynamic(257 + (t & 0x1f),
+ 1 + ((t >> 5) & 0x1f),
+ blens, bl, bd, tl, td, hufts, z);
+
+ if (t != Z_OK){
+ if (t == Z_DATA_ERROR){
+ blens=null;
+ mode = BAD;
+ }
+ r = t;
+
+ bitb=b; bitk=k;
+ z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
+ write=q;
+ return inflate_flush(z,r);
+ }
+ codes.init(bl[0], bd[0], hufts, tl[0], hufts, td[0], z);
+ }
+ mode = CODES;
+ goto case CODES;
+ case CODES:
+ bitb=b; bitk=k;
+ z.avail_in=n; z.total_in+=p-z.next_in_index;z.next_in_index=p;
+ write=q;
+
+ if ((r = codes.proc(this, z, r)) != Z_STREAM_END){
+ return inflate_flush(z, r);
+ }
+ r = Z_OK;
+ codes.free(z);
+
+ p=z.next_in_index; n=z.avail_in;b=bitb;k=bitk;
+ q=write;m=(int)(q z.avail_out) n = z.avail_out;
+ if (n!=0 && r == Z_BUF_ERROR) r = Z_OK;
+
+ // update counters
+ z.avail_out -= n;
+ z.total_out += n;
+
+ // update check information
+ if(checkfn != null)
+ z.adler=check=z._adler.adler32(check, window, q, n);
+
+ // copy as far as end of window
+ System.Array.Copy(window, q, z.next_out, p, n);
+ p += n;
+ q += n;
+
+ // see if more to copy at beginning of window
+ if (q == end){
+ // wrap pointers
+ q = 0;
+ if (write == end)
+ write = 0;
+
+ // compute bytes to copy
+ n = write - q;
+ if (n > z.avail_out) n = z.avail_out;
+ if (n!=0 && r == Z_BUF_ERROR) r = Z_OK;
+
+ // update counters
+ z.avail_out -= n;
+ z.total_out += n;
+
+ // update check information
+ if(checkfn != null)
+ z.adler=check=z._adler.adler32(check, window, q, n);
+
+ // copy
+ System.Array.Copy(window, q, z.next_out, p, n);
+ p += n;
+ q += n;
+ }
+
+ // update pointers
+ z.next_out_index = p;
+ read = q;
+
+ // done
+ return r;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/InfBlocks.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/InfBlocks.cs.meta
new file mode 100644
index 00000000..06e5644c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/InfBlocks.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 39991dab49f0a85419083ecf2f53dc90
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/InfCodes.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/InfCodes.cs
new file mode 100644
index 00000000..2cedae17
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/InfCodes.cs
@@ -0,0 +1,615 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+/*
+ * $Id: InfCodes.cs,v 1.2 2008-05-10 09:35:40 bouncy Exp $
+ *
+Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the distribution.
+
+ 3. The names of the authors may not be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
+INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
+INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/*
+ * This program is based on zlib-1.1.3, so all credit should go authors
+ * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
+ * and contributors of zlib.
+ */
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Zlib {
+
+ internal sealed class InfCodes{
+
+ private static readonly int[] inflate_mask = {
+ 0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000f,
+ 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 0x000001ff,
+ 0x000003ff, 0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff,
+ 0x00007fff, 0x0000ffff
+ };
+
+ private const int Z_OK=0;
+ private const int Z_STREAM_END=1;
+ private const int Z_NEED_DICT=2;
+ private const int Z_ERRNO=-1;
+ private const int Z_STREAM_ERROR=-2;
+ private const int Z_DATA_ERROR=-3;
+ private const int Z_MEM_ERROR=-4;
+ private const int Z_BUF_ERROR=-5;
+ private const int Z_VERSION_ERROR=-6;
+
+ // waiting for "i:"=input,
+ // "o:"=output,
+ // "x:"=nothing
+ private const int START=0; // x: set up for LEN
+ private const int LEN=1; // i: get length/literal/eob next
+ private const int LENEXT=2; // i: getting length extra (have base)
+ private const int DIST=3; // i: get distance next
+ private const int DISTEXT=4;// i: getting distance extra
+ private const int COPY=5; // o: copying bytes in window, waiting for space
+ private const int LIT=6; // o: got literal, waiting for output space
+ private const int WASH=7; // o: got eob, possibly still output waiting
+ private const int END=8; // x: got eob and all data flushed
+ private const int BADCODE=9;// x: got error
+
+ int mode; // current inflate_codes mode
+
+ // mode dependent information
+ int len;
+
+ int[] tree; // pointer into tree
+ int tree_index=0;
+ int need; // bits needed
+
+ int lit;
+
+ // if EXT or COPY, where and how much
+ int get; // bits to get for extra
+ int dist; // distance back to copy from
+
+ byte lbits; // ltree bits decoded per branch
+ byte dbits; // dtree bits decoder per branch
+ int[] ltree; // literal/length/eob tree
+ int ltree_index; // literal/length/eob tree
+ int[] dtree; // distance tree
+ int dtree_index; // distance tree
+
+ internal InfCodes(){
+ }
+ internal void init(int bl, int bd,
+ int[] tl, int tl_index,
+ int[] td, int td_index, ZStream z){
+ mode=START;
+ lbits=(byte)bl;
+ dbits=(byte)bd;
+ ltree=tl;
+ ltree_index=tl_index;
+ dtree = td;
+ dtree_index=td_index;
+ tree=null;
+ }
+
+ internal int proc(InfBlocks s, ZStream z, int r){
+ int j; // temporary storage
+ int tindex; // temporary pointer
+ int e; // extra bits or operation
+ int b=0; // bit buffer
+ int k=0; // bits in bit buffer
+ int p=0; // input data pointer
+ int n; // bytes available there
+ int q; // output window write pointer
+ int m; // bytes to end of window or read pointer
+ int f; // pointer to copy strings from
+
+ // copy input/output information to locals (UPDATE macro restores)
+ p=z.next_in_index;n=z.avail_in;b=s.bitb;k=s.bitk;
+ q=s.write;m=q= 258 && n >= 10){
+
+ s.bitb=b;s.bitk=k;
+ z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
+ s.write=q;
+ r = inflate_fast(lbits, dbits,
+ ltree, ltree_index,
+ dtree, dtree_index,
+ s, z);
+
+ p=z.next_in_index;n=z.avail_in;b=s.bitb;k=s.bitk;
+ q=s.write;m=q>=(tree[tindex+1]);
+ k-=(tree[tindex+1]);
+
+ e=tree[tindex];
+
+ if(e == 0){ // literal
+ lit = tree[tindex+2];
+ mode = LIT;
+ break;
+ }
+ if((e & 16)!=0 ){ // length
+ get = e & 15;
+ len = tree[tindex+2];
+ mode = LENEXT;
+ break;
+ }
+ if ((e & 64) == 0){ // next table
+ need = e;
+ tree_index = tindex/3+tree[tindex+2];
+ break;
+ }
+ if ((e & 32)!=0){ // end of block
+ mode = WASH;
+ break;
+ }
+ mode = BADCODE; // invalid code
+ z.msg = "invalid literal/length code";
+ r = Z_DATA_ERROR;
+
+ s.bitb=b;s.bitk=k;
+ z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
+ s.write=q;
+ return s.inflate_flush(z,r);
+
+ case LENEXT: // i: getting length extra (have base)
+ j = get;
+
+ while(k<(j)){
+ if(n!=0)r=Z_OK;
+ else{
+
+ s.bitb=b;s.bitk=k;
+ z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
+ s.write=q;
+ return s.inflate_flush(z,r);
+ }
+ n--; b|=(z.next_in[p++]&0xff)<>=j;
+ k-=j;
+
+ need = dbits;
+ tree = dtree;
+ tree_index=dtree_index;
+ mode = DIST;
+ goto case DIST;
+ case DIST: // i: get distance next
+ j = need;
+
+ while(k<(j)){
+ if(n!=0)r=Z_OK;
+ else{
+
+ s.bitb=b;s.bitk=k;
+ z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
+ s.write=q;
+ return s.inflate_flush(z,r);
+ }
+ n--; b|=(z.next_in[p++]&0xff)<>=tree[tindex+1];
+ k-=tree[tindex+1];
+
+ e = (tree[tindex]);
+ if((e & 16)!=0){ // distance
+ get = e & 15;
+ dist = tree[tindex+2];
+ mode = DISTEXT;
+ break;
+ }
+ if ((e & 64) == 0){ // next table
+ need = e;
+ tree_index = tindex/3 + tree[tindex+2];
+ break;
+ }
+ mode = BADCODE; // invalid code
+ z.msg = "invalid distance code";
+ r = Z_DATA_ERROR;
+
+ s.bitb=b;s.bitk=k;
+ z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
+ s.write=q;
+ return s.inflate_flush(z,r);
+
+ case DISTEXT: // i: getting distance extra
+ j = get;
+
+ while(k<(j)){
+ if(n!=0)r=Z_OK;
+ else{
+
+ s.bitb=b;s.bitk=k;
+ z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
+ s.write=q;
+ return s.inflate_flush(z,r);
+ }
+ n--; b|=(z.next_in[p++]&0xff)<>=j;
+ k-=j;
+
+ mode = COPY;
+ goto case COPY;
+ case COPY: // o: copying bytes in window, waiting for space
+ f = q - dist;
+ while(f < 0){ // modulo window size-"while" instead
+ f += s.end; // of "if" handles invalid distances
+ }
+ while (len!=0){
+
+ if(m==0){
+ if(q==s.end&&s.read!=0){q=0;m=q 7){ // return unused byte, if any
+ k -= 8;
+ n++;
+ p--; // can always return one
+ }
+
+ s.write=q; r=s.inflate_flush(z,r);
+ q=s.write;m=q= 258 && n >= 10
+ // get literal/length code
+ while(k<(20)){ // max bits for literal/length code
+ n--;
+ b|=(z.next_in[p++]&0xff)<>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]);
+
+ s.window[q++] = (byte)tp[tp_index_t_3+2];
+ m--;
+ continue;
+ }
+ do {
+
+ b>>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]);
+
+ if((e&16)!=0){
+ e &= 15;
+ c = tp[tp_index_t_3+2] + ((int)b & inflate_mask[e]);
+
+ b>>=e; k-=e;
+
+ // decode distance base of block to copy
+ while(k<(15)){ // max bits for distance code
+ n--;
+ b|=(z.next_in[p++]&0xff)<>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]);
+
+ if((e&16)!=0){
+ // get extra bits to add to distance base
+ e &= 15;
+ while(k<(e)){ // get extra bits (up to 13)
+ n--;
+ b|=(z.next_in[p++]&0xff)<>=(e); k-=(e);
+
+ // do the copy
+ m -= c;
+ if (q >= d){ // offset before dest
+ // just copy
+ r=q-d;
+ if(q-r>0 && 2>(q-r)){
+ s.window[q++]=s.window[r++]; // minimum count is three,
+ s.window[q++]=s.window[r++]; // so unroll loop a little
+ c-=2;
+ }
+ else{
+ System.Array.Copy(s.window, r, s.window, q, 2);
+ q+=2; r+=2; c-=2;
+ }
+ }
+ else{ // else offset after destination
+ r=q-d;
+ do{
+ r+=s.end; // force pointer in window
+ }while(r<0); // covers invalid distances
+ e=s.end-r;
+ if(c>e){ // if source crosses,
+ c-=e; // wrapped copy
+ if(q-r>0 && e>(q-r)){
+ do{s.window[q++] = s.window[r++];}
+ while(--e!=0);
+ }
+ else{
+ System.Array.Copy(s.window, r, s.window, q, e);
+ q+=e; r+=e; e=0;
+ }
+ r = 0; // copy rest from start of window
+ }
+
+ }
+
+ // copy all or what's left
+ if(q-r>0 && c>(q-r)){
+ do{s.window[q++] = s.window[r++];}
+ while(--c!=0);
+ }
+ else{
+ System.Array.Copy(s.window, r, s.window, q, c);
+ q+=c; r+=c; c=0;
+ }
+ break;
+ }
+ else if((e&64)==0){
+ t+=tp[tp_index_t_3+2];
+ t+=(b&inflate_mask[e]);
+ tp_index_t_3=(tp_index+t)*3;
+ e=tp[tp_index_t_3];
+ }
+ else{
+ z.msg = "invalid distance code";
+
+ c=z.avail_in-n;c=(k>>3)>3:c;n+=c;p-=c;k-=c<<3;
+
+ s.bitb=b;s.bitk=k;
+ z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
+ s.write=q;
+
+ return Z_DATA_ERROR;
+ }
+ }
+ while(true);
+ break;
+ }
+
+ if((e&64)==0){
+ t+=tp[tp_index_t_3+2];
+ t+=(b&inflate_mask[e]);
+ tp_index_t_3=(tp_index+t)*3;
+ if((e=tp[tp_index_t_3])==0){
+
+ b>>=(tp[tp_index_t_3+1]); k-=(tp[tp_index_t_3+1]);
+
+ s.window[q++]=(byte)tp[tp_index_t_3+2];
+ m--;
+ break;
+ }
+ }
+ else if((e&32)!=0){
+
+ c=z.avail_in-n;c=(k>>3)>3:c;n+=c;p-=c;k-=c<<3;
+
+ s.bitb=b;s.bitk=k;
+ z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
+ s.write=q;
+
+ return Z_STREAM_END;
+ }
+ else{
+ z.msg="invalid literal/length code";
+
+ c=z.avail_in-n;c=(k>>3)>3:c;n+=c;p-=c;k-=c<<3;
+
+ s.bitb=b;s.bitk=k;
+ z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
+ s.write=q;
+
+ return Z_DATA_ERROR;
+ }
+ }
+ while(true);
+ }
+ while(m>=258 && n>= 10);
+
+ // not enough input or output--restore pointers and return
+ c=z.avail_in-n;c=(k>>3)>3:c;n+=c;p-=c;k-=c<<3;
+
+ s.bitb=b;s.bitk=k;
+ z.avail_in=n;z.total_in+=p-z.next_in_index;z.next_in_index=p;
+ s.write=q;
+
+ return Z_OK;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/InfCodes.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/InfCodes.cs.meta
new file mode 100644
index 00000000..be5b50c7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/InfCodes.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 5900c7f6a2d2b704596f30b1ff8334c8
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/InfTree.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/InfTree.cs
new file mode 100644
index 00000000..68c3e39b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/InfTree.cs
@@ -0,0 +1,527 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+/*
+ * $Id: InfTree.cs,v 1.2 2008-05-10 09:35:40 bouncy Exp $
+ *
+Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the distribution.
+
+ 3. The names of the authors may not be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
+INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
+INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/*
+ * This program is based on zlib-1.1.3, so all credit should go authors
+ * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
+ * and contributors of zlib.
+ */
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Zlib {
+
+ internal sealed class InfTree{
+
+ private const int MANY=1440;
+
+ private const int Z_OK=0;
+ private const int Z_STREAM_END=1;
+ private const int Z_NEED_DICT=2;
+ private const int Z_ERRNO=-1;
+ private const int Z_STREAM_ERROR=-2;
+ private const int Z_DATA_ERROR=-3;
+ private const int Z_MEM_ERROR=-4;
+ private const int Z_BUF_ERROR=-5;
+ private const int Z_VERSION_ERROR=-6;
+
+ private const int fixed_bl = 9;
+ private const int fixed_bd = 5;
+
+ static readonly int[] fixed_tl = {
+ 96,7,256, 0,8,80, 0,8,16, 84,8,115,
+ 82,7,31, 0,8,112, 0,8,48, 0,9,192,
+ 80,7,10, 0,8,96, 0,8,32, 0,9,160,
+ 0,8,0, 0,8,128, 0,8,64, 0,9,224,
+ 80,7,6, 0,8,88, 0,8,24, 0,9,144,
+ 83,7,59, 0,8,120, 0,8,56, 0,9,208,
+ 81,7,17, 0,8,104, 0,8,40, 0,9,176,
+ 0,8,8, 0,8,136, 0,8,72, 0,9,240,
+ 80,7,4, 0,8,84, 0,8,20, 85,8,227,
+ 83,7,43, 0,8,116, 0,8,52, 0,9,200,
+ 81,7,13, 0,8,100, 0,8,36, 0,9,168,
+ 0,8,4, 0,8,132, 0,8,68, 0,9,232,
+ 80,7,8, 0,8,92, 0,8,28, 0,9,152,
+ 84,7,83, 0,8,124, 0,8,60, 0,9,216,
+ 82,7,23, 0,8,108, 0,8,44, 0,9,184,
+ 0,8,12, 0,8,140, 0,8,76, 0,9,248,
+ 80,7,3, 0,8,82, 0,8,18, 85,8,163,
+ 83,7,35, 0,8,114, 0,8,50, 0,9,196,
+ 81,7,11, 0,8,98, 0,8,34, 0,9,164,
+ 0,8,2, 0,8,130, 0,8,66, 0,9,228,
+ 80,7,7, 0,8,90, 0,8,26, 0,9,148,
+ 84,7,67, 0,8,122, 0,8,58, 0,9,212,
+ 82,7,19, 0,8,106, 0,8,42, 0,9,180,
+ 0,8,10, 0,8,138, 0,8,74, 0,9,244,
+ 80,7,5, 0,8,86, 0,8,22, 192,8,0,
+ 83,7,51, 0,8,118, 0,8,54, 0,9,204,
+ 81,7,15, 0,8,102, 0,8,38, 0,9,172,
+ 0,8,6, 0,8,134, 0,8,70, 0,9,236,
+ 80,7,9, 0,8,94, 0,8,30, 0,9,156,
+ 84,7,99, 0,8,126, 0,8,62, 0,9,220,
+ 82,7,27, 0,8,110, 0,8,46, 0,9,188,
+ 0,8,14, 0,8,142, 0,8,78, 0,9,252,
+ 96,7,256, 0,8,81, 0,8,17, 85,8,131,
+ 82,7,31, 0,8,113, 0,8,49, 0,9,194,
+ 80,7,10, 0,8,97, 0,8,33, 0,9,162,
+ 0,8,1, 0,8,129, 0,8,65, 0,9,226,
+ 80,7,6, 0,8,89, 0,8,25, 0,9,146,
+ 83,7,59, 0,8,121, 0,8,57, 0,9,210,
+ 81,7,17, 0,8,105, 0,8,41, 0,9,178,
+ 0,8,9, 0,8,137, 0,8,73, 0,9,242,
+ 80,7,4, 0,8,85, 0,8,21, 80,8,258,
+ 83,7,43, 0,8,117, 0,8,53, 0,9,202,
+ 81,7,13, 0,8,101, 0,8,37, 0,9,170,
+ 0,8,5, 0,8,133, 0,8,69, 0,9,234,
+ 80,7,8, 0,8,93, 0,8,29, 0,9,154,
+ 84,7,83, 0,8,125, 0,8,61, 0,9,218,
+ 82,7,23, 0,8,109, 0,8,45, 0,9,186,
+ 0,8,13, 0,8,141, 0,8,77, 0,9,250,
+ 80,7,3, 0,8,83, 0,8,19, 85,8,195,
+ 83,7,35, 0,8,115, 0,8,51, 0,9,198,
+ 81,7,11, 0,8,99, 0,8,35, 0,9,166,
+ 0,8,3, 0,8,131, 0,8,67, 0,9,230,
+ 80,7,7, 0,8,91, 0,8,27, 0,9,150,
+ 84,7,67, 0,8,123, 0,8,59, 0,9,214,
+ 82,7,19, 0,8,107, 0,8,43, 0,9,182,
+ 0,8,11, 0,8,139, 0,8,75, 0,9,246,
+ 80,7,5, 0,8,87, 0,8,23, 192,8,0,
+ 83,7,51, 0,8,119, 0,8,55, 0,9,206,
+ 81,7,15, 0,8,103, 0,8,39, 0,9,174,
+ 0,8,7, 0,8,135, 0,8,71, 0,9,238,
+ 80,7,9, 0,8,95, 0,8,31, 0,9,158,
+ 84,7,99, 0,8,127, 0,8,63, 0,9,222,
+ 82,7,27, 0,8,111, 0,8,47, 0,9,190,
+ 0,8,15, 0,8,143, 0,8,79, 0,9,254,
+ 96,7,256, 0,8,80, 0,8,16, 84,8,115,
+ 82,7,31, 0,8,112, 0,8,48, 0,9,193,
+
+ 80,7,10, 0,8,96, 0,8,32, 0,9,161,
+ 0,8,0, 0,8,128, 0,8,64, 0,9,225,
+ 80,7,6, 0,8,88, 0,8,24, 0,9,145,
+ 83,7,59, 0,8,120, 0,8,56, 0,9,209,
+ 81,7,17, 0,8,104, 0,8,40, 0,9,177,
+ 0,8,8, 0,8,136, 0,8,72, 0,9,241,
+ 80,7,4, 0,8,84, 0,8,20, 85,8,227,
+ 83,7,43, 0,8,116, 0,8,52, 0,9,201,
+ 81,7,13, 0,8,100, 0,8,36, 0,9,169,
+ 0,8,4, 0,8,132, 0,8,68, 0,9,233,
+ 80,7,8, 0,8,92, 0,8,28, 0,9,153,
+ 84,7,83, 0,8,124, 0,8,60, 0,9,217,
+ 82,7,23, 0,8,108, 0,8,44, 0,9,185,
+ 0,8,12, 0,8,140, 0,8,76, 0,9,249,
+ 80,7,3, 0,8,82, 0,8,18, 85,8,163,
+ 83,7,35, 0,8,114, 0,8,50, 0,9,197,
+ 81,7,11, 0,8,98, 0,8,34, 0,9,165,
+ 0,8,2, 0,8,130, 0,8,66, 0,9,229,
+ 80,7,7, 0,8,90, 0,8,26, 0,9,149,
+ 84,7,67, 0,8,122, 0,8,58, 0,9,213,
+ 82,7,19, 0,8,106, 0,8,42, 0,9,181,
+ 0,8,10, 0,8,138, 0,8,74, 0,9,245,
+ 80,7,5, 0,8,86, 0,8,22, 192,8,0,
+ 83,7,51, 0,8,118, 0,8,54, 0,9,205,
+ 81,7,15, 0,8,102, 0,8,38, 0,9,173,
+ 0,8,6, 0,8,134, 0,8,70, 0,9,237,
+ 80,7,9, 0,8,94, 0,8,30, 0,9,157,
+ 84,7,99, 0,8,126, 0,8,62, 0,9,221,
+ 82,7,27, 0,8,110, 0,8,46, 0,9,189,
+ 0,8,14, 0,8,142, 0,8,78, 0,9,253,
+ 96,7,256, 0,8,81, 0,8,17, 85,8,131,
+ 82,7,31, 0,8,113, 0,8,49, 0,9,195,
+ 80,7,10, 0,8,97, 0,8,33, 0,9,163,
+ 0,8,1, 0,8,129, 0,8,65, 0,9,227,
+ 80,7,6, 0,8,89, 0,8,25, 0,9,147,
+ 83,7,59, 0,8,121, 0,8,57, 0,9,211,
+ 81,7,17, 0,8,105, 0,8,41, 0,9,179,
+ 0,8,9, 0,8,137, 0,8,73, 0,9,243,
+ 80,7,4, 0,8,85, 0,8,21, 80,8,258,
+ 83,7,43, 0,8,117, 0,8,53, 0,9,203,
+ 81,7,13, 0,8,101, 0,8,37, 0,9,171,
+ 0,8,5, 0,8,133, 0,8,69, 0,9,235,
+ 80,7,8, 0,8,93, 0,8,29, 0,9,155,
+ 84,7,83, 0,8,125, 0,8,61, 0,9,219,
+ 82,7,23, 0,8,109, 0,8,45, 0,9,187,
+ 0,8,13, 0,8,141, 0,8,77, 0,9,251,
+ 80,7,3, 0,8,83, 0,8,19, 85,8,195,
+ 83,7,35, 0,8,115, 0,8,51, 0,9,199,
+ 81,7,11, 0,8,99, 0,8,35, 0,9,167,
+ 0,8,3, 0,8,131, 0,8,67, 0,9,231,
+ 80,7,7, 0,8,91, 0,8,27, 0,9,151,
+ 84,7,67, 0,8,123, 0,8,59, 0,9,215,
+ 82,7,19, 0,8,107, 0,8,43, 0,9,183,
+ 0,8,11, 0,8,139, 0,8,75, 0,9,247,
+ 80,7,5, 0,8,87, 0,8,23, 192,8,0,
+ 83,7,51, 0,8,119, 0,8,55, 0,9,207,
+ 81,7,15, 0,8,103, 0,8,39, 0,9,175,
+ 0,8,7, 0,8,135, 0,8,71, 0,9,239,
+ 80,7,9, 0,8,95, 0,8,31, 0,9,159,
+ 84,7,99, 0,8,127, 0,8,63, 0,9,223,
+ 82,7,27, 0,8,111, 0,8,47, 0,9,191,
+ 0,8,15, 0,8,143, 0,8,79, 0,9,255
+ };
+ static readonly int[] fixed_td = {
+ 80,5,1, 87,5,257, 83,5,17, 91,5,4097,
+ 81,5,5, 89,5,1025, 85,5,65, 93,5,16385,
+ 80,5,3, 88,5,513, 84,5,33, 92,5,8193,
+ 82,5,9, 90,5,2049, 86,5,129, 192,5,24577,
+ 80,5,2, 87,5,385, 83,5,25, 91,5,6145,
+ 81,5,7, 89,5,1537, 85,5,97, 93,5,24577,
+ 80,5,4, 88,5,769, 84,5,49, 92,5,12289,
+ 82,5,13, 90,5,3073, 86,5,193, 192,5,24577
+ };
+
+ // Tables for deflate from PKZIP's appnote.txt.
+ static readonly int[] cplens = { // Copy lengths for literal codes 257..285
+ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
+ 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
+ };
+
+ // see note #13 above about 258
+ static readonly int[] cplext = { // Extra bits for literal codes 257..285
+ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
+ 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112 // 112==invalid
+ };
+
+ static readonly int[] cpdist = { // Copy offsets for distance codes 0..29
+ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
+ 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
+ 8193, 12289, 16385, 24577
+ };
+
+ static readonly int[] cpdext = { // Extra bits for distance codes
+ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
+ 7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
+ 12, 12, 13, 13};
+
+ // If BMAX needs to be larger than 16, then h and x[] should be uLong.
+ const int BMAX=15; // maximum bit length of any code
+
+ int[] hn = null; // hufts used in space
+ int[] v = null; // work area for huft_build
+ int[] c = null; // bit length count table
+ int[] r = null; // table entry for structure assignment
+ int[] u = null; // table stack
+ int[] x = null; // bit offsets, then code stack
+
+ private int huft_build(int[] b, // code lengths in bits (all assumed <= BMAX)
+ int bindex,
+ int n, // number of codes (assumed <= 288)
+ int s, // number of simple-valued codes (0..s-1)
+ int[] d, // list of base values for non-simple codes
+ int[] e, // list of extra bits for non-simple codes
+ int[] t, // result: starting table
+ int[] m, // maximum lookup bits, returns actual
+ int[] hp,// space for trees
+ int[] hn,// hufts used in space
+ int[] v // working area: values in order of bit length
+ ){
+ // Given a list of code lengths and a maximum table size, make a set of
+ // tables to decode that set of codes. Return Z_OK on success, Z_BUF_ERROR
+ // if the given code set is incomplete (the tables are still built in this
+ // case), Z_DATA_ERROR if the input is invalid (an over-subscribed set of
+ // lengths), or Z_MEM_ERROR if not enough memory.
+
+ int a; // counter for codes of length k
+ int f; // i repeats in table every f entries
+ int g; // maximum code length
+ int h; // table level
+ int i; // counter, current code
+ int j; // counter
+ int k; // number of bits in current code
+ int l; // bits per table (returned in m)
+ int mask; // (1 << w) - 1, to avoid cc -O bug on HP
+ int p; // pointer into c[], b[], or v[]
+ int q; // points to current table
+ int w; // bits before this table == (l * h)
+ int xp; // pointer into x
+ int y; // number of dummy codes added
+ int z; // number of entries in current table
+
+ // Generate counts for each bit length
+
+ p = 0; i = n;
+ do {
+ c[b[bindex+p]]++; p++; i--; // assume all entries <= BMAX
+ }while(i!=0);
+
+ if(c[0] == n){ // null input--all zero length codes
+ t[0] = -1;
+ m[0] = 0;
+ return Z_OK;
+ }
+
+ // Find minimum and maximum length, bound *m by those
+ l = m[0];
+ for (j = 1; j <= BMAX; j++)
+ if(c[j]!=0) break;
+ k = j; // minimum code length
+ if(l < j){
+ l = j;
+ }
+ for (i = BMAX; i!=0; i--){
+ if(c[i]!=0) break;
+ }
+ g = i; // maximum code length
+ if(l > i){
+ l = i;
+ }
+ m[0] = l;
+
+ // Adjust last length count to fill out codes, if needed
+ for (y = 1 << j; j < i; j++, y <<= 1){
+ if ((y -= c[j]) < 0){
+ return Z_DATA_ERROR;
+ }
+ }
+ if ((y -= c[i]) < 0){
+ return Z_DATA_ERROR;
+ }
+ c[i] += y;
+
+ // Generate starting offsets into the value table for each length
+ x[1] = j = 0;
+ p = 1; xp = 2;
+ while (--i!=0) { // note that i == g from above
+ x[xp] = (j += c[p]);
+ xp++;
+ p++;
+ }
+
+ // Make a table of values in order of bit lengths
+ i = 0; p = 0;
+ do {
+ if ((j = b[bindex+p]) != 0){
+ v[x[j]++] = i;
+ }
+ p++;
+ }
+ while (++i < n);
+ n = x[g]; // set n to length of v
+
+ // Generate the Huffman codes and for each, make the table entries
+ x[0] = i = 0; // first Huffman code is zero
+ p = 0; // grab values in bit order
+ h = -1; // no tables yet--level -1
+ w = -l; // bits decoded == (l * h)
+ u[0] = 0; // just to keep compilers happy
+ q = 0; // ditto
+ z = 0; // ditto
+
+ // go through the bit lengths (k already is bits in shortest code)
+ for (; k <= g; k++){
+ a = c[k];
+ while (a--!=0){
+ // here i is the Huffman code of length k bits for value *p
+ // make tables up to required level
+ while (k > w + l){
+ h++;
+ w += l; // previous table always l bits
+ // compute minimum size table less than or equal to l bits
+ z = g - w;
+ z = (z > l) ? l : z; // table size upper limit
+ if((f=1<<(j=k-w))>a+1){ // try a k-w bit table
+ // too few codes for k-w bit table
+ f -= a + 1; // deduct codes from patterns left
+ xp = k;
+ if(j < z){
+ while (++j < z){ // try smaller tables up to z bits
+ if((f <<= 1) <= c[++xp])
+ break; // enough codes to use up j bits
+ f -= c[xp]; // else deduct codes from patterns
+ }
+ }
+ }
+ z = 1 << j; // table entries for j-bit table
+
+ // allocate new table
+ if (hn[0] + z > MANY){ // (note: doesn't matter for fixed)
+ return Z_DATA_ERROR; // overflow of MANY
+ }
+ u[h] = q = /*hp+*/ hn[0]; // DEBUG
+ hn[0] += z;
+
+ // connect to last table, if there is one
+ if(h!=0){
+ x[h]=i; // save pattern for backing up
+ r[0]=(byte)j; // bits in this table
+ r[1]=(byte)l; // bits to dump before this table
+ j=i>>(w - l);
+ r[2] = (int)(q - u[h-1] - j); // offset to this table
+ System.Array.Copy(r, 0, hp, (u[h-1]+j)*3, 3); // connect to last table
+ }
+ else{
+ t[0] = q; // first table is returned result
+ }
+ }
+
+ // set up table entry in r
+ r[1] = (byte)(k - w);
+ if (p >= n){
+ r[0] = 128 + 64; // out of values--invalid code
+ }
+ else if (v[p] < s){
+ r[0] = (byte)(v[p] < 256 ? 0 : 32 + 64); // 256 is end-of-block
+ r[2] = v[p++]; // simple code is just the value
+ }
+ else{
+ r[0]=(byte)(e[v[p]-s]+16+64); // non-simple--look up in lists
+ r[2]=d[v[p++] - s];
+ }
+
+ // fill code-like entries with r
+ f=1<<(k-w);
+ for (j=i>>w;j>= 1){
+ i ^= j;
+ }
+ i ^= j;
+
+ // backup over finished tables
+ mask = (1 << w) - 1; // needed on HP, cc -O bug
+ while ((i & mask) != x[h]){
+ h--; // don't need to update q
+ w -= l;
+ mask = (1 << w) - 1;
+ }
+ }
+ }
+ // Return Z_BUF_ERROR if we were given an incomplete table
+ return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK;
+ }
+
+ internal int inflate_trees_bits(int[] c, // 19 code lengths
+ int[] bb, // bits tree desired/actual depth
+ int[] tb, // bits tree result
+ int[] hp, // space for trees
+ ZStream z // for messages
+ ){
+ int result;
+ initWorkArea(19);
+ hn[0]=0;
+ result = huft_build(c, 0, 19, 19, null, null, tb, bb, hp, hn, v);
+
+ if(result == Z_DATA_ERROR){
+ z.msg = "oversubscribed dynamic bit lengths tree";
+ }
+ else if(result == Z_BUF_ERROR || bb[0] == 0){
+ z.msg = "incomplete dynamic bit lengths tree";
+ result = Z_DATA_ERROR;
+ }
+ return result;
+ }
+
+ internal int inflate_trees_dynamic(int nl, // number of literal/length codes
+ int nd, // number of distance codes
+ int[] c, // that many (total) code lengths
+ int[] bl, // literal desired/actual bit depth
+ int[] bd, // distance desired/actual bit depth
+ int[] tl, // literal/length tree result
+ int[] td, // distance tree result
+ int[] hp, // space for trees
+ ZStream z // for messages
+ ){
+ int result;
+
+ // build literal/length tree
+ initWorkArea(288);
+ hn[0]=0;
+ result = huft_build(c, 0, nl, 257, cplens, cplext, tl, bl, hp, hn, v);
+ if (result != Z_OK || bl[0] == 0){
+ if(result == Z_DATA_ERROR){
+ z.msg = "oversubscribed literal/length tree";
+ }
+ else if (result != Z_MEM_ERROR){
+ z.msg = "incomplete literal/length tree";
+ result = Z_DATA_ERROR;
+ }
+ return result;
+ }
+
+ // build distance tree
+ initWorkArea(288);
+ result = huft_build(c, nl, nd, 0, cpdist, cpdext, td, bd, hp, hn, v);
+
+ if (result != Z_OK || (bd[0] == 0 && nl > 257)){
+ if (result == Z_DATA_ERROR){
+ z.msg = "oversubscribed distance tree";
+ }
+ else if (result == Z_BUF_ERROR) {
+ z.msg = "incomplete distance tree";
+ result = Z_DATA_ERROR;
+ }
+ else if (result != Z_MEM_ERROR){
+ z.msg = "empty distance tree with lengths";
+ result = Z_DATA_ERROR;
+ }
+ return result;
+ }
+
+ return Z_OK;
+ }
+
+ internal static int inflate_trees_fixed(int[] bl, //literal desired/actual bit depth
+ int[] bd, //distance desired/actual bit depth
+ int[][] tl,//literal/length tree result
+ int[][] td,//distance tree result
+ ZStream z //for memory allocation
+ ){
+ bl[0]=fixed_bl;
+ bd[0]=fixed_bd;
+ tl[0]=fixed_tl;
+ td[0]=fixed_td;
+ return Z_OK;
+ }
+
+ private void initWorkArea(int vsize){
+ if(hn==null){
+ hn=new int[1];
+ v=new int[vsize];
+ c=new int[BMAX+1];
+ r=new int[3];
+ u=new int[BMAX];
+ x=new int[BMAX+1];
+ }
+ if(v.Lengthstate);
+ return Z_OK;
+ }
+
+ internal int inflateInit(ZStream z, int w){
+ z.msg = null;
+ blocks = null;
+
+ // handle undocumented nowrap option (no zlib header or check)
+ nowrap = 0;
+ if(w < 0){
+ w = - w;
+ nowrap = 1;
+ }
+
+ // set window size
+ if(w<8 ||w>15){
+ inflateEnd(z);
+ return Z_STREAM_ERROR;
+ }
+ wbits=w;
+
+ z.istate.blocks=new InfBlocks(z,
+ z.istate.nowrap!=0 ? null : this,
+ 1<>4)+8>z.istate.wbits){
+ z.istate.mode = BAD;
+ z.msg="invalid window size";
+ z.istate.marker = 5; // can't try inflateSync
+ break;
+ }
+ z.istate.mode=FLAG;
+ goto case FLAG;
+ case FLAG:
+
+ if(z.avail_in==0)return r;r=f;
+
+ z.avail_in--; z.total_in++;
+ b = (z.next_in[z.next_in_index++])&0xff;
+
+ if((((z.istate.method << 8)+b) % 31)!=0){
+ z.istate.mode = BAD;
+ z.msg = "incorrect header check";
+ z.istate.marker = 5; // can't try inflateSync
+ break;
+ }
+
+ if((b&PRESET_DICT)==0){
+ z.istate.mode = BLOCKS;
+ break;
+ }
+ z.istate.mode = DICT4;
+ goto case DICT4;
+ case DICT4:
+
+ if(z.avail_in==0)return r;r=f;
+
+ z.avail_in--; z.total_in++;
+ z.istate.need=((z.next_in[z.next_in_index++]&0xff)<<24)&0xff000000L;
+ z.istate.mode=DICT3;
+ goto case DICT3;
+ case DICT3:
+
+ if(z.avail_in==0)return r;r=f;
+
+ z.avail_in--; z.total_in++;
+ z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<16)&0xff0000L;
+ z.istate.mode=DICT2;
+ goto case DICT2;
+ case DICT2:
+
+ if(z.avail_in==0)return r;r=f;
+
+ z.avail_in--; z.total_in++;
+ z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<8)&0xff00L;
+ z.istate.mode=DICT1;
+ goto case DICT1;
+ case DICT1:
+
+ if(z.avail_in==0)return r;r=f;
+
+ z.avail_in--; z.total_in++;
+ z.istate.need += (z.next_in[z.next_in_index++]&0xffL);
+ z.adler = z.istate.need;
+ z.istate.mode = DICT0;
+ return Z_NEED_DICT;
+ case DICT0:
+ z.istate.mode = BAD;
+ z.msg = "need dictionary";
+ z.istate.marker = 0; // can try inflateSync
+ return Z_STREAM_ERROR;
+ case BLOCKS:
+
+ r = z.istate.blocks.proc(z, r);
+ if(r == Z_DATA_ERROR){
+ z.istate.mode = BAD;
+ z.istate.marker = 0; // can try inflateSync
+ break;
+ }
+ if(r == Z_OK){
+ r = f;
+ }
+ if(r != Z_STREAM_END){
+ return r;
+ }
+ r = f;
+ z.istate.blocks.reset(z, z.istate.was);
+ if(z.istate.nowrap!=0){
+ z.istate.mode=DONE;
+ break;
+ }
+ z.istate.mode=CHECK4;
+ goto case CHECK4;
+ case CHECK4:
+
+ if(z.avail_in==0)return r;r=f;
+
+ z.avail_in--; z.total_in++;
+ z.istate.need=((z.next_in[z.next_in_index++]&0xff)<<24)&0xff000000L;
+ z.istate.mode=CHECK3;
+ goto case CHECK3;
+ case CHECK3:
+
+ if(z.avail_in==0)return r;r=f;
+
+ z.avail_in--; z.total_in++;
+ z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<16)&0xff0000L;
+ z.istate.mode = CHECK2;
+ goto case CHECK2;
+ case CHECK2:
+
+ if(z.avail_in==0)return r;r=f;
+
+ z.avail_in--; z.total_in++;
+ z.istate.need+=((z.next_in[z.next_in_index++]&0xff)<<8)&0xff00L;
+ z.istate.mode = CHECK1;
+ goto case CHECK1;
+ case CHECK1:
+
+ if(z.avail_in==0)return r;r=f;
+
+ z.avail_in--; z.total_in++;
+ z.istate.need+=(z.next_in[z.next_in_index++]&0xffL);
+
+ if(((int)(z.istate.was[0])) != ((int)(z.istate.need))){
+ z.istate.mode = BAD;
+ z.msg = "incorrect data check";
+ z.istate.marker = 5; // can't try inflateSync
+ break;
+ }
+
+ z.istate.mode = DONE;
+ goto case DONE;
+ case DONE:
+ return Z_STREAM_END;
+ case BAD:
+ return Z_DATA_ERROR;
+ default:
+ return Z_STREAM_ERROR;
+ }
+ }
+ }
+
+
+ internal int inflateSetDictionary(ZStream z, byte[] dictionary, int dictLength){
+ int index=0;
+ int length = dictLength;
+ if(z==null || z.istate == null|| z.istate.mode != DICT0)
+ return Z_STREAM_ERROR;
+
+ if(z._adler.adler32(1L, dictionary, 0, dictLength)!=z.adler){
+ return Z_DATA_ERROR;
+ }
+
+ z.adler = z._adler.adler32(0, null, 0, 0);
+
+ if(length >= (1<
+ /// Summary description for DeflaterOutputStream.
+ ///
+ [Obsolete("Use 'ZOutputStream' instead")]
+ public class ZDeflaterOutputStream : Stream {
+ protected ZStream z=new ZStream();
+ protected int flushLevel=JZlib.Z_NO_FLUSH;
+ private const int BUFSIZE = 4192;
+ protected byte[] buf=new byte[BUFSIZE];
+ private byte[] buf1=new byte[1];
+
+ protected Stream outp;
+
+ public ZDeflaterOutputStream(Stream outp) : this(outp, 6, false) {
+ }
+
+ public ZDeflaterOutputStream(Stream outp, int level) : this(outp, level, false) {
+ }
+
+ public ZDeflaterOutputStream(Stream outp, int level, bool nowrap) {
+ this.outp=outp;
+ z.deflateInit(level, nowrap);
+ }
+
+
+ public override bool CanRead {
+ get {
+ // TODO: Add DeflaterOutputStream.CanRead getter implementation
+ return false;
+ }
+ }
+
+ public override bool CanSeek {
+ get {
+ // TODO: Add DeflaterOutputStream.CanSeek getter implementation
+ return false;
+ }
+ }
+
+ public override bool CanWrite {
+ get {
+ // TODO: Add DeflaterOutputStream.CanWrite getter implementation
+ return true;
+ }
+ }
+
+ public override long Length {
+ get {
+ // TODO: Add DeflaterOutputStream.Length getter implementation
+ return 0;
+ }
+ }
+
+ public override long Position {
+ get {
+ // TODO: Add DeflaterOutputStream.Position getter implementation
+ return 0;
+ }
+ set {
+ // TODO: Add DeflaterOutputStream.Position setter implementation
+ }
+ }
+
+ public override void Write(byte[] b, int off, int len) {
+ if(len==0)
+ return;
+ int err;
+ z.next_in=b;
+ z.next_in_index=off;
+ z.avail_in=len;
+ do{
+ z.next_out=buf;
+ z.next_out_index=0;
+ z.avail_out=BUFSIZE;
+ err=z.deflate(flushLevel);
+ if(err!=JZlib.Z_OK)
+ throw new IOException("deflating: "+z.msg);
+ if (z.avail_out < BUFSIZE)
+ {
+ outp.Write(buf, 0, BUFSIZE-z.avail_out);
+ }
+ }
+ while(z.avail_in>0 || z.avail_out==0);
+ }
+
+ public override long Seek(long offset, SeekOrigin origin) {
+ // TODO: Add DeflaterOutputStream.Seek implementation
+ return 0;
+ }
+
+ public override void SetLength(long value) {
+ // TODO: Add DeflaterOutputStream.SetLength implementation
+
+ }
+
+ public override int Read(byte[] buffer, int offset, int count) {
+ // TODO: Add DeflaterOutputStream.Read implementation
+ return 0;
+ }
+
+ public override void Flush() {
+ outp.Flush();
+ }
+
+ public override void WriteByte(byte b) {
+ buf1[0]=(byte)b;
+ Write(buf1, 0, 1);
+ }
+
+ public void Finish() {
+ int err;
+ do{
+ z.next_out=buf;
+ z.next_out_index=0;
+ z.avail_out=BUFSIZE;
+ err=z.deflate(JZlib.Z_FINISH);
+ if(err!=JZlib.Z_STREAM_END && err != JZlib.Z_OK)
+ throw new IOException("deflating: "+z.msg);
+ if(BUFSIZE-z.avail_out>0){
+ outp.Write(buf, 0, BUFSIZE-z.avail_out);
+ }
+ }
+ while(z.avail_in>0 || z.avail_out==0);
+ Flush();
+ }
+
+ public void End() {
+ if(z==null)
+ return;
+ z.deflateEnd();
+ z.free();
+ z=null;
+ }
+
+#if PORTABLE || NETFX_CORE
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ try{
+ try{Finish();}
+ catch (IOException) {}
+ }
+ finally{
+ End();
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(outp);
+ outp=null;
+ }
+ }
+ base.Dispose(disposing);
+ }
+#else
+ public override void Close() {
+ try{
+ try{Finish();}
+ catch (IOException) {}
+ }
+ finally{
+ End();
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(outp);
+ outp=null;
+ }
+ base.Close();
+ }
+#endif
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/ZDeflaterOutputStream.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/ZDeflaterOutputStream.cs.meta
new file mode 100644
index 00000000..7fdbca21
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/ZDeflaterOutputStream.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 1235cf9b25f415a43af3b5e12ebb8a8d
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/ZInflaterInputStream.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/ZInflaterInputStream.cs
new file mode 100644
index 00000000..9f695af1
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/ZInflaterInputStream.cs
@@ -0,0 +1,144 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Zlib {
+ ///
+ /// Summary description for DeflaterOutputStream.
+ ///
+ [Obsolete("Use 'ZInputStream' instead")]
+ public class ZInflaterInputStream : Stream {
+ protected ZStream z=new ZStream();
+ protected int flushLevel=JZlib.Z_NO_FLUSH;
+ private const int BUFSIZE = 4192;
+ protected byte[] buf=new byte[BUFSIZE];
+ private byte[] buf1=new byte[1];
+
+ protected Stream inp=null;
+ private bool nomoreinput=false;
+
+ public ZInflaterInputStream(Stream inp) : this(inp, false) {
+ }
+
+ public ZInflaterInputStream(Stream inp, bool nowrap) {
+ this.inp=inp;
+ z.inflateInit(nowrap);
+ z.next_in=buf;
+ z.next_in_index=0;
+ z.avail_in=0;
+ }
+
+ public override bool CanRead {
+ get {
+ // TODO: Add DeflaterOutputStream.CanRead getter implementation
+ return true;
+ }
+ }
+
+ public override bool CanSeek {
+ get {
+ // TODO: Add DeflaterOutputStream.CanSeek getter implementation
+ return false;
+ }
+ }
+
+ public override bool CanWrite {
+ get {
+ // TODO: Add DeflaterOutputStream.CanWrite getter implementation
+ return false;
+ }
+ }
+
+ public override long Length {
+ get {
+ // TODO: Add DeflaterOutputStream.Length getter implementation
+ return 0;
+ }
+ }
+
+ public override long Position {
+ get {
+ // TODO: Add DeflaterOutputStream.Position getter implementation
+ return 0;
+ }
+ set {
+ // TODO: Add DeflaterOutputStream.Position setter implementation
+ }
+ }
+
+ public override void Write(byte[] b, int off, int len) {
+ }
+
+ public override long Seek(long offset, SeekOrigin origin) {
+ // TODO: Add DeflaterOutputStream.Seek implementation
+ return 0;
+ }
+
+ public override void SetLength(long value) {
+ // TODO: Add DeflaterOutputStream.SetLength implementation
+
+ }
+
+ public override int Read(byte[] b, int off, int len) {
+ if(len==0)
+ return(0);
+ int err;
+ z.next_out=b;
+ z.next_out_index=off;
+ z.avail_out=len;
+ do {
+ if((z.avail_in==0)&&(!nomoreinput)) { // if buffer is empty and more input is avaiable, refill it
+ z.next_in_index=0;
+ z.avail_in=inp.Read(buf, 0, BUFSIZE);//(BUFSIZE 0)
+ {
+ output.Write(buf, 0, count);
+ }
+ }
+ while (z.avail_in > 0 || z.avail_out == 0);
+
+ Flush();
+ }
+
+ public override void Flush()
+ {
+ output.Flush();
+ }
+
+ public virtual int FlushMode
+ {
+ get { return flushLevel; }
+ set { this.flushLevel = value; }
+ }
+
+ public sealed override long Length { get { throw new NotSupportedException(); } }
+ public sealed override long Position
+ {
+ get { throw new NotSupportedException(); }
+ set { throw new NotSupportedException(); }
+ }
+ public sealed override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); }
+ public sealed override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); }
+ public sealed override void SetLength(long value) { throw new NotSupportedException(); }
+
+ public virtual long TotalIn
+ {
+ get { return z.total_in; }
+ }
+
+ public virtual long TotalOut
+ {
+ get { return z.total_out; }
+ }
+
+ public override void Write(byte[] b, int off, int len)
+ {
+ if (len == 0)
+ return;
+
+ z.next_in = b;
+ z.next_in_index = off;
+ z.avail_in = len;
+
+ do
+ {
+ z.next_out = buf;
+ z.next_out_index = 0;
+ z.avail_out = buf.Length;
+
+ int err = compress
+ ? z.deflate(flushLevel)
+ : z.inflate(flushLevel);
+
+ if (err != JZlib.Z_OK)
+ // TODO
+// throw new ZStreamException((compress ? "de" : "in") + "flating: " + z.msg);
+ throw new IOException((compress ? "de" : "in") + "flating: " + z.msg);
+
+ output.Write(buf, 0, buf.Length - z.avail_out);
+ }
+ while (z.avail_in > 0 || z.avail_out == 0);
+ }
+
+ public override void WriteByte(byte b)
+ {
+ buf1[0] = b;
+ Write(buf1, 0, 1);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/ZOutputStream.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/ZOutputStream.cs.meta
new file mode 100644
index 00000000..4a5a596e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/ZOutputStream.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 7184782482afa5f43b30b456f1930268
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/ZStream.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/ZStream.cs
new file mode 100644
index 00000000..ea4c53eb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/ZStream.cs
@@ -0,0 +1,218 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+/*
+ * $Id: ZStream.cs,v 1.1 2006-07-31 13:59:26 bouncy Exp $
+ *
+Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the distribution.
+
+ 3. The names of the authors may not be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
+INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
+INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/*
+ * This program is based on zlib-1.1.3, so all credit should go authors
+ * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
+ * and contributors of zlib.
+ */
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Zlib {
+
+ public sealed class ZStream{
+
+ private const int MAX_WBITS=15; // 32K LZ77 window
+ private const int DEF_WBITS=MAX_WBITS;
+
+ private const int Z_NO_FLUSH=0;
+ private const int Z_PARTIAL_FLUSH=1;
+ private const int Z_SYNC_FLUSH=2;
+ private const int Z_FULL_FLUSH=3;
+ private const int Z_FINISH=4;
+
+ private const int MAX_MEM_LEVEL=9;
+
+ private const int Z_OK=0;
+ private const int Z_STREAM_END=1;
+ private const int Z_NEED_DICT=2;
+ private const int Z_ERRNO=-1;
+ private const int Z_STREAM_ERROR=-2;
+ private const int Z_DATA_ERROR=-3;
+ private const int Z_MEM_ERROR=-4;
+ private const int Z_BUF_ERROR=-5;
+ private const int Z_VERSION_ERROR=-6;
+
+ public byte[] next_in; // next input byte
+ public int next_in_index;
+ public int avail_in; // number of bytes available at next_in
+ public long total_in; // total nb of input bytes read so far
+
+ public byte[] next_out; // next output byte should be put there
+ public int next_out_index;
+ public int avail_out; // remaining free space at next_out
+ public long total_out; // total nb of bytes output so far
+
+ public String msg;
+
+ internal Deflate dstate;
+ internal Inflate istate;
+
+ internal int data_type; // best guess about the data type: ascii or binary
+
+ public long adler;
+ internal Adler32 _adler=new Adler32();
+
+ public int inflateInit(){
+ return inflateInit(DEF_WBITS);
+ }
+ public int inflateInit(bool nowrap){
+ return inflateInit(DEF_WBITS, nowrap);
+ }
+ public int inflateInit(int w){
+ return inflateInit(w, false);
+ }
+
+ public int inflateInit(int w, bool nowrap){
+ istate=new Inflate();
+ return istate.inflateInit(this, nowrap?-w:w);
+ }
+
+ public int inflate(int f){
+ if(istate==null) return Z_STREAM_ERROR;
+ return istate.inflate(this, f);
+ }
+ public int inflateEnd(){
+ if(istate==null) return Z_STREAM_ERROR;
+ int ret=istate.inflateEnd(this);
+ istate = null;
+ return ret;
+ }
+ public int inflateSync(){
+ if(istate == null)
+ return Z_STREAM_ERROR;
+ return istate.inflateSync(this);
+ }
+ public int inflateSetDictionary(byte[] dictionary, int dictLength){
+ if(istate == null)
+ return Z_STREAM_ERROR;
+ return istate.inflateSetDictionary(this, dictionary, dictLength);
+ }
+
+ public int deflateInit(int level){
+ return deflateInit(level, MAX_WBITS);
+ }
+ public int deflateInit(int level, bool nowrap){
+ return deflateInit(level, MAX_WBITS, nowrap);
+ }
+ public int deflateInit(int level, int bits){
+ return deflateInit(level, bits, false);
+ }
+ public int deflateInit(int level, int bits, bool nowrap){
+ dstate=new Deflate();
+ return dstate.deflateInit(this, level, nowrap?-bits:bits);
+ }
+ public int deflate(int flush){
+ if(dstate==null){
+ return Z_STREAM_ERROR;
+ }
+ return dstate.deflate(this, flush);
+ }
+ public int deflateEnd(){
+ if(dstate==null) return Z_STREAM_ERROR;
+ int ret=dstate.deflateEnd();
+ dstate=null;
+ return ret;
+ }
+ public int deflateParams(int level, int strategy){
+ if(dstate==null) return Z_STREAM_ERROR;
+ return dstate.deflateParams(this, level, strategy);
+ }
+ public int deflateSetDictionary (byte[] dictionary, int dictLength){
+ if(dstate == null)
+ return Z_STREAM_ERROR;
+ return dstate.deflateSetDictionary(this, dictionary, dictLength);
+ }
+
+ // Flush as much pending output as possible. All deflate() output goes
+ // through this function so some applications may wish to modify it
+ // to avoid allocating a large strm->next_out buffer and copying into it.
+ // (See also read_buf()).
+ internal void flush_pending(){
+ int len=dstate.pending;
+
+ if(len>avail_out) len=avail_out;
+ if(len==0) return;
+
+ if(dstate.pending_buf.Length<=dstate.pending_out ||
+ next_out.Length<=next_out_index ||
+ dstate.pending_buf.Length<(dstate.pending_out+len) ||
+ next_out.Length<(next_out_index+len)){
+ // System.out.println(dstate.pending_buf.length+", "+dstate.pending_out+
+ // ", "+next_out.length+", "+next_out_index+", "+len);
+ // System.out.println("avail_out="+avail_out);
+ }
+
+ System.Array.Copy(dstate.pending_buf, dstate.pending_out,
+ next_out, next_out_index, len);
+
+ next_out_index+=len;
+ dstate.pending_out+=len;
+ total_out+=len;
+ avail_out-=len;
+ dstate.pending-=len;
+ if(dstate.pending==0){
+ dstate.pending_out=0;
+ }
+ }
+
+ // Read a new buffer from the current input stream, update the adler32
+ // and total number of bytes read. All deflate() input goes through
+ // this function so some applications may wish to modify it to avoid
+ // allocating a large strm->next_in buffer and copying from it.
+ // (See also flush_pending()).
+ internal int read_buf(byte[] buf, int start, int size) {
+ int len=avail_in;
+
+ if(len>size) len=size;
+ if(len==0) return 0;
+
+ avail_in-=len;
+
+ if(dstate.noheader==0) {
+ adler=_adler.adler32(adler, next_in, next_in_index, len);
+ }
+ System.Array.Copy(next_in, next_in_index, buf, start, len);
+ next_in_index += len;
+ total_in += len;
+ return len;
+ }
+
+ public void free(){
+ next_in=null;
+ next_out=null;
+ msg=null;
+ _adler=null;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/ZStream.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/ZStream.cs.meta
new file mode 100644
index 00000000..b4414aea
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/ZStream.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 8ddcf6fa74a82c246a547246aefee100
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/ZTree.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/ZTree.cs
new file mode 100644
index 00000000..068f027c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/ZTree.cs
@@ -0,0 +1,371 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+/*
+ * $Id: Tree.cs,v 1.2 2008-05-10 09:35:40 bouncy Exp $
+ *
+Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the distribution.
+
+ 3. The names of the authors may not be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
+INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
+INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/*
+ * This program is based on zlib-1.1.3, so all credit should go authors
+ * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
+ * and contributors of zlib.
+ */
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Zlib {
+
+ internal sealed class ZTree{
+ private const int MAX_BITS=15;
+ private const int BL_CODES=19;
+ private const int D_CODES=30;
+ private const int LITERALS=256;
+ private const int LENGTH_CODES=29;
+ private const int L_CODES=(LITERALS+1+LENGTH_CODES);
+ private const int HEAP_SIZE=(2*L_CODES+1);
+
+ // Bit length codes must not exceed MAX_BL_BITS bits
+ internal const int MAX_BL_BITS=7;
+
+ // end of block literal code
+ internal const int END_BLOCK=256;
+
+ // repeat previous bit length 3-6 times (2 bits of repeat count)
+ internal const int REP_3_6=16;
+
+ // repeat a zero length 3-10 times (3 bits of repeat count)
+ internal const int REPZ_3_10=17;
+
+ // repeat a zero length 11-138 times (7 bits of repeat count)
+ internal const int REPZ_11_138=18;
+
+ // extra bits for each length code
+ internal static readonly int[] extra_lbits={
+ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0
+ };
+
+ // extra bits for each distance code
+ internal static readonly int[] extra_dbits={
+ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13
+ };
+
+ // extra bits for each bit length code
+ internal static readonly int[] extra_blbits={
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7
+ };
+
+ internal static readonly byte[] bl_order={
+ 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
+
+
+ // The lengths of the bit length codes are sent in order of decreasing
+ // probability, to avoid transmitting the lengths for unused bit
+ // length codes.
+
+ internal const int Buf_size=8*2;
+
+ // see definition of array dist_code below
+ internal const int DIST_CODE_LEN=512;
+
+ internal static readonly byte[] _dist_code = {
+ 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
+ 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
+ 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
+ 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+ 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
+ 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+ 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
+ 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+ 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+ 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
+ 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
+ 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+ 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
+ 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
+ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
+ 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
+ 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
+ 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
+ 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
+ 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
+ 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
+ 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
+ };
+
+ internal static readonly byte[] _length_code={
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
+ 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
+ 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
+ 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+ 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
+ 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
+ 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+ 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
+ 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
+ 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
+ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
+ };
+
+ internal static readonly int[] base_length = {
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
+ 64, 80, 96, 112, 128, 160, 192, 224, 0
+ };
+
+ internal static readonly int[] base_dist = {
+ 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
+ 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
+ 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
+ };
+
+ // Mapping from a distance to a distance code. dist is the distance - 1 and
+ // must not have side effects. _dist_code[256] and _dist_code[257] are never
+ // used.
+ internal static int d_code(int dist){
+ return ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]);
+ }
+
+ internal short[] dyn_tree; // the dynamic tree
+ internal int max_code; // largest code with non zero frequency
+ internal StaticTree stat_desc; // the corresponding static tree
+
+ // Compute the optimal bit lengths for a tree and update the total bit length
+ // for the current block.
+ // IN assertion: the fields freq and dad are set, heap[heap_max] and
+ // above are the tree nodes sorted by increasing frequency.
+ // OUT assertions: the field len is set to the optimal bit length, the
+ // array bl_count contains the frequencies for each bit length.
+ // The length opt_len is updated; static_len is also updated if stree is
+ // not null.
+ internal void gen_bitlen(Deflate s){
+ short[] tree = dyn_tree;
+ short[] stree = stat_desc.static_tree;
+ int[] extra = stat_desc.extra_bits;
+ int based = stat_desc.extra_base;
+ int max_length = stat_desc.max_length;
+ int h; // heap index
+ int n, m; // iterate over the tree elements
+ int bits; // bit length
+ int xbits; // extra bits
+ short f; // frequency
+ int overflow = 0; // number of elements with bit length too large
+
+ for (bits = 0; bits <= MAX_BITS; bits++) s.bl_count[bits] = 0;
+
+ // In a first pass, compute the optimal bit lengths (which may
+ // overflow in the case of the bit length tree).
+ tree[s.heap[s.heap_max]*2+1] = 0; // root of the heap
+
+ for(h=s.heap_max+1; h max_length){ bits = max_length; overflow++; }
+ tree[n*2+1] = (short)bits;
+ // We overwrite tree[n*2+1] which is no longer needed
+
+ if (n > max_code) continue; // not a leaf node
+
+ s.bl_count[bits]++;
+ xbits = 0;
+ if (n >= based) xbits = extra[n-based];
+ f = tree[n*2];
+ s.opt_len += f * (bits + xbits);
+ if (stree!=null) s.static_len += f * (stree[n*2+1] + xbits);
+ }
+ if (overflow == 0) return;
+
+ // This happens for example on obj2 and pic of the Calgary corpus
+ // Find the first bit length which could increase:
+ do {
+ bits = max_length-1;
+ while(s.bl_count[bits]==0) bits--;
+ s.bl_count[bits]--; // move one leaf down the tree
+ s.bl_count[bits+1]+=2; // move one overflow item as its brother
+ s.bl_count[max_length]--;
+ // The brother of the overflow item also moves one step up,
+ // but this does not affect bl_count[max_length]
+ overflow -= 2;
+ }
+ while (overflow > 0);
+
+ for (bits = max_length; bits != 0; bits--) {
+ n = s.bl_count[bits];
+ while (n != 0) {
+ m = s.heap[--h];
+ if (m > max_code) continue;
+ if (tree[m*2+1] != bits) {
+ s.opt_len += (int)(((long)bits - (long)tree[m*2+1])*(long)tree[m*2]);
+ tree[m*2+1] = (short)bits;
+ }
+ n--;
+ }
+ }
+ }
+
+ // Construct one Huffman tree and assigns the code bit strings and lengths.
+ // Update the total bit length for the current block.
+ // IN assertion: the field freq is set for all tree elements.
+ // OUT assertions: the fields len and code are set to the optimal bit length
+ // and corresponding code. The length opt_len is updated; static_len is
+ // also updated if stree is not null. The field max_code is set.
+ internal void build_tree(Deflate s){
+ short[] tree=dyn_tree;
+ short[] stree=stat_desc.static_tree;
+ int elems=stat_desc.elems;
+ int n, m; // iterate over heap elements
+ int max_code=-1; // largest code with non zero frequency
+ int node; // new node being created
+
+ // Construct the initial heap, with least frequent element in
+ // heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
+ // heap[0] is not used.
+ s.heap_len = 0;
+ s.heap_max = HEAP_SIZE;
+
+ for(n=0; n=1; n--)
+ s.pqdownheap(tree, n);
+
+ // Construct the Huffman tree by repeatedly combining the least two
+ // frequent nodes.
+
+ node=elems; // next internal node of the tree
+ do{
+ // n = node of least frequency
+ n=s.heap[1];
+ s.heap[1]=s.heap[s.heap_len--];
+ s.pqdownheap(tree, 1);
+ m=s.heap[1]; // m = node of next least frequency
+
+ s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
+ s.heap[--s.heap_max] = m;
+
+ // Create a new node father of n and m
+ tree[node*2] = (short)(tree[n*2] + tree[m*2]);
+ s.depth[node] = (byte)(System.Math.Max(s.depth[n],s.depth[m])+1);
+ tree[n*2+1] = tree[m*2+1] = (short)node;
+
+ // and insert the new node in the heap
+ s.heap[1] = node++;
+ s.pqdownheap(tree, 1);
+ }
+ while(s.heap_len>=2);
+
+ s.heap[--s.heap_max] = s.heap[1];
+
+ // At this point, the fields freq and dad are set. We can now
+ // generate the bit lengths.
+
+ gen_bitlen(s);
+
+ // The field len is now set, we can generate the bit codes
+ gen_codes(tree, max_code, s.bl_count);
+ }
+
+ // Generate the codes for a given tree and bit counts (which need not be
+ // optimal).
+ // IN assertion: the array bl_count contains the bit length statistics for
+ // the given tree and the field len is set for all tree elements.
+ // OUT assertion: the field code is set for all tree elements of non
+ // zero code length.
+ internal static void gen_codes(short[] tree, // the tree to decorate
+ int max_code, // largest code with non zero frequency
+ short[] bl_count // number of codes at each bit length
+ ){
+ short[] next_code=new short[MAX_BITS+1]; // next code value for each bit length
+ short code = 0; // running code value
+ int bits; // bit index
+ int n; // code index
+
+ // The distribution counts are first used to generate the code values
+ // without bit reversal.
+ for (bits = 1; bits <= MAX_BITS; bits++) {
+ next_code[bits] = code = (short)((code + bl_count[bits-1]) << 1);
+ }
+
+ // Check that the bit counts in bl_count are consistent. The last code
+ // must be all ones.
+ //Assert (code + bl_count[MAX_BITS]-1 == (1<>=1;
+ res<<=1;
+ }
+ while(--len>0);
+ return res>>1;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/ZTree.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/ZTree.cs.meta
new file mode 100644
index 00000000..d919e1d2
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/util/zlib/ZTree.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: b6b33c17bec77554891e8c5d75de87d2
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509.meta
new file mode 100644
index 00000000..1b5af611
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: c54419453e5665246b78dd2cc005e17a
+folderAsset: yes
+DefaultImporter:
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/AttributeCertificateHolder.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/AttributeCertificateHolder.cs
new file mode 100644
index 00000000..122b6a88
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/AttributeCertificateHolder.cs
@@ -0,0 +1,446 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509
+{
+ ///
+ /// The Holder object.
+ ///
+ /// Holder ::= SEQUENCE {
+ /// baseCertificateID [0] IssuerSerial OPTIONAL,
+ /// -- the issuer and serial number of
+ /// -- the holder's Public Key Certificate
+ /// entityName [1] GeneralNames OPTIONAL,
+ /// -- the name of the claimant or role
+ /// objectDigestInfo [2] ObjectDigestInfo OPTIONAL
+ /// -- used to directly authenticate the holder,
+ /// -- for example, an executable
+ /// }
+ ///
+ ///
+ public class AttributeCertificateHolder
+ //: CertSelector, Selector
+ : IX509Selector
+ {
+ internal readonly Holder holder;
+
+ internal AttributeCertificateHolder(
+ Asn1Sequence seq)
+ {
+ holder = Holder.GetInstance(seq);
+ }
+
+ public AttributeCertificateHolder(
+ X509Name issuerName,
+ BigInteger serialNumber)
+ {
+ holder = new Holder(
+ new IssuerSerial(
+ GenerateGeneralNames(issuerName),
+ new DerInteger(serialNumber)));
+ }
+
+ public AttributeCertificateHolder(
+ X509Certificate cert)
+ {
+ X509Name name;
+ try
+ {
+ name = PrincipalUtilities.GetIssuerX509Principal(cert);
+ }
+ catch (Exception e)
+ {
+ throw new CertificateParsingException(e.Message);
+ }
+
+ holder = new Holder(new IssuerSerial(GenerateGeneralNames(name), new DerInteger(cert.SerialNumber)));
+ }
+
+ public AttributeCertificateHolder(
+ X509Name principal)
+ {
+ holder = new Holder(GenerateGeneralNames(principal));
+ }
+
+ /**
+ * Constructs a holder for v2 attribute certificates with a hash value for
+ * some type of object.
+ *
+ * digestedObjectType can be one of the following:
+ *
+ *
0 - publicKey - A hash of the public key of the holder must be
+ * passed.
+ *
1 - publicKeyCert - A hash of the public key certificate of the
+ * holder must be passed.
+ *
2 - otherObjectDigest - A hash of some other object type must be
+ * passed. otherObjectTypeID must not be empty.
+ *
+ *
+ *
This cannot be used if a v1 attribute certificate is used.
+ *
+ * @param digestedObjectType The digest object type.
+ * @param digestAlgorithm The algorithm identifier for the hash.
+ * @param otherObjectTypeID The object type ID if
+ * digestedObjectType is
+ * otherObjectDigest.
+ * @param objectDigest The hash value.
+ */
+ public AttributeCertificateHolder(
+ int digestedObjectType,
+ string digestAlgorithm,
+ string otherObjectTypeID,
+ byte[] objectDigest)
+ {
+ // TODO Allow 'objectDigest' to be null?
+
+ holder = new Holder(new ObjectDigestInfo(digestedObjectType, otherObjectTypeID,
+ new AlgorithmIdentifier(new DerObjectIdentifier(digestAlgorithm)), Arrays.Clone(objectDigest)));
+ }
+
+ /**
+ * Returns the digest object type if an object digest info is used.
+ *
+ *
+ *
0 - publicKey - A hash of the public key of the holder must be
+ * passed.
+ *
1 - publicKeyCert - A hash of the public key certificate of the
+ * holder must be passed.
+ *
2 - otherObjectDigest - A hash of some other object type must be
+ * passed. otherObjectTypeID must not be empty.
+ *
+ *
+ *
+ * @return The digest object type or -1 if no object digest info is set.
+ */
+ public int DigestedObjectType
+ {
+ get
+ {
+ ObjectDigestInfo odi = holder.ObjectDigestInfo;
+
+ return odi == null
+ ? -1
+ : odi.DigestedObjectType.Value.IntValue;
+ }
+ }
+
+ /**
+ * Returns the other object type ID if an object digest info is used.
+ *
+ * @return The other object type ID or null if no object
+ * digest info is set.
+ */
+ public string DigestAlgorithm
+ {
+ get
+ {
+ ObjectDigestInfo odi = holder.ObjectDigestInfo;
+
+ return odi == null
+ ? null
+ : odi.DigestAlgorithm.Algorithm.Id;
+ }
+ }
+
+ /**
+ * Returns the hash if an object digest info is used.
+ *
+ * @return The hash or null if no object digest info is set.
+ */
+ public byte[] GetObjectDigest()
+ {
+ ObjectDigestInfo odi = holder.ObjectDigestInfo;
+
+ return odi == null
+ ? null
+ : odi.ObjectDigest.GetBytes();
+ }
+
+ /**
+ * Returns the digest algorithm ID if an object digest info is used.
+ *
+ * @return The digest algorithm ID or null if no object
+ * digest info is set.
+ */
+ public string OtherObjectTypeID
+ {
+ get
+ {
+ ObjectDigestInfo odi = holder.ObjectDigestInfo;
+
+ return odi == null
+ ? null
+ : odi.OtherObjectTypeID.Id;
+ }
+ }
+
+ private GeneralNames GenerateGeneralNames(
+ X509Name principal)
+ {
+// return GeneralNames.GetInstance(new DerSequence(new GeneralName(principal)));
+ return new GeneralNames(new GeneralName(principal));
+ }
+
+ private bool MatchesDN(
+ X509Name subject,
+ GeneralNames targets)
+ {
+ GeneralName[] names = targets.GetNames();
+
+ for (int i = 0; i != names.Length; i++)
+ {
+ GeneralName gn = names[i];
+
+ if (gn.TagNo == GeneralName.DirectoryName)
+ {
+ try
+ {
+ if (X509Name.GetInstance(gn.Name).Equivalent(subject))
+ {
+ return true;
+ }
+ }
+ catch (Exception)
+ {
+ }
+ }
+ }
+
+ return false;
+ }
+
+ private object[] GetNames(
+ GeneralName[] names)
+ {
+ int count = 0;
+ for (int i = 0; i != names.Length; i++)
+ {
+ if (names[i].TagNo == GeneralName.DirectoryName)
+ {
+ ++count;
+ }
+ }
+
+ object[] result = new object[count];
+
+ int pos = 0;
+ for (int i = 0; i != names.Length; i++)
+ {
+ if (names[i].TagNo == GeneralName.DirectoryName)
+ {
+ result[pos++] = X509Name.GetInstance(names[i].Name);
+ }
+ }
+
+ return result;
+ }
+
+ private X509Name[] GetPrincipals(
+ GeneralNames names)
+ {
+ object[] p = this.GetNames(names.GetNames());
+
+ int count = 0;
+
+ for (int i = 0; i != p.Length; i++)
+ {
+ if (p[i] is X509Name)
+ {
+ ++count;
+ }
+ }
+
+ X509Name[] result = new X509Name[count];
+
+ int pos = 0;
+ for (int i = 0; i != p.Length; i++)
+ {
+ if (p[i] is X509Name)
+ {
+ result[pos++] = (X509Name)p[i];
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * Return any principal objects inside the attribute certificate holder entity names field.
+ *
+ * @return an array of IPrincipal objects (usually X509Name), null if no entity names field is set.
+ */
+ public X509Name[] GetEntityNames()
+ {
+ if (holder.EntityName != null)
+ {
+ return GetPrincipals(holder.EntityName);
+ }
+
+ return null;
+ }
+
+ /**
+ * Return the principals associated with the issuer attached to this holder
+ *
+ * @return an array of principals, null if no BaseCertificateID is set.
+ */
+ public X509Name[] GetIssuer()
+ {
+ if (holder.BaseCertificateID != null)
+ {
+ return GetPrincipals(holder.BaseCertificateID.Issuer);
+ }
+
+ return null;
+ }
+
+ /**
+ * Return the serial number associated with the issuer attached to this holder.
+ *
+ * @return the certificate serial number, null if no BaseCertificateID is set.
+ */
+ public BigInteger SerialNumber
+ {
+ get
+ {
+ if (holder.BaseCertificateID != null)
+ {
+ return holder.BaseCertificateID.Serial.Value;
+ }
+
+ return null;
+ }
+ }
+
+ public object Clone()
+ {
+ return new AttributeCertificateHolder((Asn1Sequence)holder.ToAsn1Object());
+ }
+
+ public bool Match(
+// Certificate cert)
+ X509Certificate x509Cert)
+ {
+// if (!(cert is X509Certificate))
+// {
+// return false;
+// }
+//
+// X509Certificate x509Cert = (X509Certificate)cert;
+
+ try
+ {
+ if (holder.BaseCertificateID != null)
+ {
+ return holder.BaseCertificateID.Serial.Value.Equals(x509Cert.SerialNumber)
+ && MatchesDN(PrincipalUtilities.GetIssuerX509Principal(x509Cert), holder.BaseCertificateID.Issuer);
+ }
+
+ if (holder.EntityName != null)
+ {
+ if (MatchesDN(PrincipalUtilities.GetSubjectX509Principal(x509Cert), holder.EntityName))
+ {
+ return true;
+ }
+ }
+
+ if (holder.ObjectDigestInfo != null)
+ {
+ IDigest md = null;
+ try
+ {
+ md = DigestUtilities.GetDigest(DigestAlgorithm);
+ }
+ catch (Exception)
+ {
+ return false;
+ }
+
+ switch (DigestedObjectType)
+ {
+ case ObjectDigestInfo.PublicKey:
+ {
+ // TODO: DSA Dss-parms
+
+ //byte[] b = x509Cert.GetPublicKey().getEncoded();
+ // TODO Is this the right way to encode?
+ byte[] b = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(
+ x509Cert.GetPublicKey()).GetEncoded();
+ md.BlockUpdate(b, 0, b.Length);
+ break;
+ }
+
+ case ObjectDigestInfo.PublicKeyCert:
+ {
+ byte[] b = x509Cert.GetEncoded();
+ md.BlockUpdate(b, 0, b.Length);
+ break;
+ }
+
+ // TODO Default handler?
+ }
+
+ // TODO Shouldn't this be the other way around?
+ if (!Arrays.AreEqual(DigestUtilities.DoFinal(md), GetObjectDigest()))
+ {
+ return false;
+ }
+ }
+ }
+ catch (CertificateEncodingException)
+ {
+ return false;
+ }
+
+ return false;
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ {
+ return true;
+ }
+
+ if (!(obj is AttributeCertificateHolder))
+ {
+ return false;
+ }
+
+ AttributeCertificateHolder other = (AttributeCertificateHolder)obj;
+
+ return this.holder.Equals(other.holder);
+ }
+
+ public override int GetHashCode()
+ {
+ return this.holder.GetHashCode();
+ }
+
+ public bool Match(
+ object obj)
+ {
+ if (!(obj is X509Certificate))
+ {
+ return false;
+ }
+
+// return Match((Certificate)obj);
+ return Match((X509Certificate)obj);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/AttributeCertificateHolder.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/AttributeCertificateHolder.cs.meta
new file mode 100644
index 00000000..4317107f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/AttributeCertificateHolder.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 938387042cf639245ad61e6176058eca
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/AttributeCertificateIssuer.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/AttributeCertificateIssuer.cs
new file mode 100644
index 00000000..26d4b0d7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/AttributeCertificateIssuer.cs
@@ -0,0 +1,203 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509
+{
+ /**
+ * Carrying class for an attribute certificate issuer.
+ */
+ public class AttributeCertificateIssuer
+ //: CertSelector, Selector
+ : IX509Selector
+ {
+ internal readonly Asn1Encodable form;
+
+ /**
+ * Set the issuer directly with the ASN.1 structure.
+ *
+ * @param issuer The issuer
+ */
+ public AttributeCertificateIssuer(
+ AttCertIssuer issuer)
+ {
+ form = issuer.Issuer;
+ }
+
+ public AttributeCertificateIssuer(
+ X509Name principal)
+ {
+// form = new V2Form(GeneralNames.GetInstance(new DerSequence(new GeneralName(principal))));
+ form = new V2Form(new GeneralNames(new GeneralName(principal)));
+ }
+
+ private object[] GetNames()
+ {
+ GeneralNames name;
+ if (form is V2Form)
+ {
+ name = ((V2Form)form).IssuerName;
+ }
+ else
+ {
+ name = (GeneralNames)form;
+ }
+
+ GeneralName[] names = name.GetNames();
+
+ int count = 0;
+ for (int i = 0; i != names.Length; i++)
+ {
+ if (names[i].TagNo == GeneralName.DirectoryName)
+ {
+ ++count;
+ }
+ }
+
+ object[] result = new object[count];
+
+ int pos = 0;
+ for (int i = 0; i != names.Length; i++)
+ {
+ if (names[i].TagNo == GeneralName.DirectoryName)
+ {
+ result[pos++] = X509Name.GetInstance(names[i].Name);
+ }
+ }
+
+ return result;
+ }
+
+ /// Return any principal objects inside the attribute certificate issuer object.
+ /// An array of IPrincipal objects (usually X509Principal).
+ public X509Name[] GetPrincipals()
+ {
+ object[] p = this.GetNames();
+
+ int count = 0;
+ for (int i = 0; i != p.Length; i++)
+ {
+ if (p[i] is X509Name)
+ {
+ ++count;
+ }
+ }
+
+ X509Name[] result = new X509Name[count];
+
+ int pos = 0;
+ for (int i = 0; i != p.Length; i++)
+ {
+ if (p[i] is X509Name)
+ {
+ result[pos++] = (X509Name)p[i];
+ }
+ }
+
+ return result;
+ }
+
+ private bool MatchesDN(
+ X509Name subject,
+ GeneralNames targets)
+ {
+ GeneralName[] names = targets.GetNames();
+
+ for (int i = 0; i != names.Length; i++)
+ {
+ GeneralName gn = names[i];
+
+ if (gn.TagNo == GeneralName.DirectoryName)
+ {
+ try
+ {
+ if (X509Name.GetInstance(gn.Name).Equivalent(subject))
+ {
+ return true;
+ }
+ }
+ catch (Exception)
+ {
+ }
+ }
+ }
+
+ return false;
+ }
+
+ public object Clone()
+ {
+ return new AttributeCertificateIssuer(AttCertIssuer.GetInstance(form));
+ }
+
+ public bool Match(
+// Certificate cert)
+ X509Certificate x509Cert)
+ {
+// if (!(cert is X509Certificate))
+// {
+// return false;
+// }
+//
+// X509Certificate x509Cert = (X509Certificate)cert;
+
+ if (form is V2Form)
+ {
+ V2Form issuer = (V2Form) form;
+ if (issuer.BaseCertificateID != null)
+ {
+ return issuer.BaseCertificateID.Serial.Value.Equals(x509Cert.SerialNumber)
+ && MatchesDN(x509Cert.IssuerDN, issuer.BaseCertificateID.Issuer);
+ }
+
+ return MatchesDN(x509Cert.SubjectDN, issuer.IssuerName);
+ }
+
+ return MatchesDN(x509Cert.SubjectDN, (GeneralNames) form);
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ {
+ return true;
+ }
+
+ if (!(obj is AttributeCertificateIssuer))
+ {
+ return false;
+ }
+
+ AttributeCertificateIssuer other = (AttributeCertificateIssuer)obj;
+
+ return this.form.Equals(other.form);
+ }
+
+ public override int GetHashCode()
+ {
+ return this.form.GetHashCode();
+ }
+
+ public bool Match(
+ object obj)
+ {
+ if (!(obj is X509Certificate))
+ {
+ return false;
+ }
+
+ //return Match((Certificate)obj);
+ return Match((X509Certificate)obj);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/AttributeCertificateIssuer.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/AttributeCertificateIssuer.cs.meta
new file mode 100644
index 00000000..ed5fc272
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/AttributeCertificateIssuer.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: acf2171ca98d9a84b9b2f630c3ed992f
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/IX509AttributeCertificate.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/IX509AttributeCertificate.cs
new file mode 100644
index 00000000..119e1d94
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/IX509AttributeCertificate.cs
@@ -0,0 +1,61 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509
+{
+ /// Interface for an X.509 Attribute Certificate.
+ public interface IX509AttributeCertificate
+ : IX509Extension
+ {
+ /// The version number for the certificate.
+ int Version { get; }
+
+ /// The serial number for the certificate.
+ BigInteger SerialNumber { get; }
+
+ /// The UTC DateTime before which the certificate is not valid.
+ DateTime NotBefore { get; }
+
+ /// The UTC DateTime after which the certificate is not valid.
+ DateTime NotAfter { get; }
+
+ /// The holder of the certificate.
+ AttributeCertificateHolder Holder { get; }
+
+ /// The issuer details for the certificate.
+ AttributeCertificateIssuer Issuer { get; }
+
+ /// Return the attributes contained in the attribute block in the certificate.
+ /// An array of attributes.
+ X509Attribute[] GetAttributes();
+
+ /// Return the attributes with the same type as the passed in oid.
+ /// The object identifier we wish to match.
+ /// An array of matched attributes, null if there is no match.
+ X509Attribute[] GetAttributes(string oid);
+
+ bool[] GetIssuerUniqueID();
+
+ bool IsValidNow { get; }
+ bool IsValid(DateTime date);
+
+ void CheckValidity();
+ void CheckValidity(DateTime date);
+
+ byte[] GetSignature();
+
+ void Verify(AsymmetricKeyParameter publicKey);
+
+ /// Return an ASN.1 encoded byte array representing the attribute certificate.
+ /// An ASN.1 encoded byte array.
+ /// If the certificate cannot be encoded.
+ byte[] GetEncoded();
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/IX509AttributeCertificate.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/IX509AttributeCertificate.cs.meta
new file mode 100644
index 00000000..c3a5e96d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/IX509AttributeCertificate.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 3760a7b484ecf0240b37666571cfc6a4
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/IX509Extension.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/IX509Extension.cs
new file mode 100644
index 00000000..1e3ab12c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/IX509Extension.cs
@@ -0,0 +1,31 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509
+{
+ public interface IX509Extension
+ {
+ ///
+ /// Get all critical extension values, by oid
+ ///
+ /// IDictionary with string (OID) keys and Asn1OctetString values
+ ISet GetCriticalExtensionOids();
+
+ ///
+ /// Get all non-critical extension values, by oid
+ ///
+ /// IDictionary with string (OID) keys and Asn1OctetString values
+ ISet GetNonCriticalExtensionOids();
+
+ [Obsolete("Use version taking a DerObjectIdentifier instead")]
+ Asn1OctetString GetExtensionValue(string oid);
+
+ Asn1OctetString GetExtensionValue(DerObjectIdentifier oid);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/IX509Extension.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/IX509Extension.cs.meta
new file mode 100644
index 00000000..3d5a21b7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/IX509Extension.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 8a0d122875ecdab4796b2617ab2d97eb
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/PEMParser.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/PEMParser.cs
new file mode 100644
index 00000000..7d41b694
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/PEMParser.cs
@@ -0,0 +1,99 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509
+{
+ class PemParser
+ {
+ private readonly string _header1;
+ private readonly string _header2;
+ private readonly string _footer1;
+ private readonly string _footer2;
+
+ internal PemParser(
+ string type)
+ {
+ _header1 = "-----BEGIN " + type + "-----";
+ _header2 = "-----BEGIN X509 " + type + "-----";
+ _footer1 = "-----END " + type + "-----";
+ _footer2 = "-----END X509 " + type + "-----";
+ }
+
+ private string ReadLine(
+ Stream inStream)
+ {
+ int c;
+ StringBuilder l = new StringBuilder();
+
+ do
+ {
+ while (((c = inStream.ReadByte()) != '\r') && c != '\n' && (c >= 0))
+ {
+ if (c == '\r')
+ {
+ continue;
+ }
+
+ l.Append((char)c);
+ }
+ }
+ while (c >= 0 && l.Length == 0);
+
+ if (c < 0)
+ {
+ return null;
+ }
+
+ return l.ToString();
+ }
+
+ internal Asn1Sequence ReadPemObject(
+ Stream inStream)
+ {
+ string line;
+ StringBuilder pemBuf = new StringBuilder();
+
+ while ((line = ReadLine(inStream)) != null)
+ {
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(line, _header1) || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(line, _header2))
+ {
+ break;
+ }
+ }
+
+ while ((line = ReadLine(inStream)) != null)
+ {
+ if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(line, _footer1) || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(line, _footer2))
+ {
+ break;
+ }
+
+ pemBuf.Append(line);
+ }
+
+ if (pemBuf.Length != 0)
+ {
+ Asn1Object o = Asn1Object.FromByteArray(Base64.Decode(pemBuf.ToString()));
+
+ if (!(o is Asn1Sequence))
+ {
+ throw new IOException("malformed PEM data encountered");
+ }
+
+ return (Asn1Sequence) o;
+ }
+
+ return null;
+ }
+ }
+}
+
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/PEMParser.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/PEMParser.cs.meta
new file mode 100644
index 00000000..5a347ec6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/PEMParser.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 6c0af44d6133b484fad764d838af9600
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/PrincipalUtil.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/PrincipalUtil.cs
new file mode 100644
index 00000000..674e548a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/PrincipalUtil.cs
@@ -0,0 +1,74 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509
+{
+ ///
+ /// A utility class that will extract X509Principal objects from X.509 certificates.
+ ///
+ /// Use this in preference to trying to recreate a principal from a string, not all
+ /// DNs are what they should be, so it's best to leave them encoded where they
+ /// can be.
+ ///
+ public class PrincipalUtilities
+ {
+ /// Return the issuer of the given cert as an X509Principal.
+ public static X509Name GetIssuerX509Principal(
+ X509Certificate cert)
+ {
+ try
+ {
+ TbsCertificateStructure tbsCert = TbsCertificateStructure.GetInstance(
+ Asn1Object.FromByteArray(cert.GetTbsCertificate()));
+
+ return tbsCert.Issuer;
+ }
+ catch (Exception e)
+ {
+ throw new CertificateEncodingException("Could not extract issuer", e);
+ }
+ }
+
+ /// Return the subject of the given cert as an X509Principal.
+ public static X509Name GetSubjectX509Principal(
+ X509Certificate cert)
+ {
+ try
+ {
+ TbsCertificateStructure tbsCert = TbsCertificateStructure.GetInstance(
+ Asn1Object.FromByteArray(cert.GetTbsCertificate()));
+
+ return tbsCert.Subject;
+ }
+ catch (Exception e)
+ {
+ throw new CertificateEncodingException("Could not extract subject", e);
+ }
+ }
+
+ /// Return the issuer of the given CRL as an X509Principal.
+ public static X509Name GetIssuerX509Principal(
+ X509Crl crl)
+ {
+ try
+ {
+ TbsCertificateList tbsCertList = TbsCertificateList.GetInstance(
+ Asn1Object.FromByteArray(crl.GetTbsCertList()));
+
+ return tbsCertList.Issuer;
+ }
+ catch (Exception e)
+ {
+ throw new CrlException("Could not extract issuer", e);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/PrincipalUtil.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/PrincipalUtil.cs.meta
new file mode 100644
index 00000000..62598112
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/PrincipalUtil.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: afc0a35c1a82d7047807b55049604a40
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/SubjectPublicKeyInfoFactory.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/SubjectPublicKeyInfoFactory.cs
new file mode 100644
index 00000000..75d5f379
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/SubjectPublicKeyInfoFactory.cs
@@ -0,0 +1,217 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.EdEC;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Oiw;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509
+{
+ ///
+ /// A factory to produce Public Key Info Objects.
+ ///
+ public sealed class SubjectPublicKeyInfoFactory
+ {
+ private SubjectPublicKeyInfoFactory()
+ {
+ }
+
+ ///
+ /// Create a Subject Public Key Info object for a given public key.
+ ///
+ /// One of ElGammalPublicKeyParameters, DSAPublicKeyParameter, DHPublicKeyParameters, RsaKeyParameters or ECPublicKeyParameters
+ /// A subject public key info object.
+ /// Throw exception if object provided is not one of the above.
+ public static SubjectPublicKeyInfo CreateSubjectPublicKeyInfo(
+ AsymmetricKeyParameter publicKey)
+ {
+ if (publicKey == null)
+ throw new ArgumentNullException("publicKey");
+ if (publicKey.IsPrivate)
+ throw new ArgumentException("Private key passed - public key expected.", "publicKey");
+
+ if (publicKey is ElGamalPublicKeyParameters)
+ {
+ ElGamalPublicKeyParameters _key = (ElGamalPublicKeyParameters)publicKey;
+ ElGamalParameters kp = _key.Parameters;
+
+ SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
+ new AlgorithmIdentifier(
+ OiwObjectIdentifiers.ElGamalAlgorithm,
+ new ElGamalParameter(kp.P, kp.G).ToAsn1Object()),
+ new DerInteger(_key.Y));
+
+ return info;
+ }
+
+ if (publicKey is DsaPublicKeyParameters)
+ {
+ DsaPublicKeyParameters _key = (DsaPublicKeyParameters) publicKey;
+ DsaParameters kp = _key.Parameters;
+ Asn1Encodable ae = kp == null
+ ? null
+ : new DsaParameter(kp.P, kp.Q, kp.G).ToAsn1Object();
+
+ return new SubjectPublicKeyInfo(
+ new AlgorithmIdentifier(X9ObjectIdentifiers.IdDsa, ae),
+ new DerInteger(_key.Y));
+ }
+
+ if (publicKey is DHPublicKeyParameters)
+ {
+ DHPublicKeyParameters _key = (DHPublicKeyParameters) publicKey;
+ DHParameters kp = _key.Parameters;
+
+ SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
+ new AlgorithmIdentifier(
+ _key.AlgorithmOid,
+ new DHParameter(kp.P, kp.G, kp.L).ToAsn1Object()),
+ new DerInteger(_key.Y));
+
+ return info;
+ } // End of DH
+
+ if (publicKey is RsaKeyParameters)
+ {
+ RsaKeyParameters _key = (RsaKeyParameters) publicKey;
+
+ SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
+ new AlgorithmIdentifier(PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance),
+ new RsaPublicKeyStructure(_key.Modulus, _key.Exponent).ToAsn1Object());
+
+ return info;
+ } // End of RSA.
+
+ if (publicKey is ECPublicKeyParameters)
+ {
+ ECPublicKeyParameters _key = (ECPublicKeyParameters) publicKey;
+
+ if (_key.AlgorithmName == "ECGOST3410")
+ {
+ if (_key.PublicKeyParamSet == null)
+ throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("Not a CryptoPro parameter set");
+
+ ECPoint q = _key.Q.Normalize();
+ BigInteger bX = q.AffineXCoord.ToBigInteger();
+ BigInteger bY = q.AffineYCoord.ToBigInteger();
+
+ byte[] encKey = new byte[64];
+ ExtractBytes(encKey, 0, bX);
+ ExtractBytes(encKey, 32, bY);
+
+ Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
+ _key.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet);
+
+ AlgorithmIdentifier algID = new AlgorithmIdentifier(
+ CryptoProObjectIdentifiers.GostR3410x2001,
+ gostParams.ToAsn1Object());
+
+ return new SubjectPublicKeyInfo(algID, new DerOctetString(encKey));
+ }
+ else
+ {
+ X962Parameters x962;
+ if (_key.PublicKeyParamSet == null)
+ {
+ ECDomainParameters kp = _key.Parameters;
+ X9ECParameters ecP = new X9ECParameters(kp.Curve, kp.G, kp.N, kp.H, kp.GetSeed());
+
+ x962 = new X962Parameters(ecP);
+ }
+ else
+ {
+ x962 = new X962Parameters(_key.PublicKeyParamSet);
+ }
+
+ byte[] pubKey = _key.Q.GetEncoded(false);
+
+ AlgorithmIdentifier algID = new AlgorithmIdentifier(
+ X9ObjectIdentifiers.IdECPublicKey, x962.ToAsn1Object());
+
+ return new SubjectPublicKeyInfo(algID, pubKey);
+ }
+ } // End of EC
+
+ if (publicKey is Gost3410PublicKeyParameters)
+ {
+ Gost3410PublicKeyParameters _key = (Gost3410PublicKeyParameters) publicKey;
+
+ if (_key.PublicKeyParamSet == null)
+ throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("Not a CryptoPro parameter set");
+
+ byte[] keyEnc = _key.Y.ToByteArrayUnsigned();
+ byte[] keyBytes = new byte[keyEnc.Length];
+
+ for (int i = 0; i != keyBytes.Length; i++)
+ {
+ keyBytes[i] = keyEnc[keyEnc.Length - 1 - i]; // must be little endian
+ }
+
+ Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters(
+ _key.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet);
+
+ AlgorithmIdentifier algID = new AlgorithmIdentifier(
+ CryptoProObjectIdentifiers.GostR3410x94,
+ algParams.ToAsn1Object());
+
+ return new SubjectPublicKeyInfo(algID, new DerOctetString(keyBytes));
+ }
+
+ if (publicKey is X448PublicKeyParameters)
+ {
+ X448PublicKeyParameters key = (X448PublicKeyParameters)publicKey;
+
+ return new SubjectPublicKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_X448), key.GetEncoded());
+ }
+
+ if (publicKey is X25519PublicKeyParameters)
+ {
+ X25519PublicKeyParameters key = (X25519PublicKeyParameters)publicKey;
+
+ return new SubjectPublicKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_X25519), key.GetEncoded());
+ }
+
+ if (publicKey is Ed448PublicKeyParameters)
+ {
+ Ed448PublicKeyParameters key = (Ed448PublicKeyParameters)publicKey;
+
+ return new SubjectPublicKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed448), key.GetEncoded());
+ }
+
+ if (publicKey is Ed25519PublicKeyParameters)
+ {
+ Ed25519PublicKeyParameters key = (Ed25519PublicKeyParameters)publicKey;
+
+ return new SubjectPublicKeyInfo(new AlgorithmIdentifier(EdECObjectIdentifiers.id_Ed25519), key.GetEncoded());
+ }
+
+ throw new ArgumentException("Class provided no convertible: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(publicKey));
+ }
+
+ private static void ExtractBytes(
+ byte[] encKey,
+ int offset,
+ BigInteger bI)
+ {
+ byte[] val = bI.ToByteArray();
+ int n = (bI.BitLength + 7) / 8;
+
+ for (int i = 0; i < n; ++i)
+ {
+ encKey[offset + i] = val[val.Length - 1 - i];
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/SubjectPublicKeyInfoFactory.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/SubjectPublicKeyInfoFactory.cs.meta
new file mode 100644
index 00000000..bb896e5d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/SubjectPublicKeyInfoFactory.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: cd36b9e69934c4e4a841a43e6b65c904
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509AttrCertParser.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509AttrCertParser.cs
new file mode 100644
index 00000000..380789fb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509AttrCertParser.cs
@@ -0,0 +1,177 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509
+{
+ public class X509AttrCertParser
+ {
+ private static readonly PemParser PemAttrCertParser = new PemParser("ATTRIBUTE CERTIFICATE");
+
+ private Asn1Set sData;
+ private int sDataObjectCount;
+ private Stream currentStream;
+
+ private IX509AttributeCertificate ReadDerCertificate(
+ Asn1InputStream dIn)
+ {
+ Asn1Sequence seq = (Asn1Sequence)dIn.ReadObject();
+
+ if (seq.Count > 1 && seq[0] is DerObjectIdentifier)
+ {
+ if (seq[0].Equals(PkcsObjectIdentifiers.SignedData))
+ {
+ sData = SignedData.GetInstance(
+ Asn1Sequence.GetInstance((Asn1TaggedObject) seq[1], true)).Certificates;
+
+ return GetCertificate();
+ }
+ }
+
+// return new X509V2AttributeCertificate(seq.getEncoded());
+ return new X509V2AttributeCertificate(AttributeCertificate.GetInstance(seq));
+ }
+
+ private IX509AttributeCertificate GetCertificate()
+ {
+ if (sData != null)
+ {
+ while (sDataObjectCount < sData.Count)
+ {
+ object obj = sData[sDataObjectCount++];
+
+ if (obj is Asn1TaggedObject && ((Asn1TaggedObject)obj).TagNo == 2)
+ {
+ //return new X509V2AttributeCertificate(
+ // Asn1Sequence.GetInstance((Asn1TaggedObject)obj, false).GetEncoded());
+ return new X509V2AttributeCertificate(
+ AttributeCertificate.GetInstance(
+ Asn1Sequence.GetInstance((Asn1TaggedObject)obj, false)));
+ }
+ }
+ }
+
+ return null;
+ }
+
+ private IX509AttributeCertificate ReadPemCertificate(
+ Stream inStream)
+ {
+ Asn1Sequence seq = PemAttrCertParser.ReadPemObject(inStream);
+
+ return seq == null
+ ? null
+ //: new X509V2AttributeCertificate(seq.getEncoded());
+ : new X509V2AttributeCertificate(AttributeCertificate.GetInstance(seq));
+ }
+
+ ///
+ /// Create loading data from byte array.
+ ///
+ ///
+ public IX509AttributeCertificate ReadAttrCert(
+ byte[] input)
+ {
+ return ReadAttrCert(new MemoryStream(input, false));
+ }
+
+ ///
+ /// Create loading data from byte array.
+ ///
+ ///
+ public ICollection ReadAttrCerts(
+ byte[] input)
+ {
+ return ReadAttrCerts(new MemoryStream(input, false));
+ }
+
+ /**
+ * Generates a certificate object and initializes it with the data
+ * read from the input stream inStream.
+ */
+ public IX509AttributeCertificate ReadAttrCert(
+ Stream inStream)
+ {
+ if (inStream == null)
+ throw new ArgumentNullException("inStream");
+ if (!inStream.CanRead)
+ throw new ArgumentException("inStream must be read-able", "inStream");
+
+ if (currentStream == null)
+ {
+ currentStream = inStream;
+ sData = null;
+ sDataObjectCount = 0;
+ }
+ else if (currentStream != inStream) // reset if input stream has changed
+ {
+ currentStream = inStream;
+ sData = null;
+ sDataObjectCount = 0;
+ }
+
+ try
+ {
+ if (sData != null)
+ {
+ if (sDataObjectCount != sData.Count)
+ {
+ return GetCertificate();
+ }
+
+ sData = null;
+ sDataObjectCount = 0;
+ return null;
+ }
+
+ PushbackStream pis = new PushbackStream(inStream);
+ int tag = pis.ReadByte();
+
+ if (tag < 0)
+ return null;
+
+ pis.Unread(tag);
+
+ if (tag != 0x30) // assume ascii PEM encoded.
+ {
+ return ReadPemCertificate(pis);
+ }
+
+ return ReadDerCertificate(new Asn1InputStream(pis));
+ }
+ catch (Exception e)
+ {
+ throw new CertificateException(e.ToString());
+ }
+ }
+
+ /**
+ * Returns a (possibly empty) collection view of the certificates
+ * read from the given input stream inStream.
+ */
+ public ICollection ReadAttrCerts(
+ Stream inStream)
+ {
+ IX509AttributeCertificate attrCert;
+ IList attrCerts = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+
+ while ((attrCert = ReadAttrCert(inStream)) != null)
+ {
+ attrCerts.Add(attrCert);
+ }
+
+ return attrCerts;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509AttrCertParser.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509AttrCertParser.cs.meta
new file mode 100644
index 00000000..0d7b9543
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509AttrCertParser.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: fb17e3130c56fdb44a2169c7946d70f2
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509Attribute.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509Attribute.cs
new file mode 100644
index 00000000..6f9aadba
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509Attribute.cs
@@ -0,0 +1,80 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509
+{
+ /**
+ * Class for carrying the values in an X.509 Attribute.
+ */
+ public class X509Attribute
+ : Asn1Encodable
+ {
+ private readonly AttributeX509 attr;
+
+ /**
+ * @param at an object representing an attribute.
+ */
+ internal X509Attribute(
+ Asn1Encodable at)
+ {
+ this.attr = AttributeX509.GetInstance(at);
+ }
+
+ /**
+ * Create an X.509 Attribute with the type given by the passed in oid and
+ * the value represented by an ASN.1 Set containing value.
+ *
+ * @param oid type of the attribute
+ * @param value value object to go into the atribute's value set.
+ */
+ public X509Attribute(
+ string oid,
+ Asn1Encodable value)
+ {
+ this.attr = new AttributeX509(new DerObjectIdentifier(oid), new DerSet(value));
+ }
+
+ /**
+ * Create an X.59 Attribute with the type given by the passed in oid and the
+ * value represented by an ASN.1 Set containing the objects in value.
+ *
+ * @param oid type of the attribute
+ * @param value vector of values to go in the attribute's value set.
+ */
+ public X509Attribute(
+ string oid,
+ Asn1EncodableVector value)
+ {
+ this.attr = new AttributeX509(new DerObjectIdentifier(oid), new DerSet(value));
+ }
+
+ public string Oid
+ {
+ get { return attr.AttrType.Id; }
+ }
+
+ public Asn1Encodable[] GetValues()
+ {
+ Asn1Set s = attr.AttrValues;
+ Asn1Encodable[] values = new Asn1Encodable[s.Count];
+
+ for (int i = 0; i != s.Count; i++)
+ {
+ values[i] = (Asn1Encodable)s[i];
+ }
+
+ return values;
+ }
+
+ public override Asn1Object ToAsn1Object()
+ {
+ return attr.ToAsn1Object();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509Attribute.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509Attribute.cs.meta
new file mode 100644
index 00000000..33aea968
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509Attribute.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 8689ae3e6241dab498e32e4185da76fc
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CertPairParser.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CertPairParser.cs
new file mode 100644
index 00000000..a73c1089
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CertPairParser.cs
@@ -0,0 +1,99 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509
+{
+ public class X509CertPairParser
+ {
+ private Stream currentStream;
+
+ private X509CertificatePair ReadDerCrossCertificatePair(
+ Stream inStream)
+ {
+ Asn1InputStream dIn = new Asn1InputStream(inStream);//, ProviderUtil.getReadLimit(in));
+ Asn1Sequence seq = (Asn1Sequence)dIn.ReadObject();
+ CertificatePair pair = CertificatePair.GetInstance(seq);
+ return new X509CertificatePair(pair);
+ }
+
+ ///
+ /// Create loading data from byte array.
+ ///
+ ///
+ public X509CertificatePair ReadCertPair(
+ byte[] input)
+ {
+ return ReadCertPair(new MemoryStream(input, false));
+ }
+
+ ///
+ /// Create loading data from byte array.
+ ///
+ ///
+ public ICollection ReadCertPairs(
+ byte[] input)
+ {
+ return ReadCertPairs(new MemoryStream(input, false));
+ }
+
+ public X509CertificatePair ReadCertPair(
+ Stream inStream)
+ {
+ if (inStream == null)
+ throw new ArgumentNullException("inStream");
+ if (!inStream.CanRead)
+ throw new ArgumentException("inStream must be read-able", "inStream");
+
+ if (currentStream == null)
+ {
+ currentStream = inStream;
+ }
+ else if (currentStream != inStream) // reset if input stream has changed
+ {
+ currentStream = inStream;
+ }
+
+ try
+ {
+ PushbackStream pis = new PushbackStream(inStream);
+ int tag = pis.ReadByte();
+
+ if (tag < 0)
+ return null;
+
+ pis.Unread(tag);
+
+ return ReadDerCrossCertificatePair(pis);
+ }
+ catch (Exception e)
+ {
+ throw new CertificateException(e.ToString());
+ }
+ }
+
+ public ICollection ReadCertPairs(
+ Stream inStream)
+ {
+ X509CertificatePair certPair;
+ IList certPairs = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+
+ while ((certPair = ReadCertPair(inStream)) != null)
+ {
+ certPairs.Add(certPair);
+ }
+
+ return certPairs;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CertPairParser.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CertPairParser.cs.meta
new file mode 100644
index 00000000..9b0c612e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CertPairParser.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 8127558424a84ff4b96f41dbcb52b8f7
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509Certificate.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509Certificate.cs
new file mode 100644
index 00000000..75041f85
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509Certificate.cs
@@ -0,0 +1,608 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Misc;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Extension;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Operators;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509
+{
+ ///
+ /// An Object representing an X509 Certificate.
+ /// Has static methods for loading Certificates encoded in many forms that return X509Certificate Objects.
+ ///
+ public class X509Certificate
+ : X509ExtensionBase
+// , PKCS12BagAttributeCarrier
+ {
+ private readonly X509CertificateStructure c;
+// private Hashtable pkcs12Attributes = new Hashtable();
+// private ArrayList pkcs12Ordering = new ArrayList();
+ private readonly BasicConstraints basicConstraints;
+ private readonly bool[] keyUsage;
+
+ private bool hashValueSet;
+ private int hashValue;
+
+ protected X509Certificate()
+ {
+ }
+
+ public X509Certificate(
+ X509CertificateStructure c)
+ {
+ this.c = c;
+
+ try
+ {
+ Asn1OctetString str = this.GetExtensionValue(new DerObjectIdentifier("2.5.29.19"));
+
+ if (str != null)
+ {
+ basicConstraints = BasicConstraints.GetInstance(
+ X509ExtensionUtilities.FromExtensionValue(str));
+ }
+ }
+ catch (Exception e)
+ {
+ throw new CertificateParsingException("cannot construct BasicConstraints: " + e);
+ }
+
+ try
+ {
+ Asn1OctetString str = this.GetExtensionValue(new DerObjectIdentifier("2.5.29.15"));
+
+ if (str != null)
+ {
+ DerBitString bits = DerBitString.GetInstance(
+ X509ExtensionUtilities.FromExtensionValue(str));
+
+ byte[] bytes = bits.GetBytes();
+ int length = (bytes.Length * 8) - bits.PadBits;
+
+ keyUsage = new bool[(length < 9) ? 9 : length];
+
+ for (int i = 0; i != length; i++)
+ {
+// keyUsage[i] = (bytes[i / 8] & (0x80 >>> (i % 8))) != 0;
+ keyUsage[i] = (bytes[i / 8] & (0x80 >> (i % 8))) != 0;
+ }
+ }
+ else
+ {
+ keyUsage = null;
+ }
+ }
+ catch (Exception e)
+ {
+ throw new CertificateParsingException("cannot construct KeyUsage: " + e);
+ }
+ }
+
+// internal X509Certificate(
+// Asn1Sequence seq)
+// {
+// this.c = X509CertificateStructure.GetInstance(seq);
+// }
+
+// ///
+// /// Load certificate from byte array.
+// ///
+// /// Byte array containing encoded X509Certificate.
+// public X509Certificate(
+// byte[] encoded)
+// : this((Asn1Sequence) new Asn1InputStream(encoded).ReadObject())
+// {
+// }
+//
+// ///
+// /// Load certificate from Stream.
+// /// Must be positioned at start of certificate.
+// ///
+// ///
+// public X509Certificate(
+// Stream input)
+// : this((Asn1Sequence) new Asn1InputStream(input).ReadObject())
+// {
+// }
+
+ public virtual X509CertificateStructure CertificateStructure
+ {
+ get { return c; }
+ }
+
+ ///
+ /// Return true if the current time is within the start and end times nominated on the certificate.
+ ///
+ /// true id certificate is valid for the current time.
+ public virtual bool IsValidNow
+ {
+ get { return IsValid(DateTime.UtcNow); }
+ }
+
+ ///
+ /// Return true if the nominated time is within the start and end times nominated on the certificate.
+ ///
+ /// The time to test validity against.
+ /// True if certificate is valid for nominated time.
+ public virtual bool IsValid(
+ DateTime time)
+ {
+ return time.CompareTo(NotBefore) >= 0 && time.CompareTo(NotAfter) <= 0;
+ }
+
+ ///
+ /// Checks if the current date is within certificate's validity period.
+ ///
+ public virtual void CheckValidity()
+ {
+ this.CheckValidity(DateTime.UtcNow);
+ }
+
+ ///
+ /// Checks if the given date is within certificate's validity period.
+ ///
+ /// if the certificate is expired by given date
+ /// if the certificate is not yet valid on given date
+ public virtual void CheckValidity(
+ DateTime time)
+ {
+ if (time.CompareTo(NotAfter) > 0)
+ throw new CertificateExpiredException("certificate expired on " + c.EndDate.GetTime());
+ if (time.CompareTo(NotBefore) < 0)
+ throw new CertificateNotYetValidException("certificate not valid until " + c.StartDate.GetTime());
+ }
+
+ ///
+ /// Return the certificate's version.
+ ///
+ /// An integer whose value Equals the version of the cerficate.
+ public virtual int Version
+ {
+ get { return c.Version; }
+ }
+
+ ///
+ /// Return a BigInteger containing the serial number.
+ ///
+ /// The Serial number.
+ public virtual BigInteger SerialNumber
+ {
+ get { return c.SerialNumber.Value; }
+ }
+
+ ///
+ /// Get the Issuer Distinguished Name. (Who signed the certificate.)
+ ///
+ /// And X509Object containing name and value pairs.
+// public IPrincipal IssuerDN
+ public virtual X509Name IssuerDN
+ {
+ get { return c.Issuer; }
+ }
+
+ ///
+ /// Get the subject of this certificate.
+ ///
+ /// An X509Name object containing name and value pairs.
+// public IPrincipal SubjectDN
+ public virtual X509Name SubjectDN
+ {
+ get { return c.Subject; }
+ }
+
+ ///
+ /// The time that this certificate is valid from.
+ ///
+ /// A DateTime object representing that time in the local time zone.
+ public virtual DateTime NotBefore
+ {
+ get { return c.StartDate.ToDateTime(); }
+ }
+
+ ///
+ /// The time that this certificate is valid up to.
+ ///
+ /// A DateTime object representing that time in the local time zone.
+ public virtual DateTime NotAfter
+ {
+ get { return c.EndDate.ToDateTime(); }
+ }
+
+ ///
+ /// Return the Der encoded TbsCertificate data.
+ /// This is the certificate component less the signature.
+ /// To Get the whole certificate call the GetEncoded() member.
+ ///
+ /// A byte array containing the Der encoded Certificate component.
+ public virtual byte[] GetTbsCertificate()
+ {
+ return c.TbsCertificate.GetDerEncoded();
+ }
+
+ ///
+ /// The signature.
+ ///
+ /// A byte array containg the signature of the certificate.
+ public virtual byte[] GetSignature()
+ {
+ return c.GetSignatureOctets();
+ }
+
+ ///
+ /// A meaningful version of the Signature Algorithm. (EG SHA1WITHRSA)
+ ///
+ /// A sting representing the signature algorithm.
+ public virtual string SigAlgName
+ {
+ get { return SignerUtilities.GetEncodingName(c.SignatureAlgorithm.Algorithm); }
+ }
+
+ ///
+ /// Get the Signature Algorithms Object ID.
+ ///
+ /// A string containg a '.' separated object id.
+ public virtual string SigAlgOid
+ {
+ get { return c.SignatureAlgorithm.Algorithm.Id; }
+ }
+
+ ///
+ /// Get the signature algorithms parameters. (EG DSA Parameters)
+ ///
+ /// A byte array containing the Der encoded version of the parameters or null if there are none.
+ public virtual byte[] GetSigAlgParams()
+ {
+ if (c.SignatureAlgorithm.Parameters != null)
+ {
+ return c.SignatureAlgorithm.Parameters.GetDerEncoded();
+ }
+
+ return null;
+ }
+
+ ///
+ /// Get the issuers UID.
+ ///
+ /// A DerBitString.
+ public virtual DerBitString IssuerUniqueID
+ {
+ get { return c.TbsCertificate.IssuerUniqueID; }
+ }
+
+ ///
+ /// Get the subjects UID.
+ ///
+ /// A DerBitString.
+ public virtual DerBitString SubjectUniqueID
+ {
+ get { return c.TbsCertificate.SubjectUniqueID; }
+ }
+
+ ///
+ /// Get a key usage guidlines.
+ ///
+ public virtual bool[] GetKeyUsage()
+ {
+ return keyUsage == null ? null : (bool[]) keyUsage.Clone();
+ }
+
+ // TODO Replace with something that returns a list of DerObjectIdentifier
+ public virtual IList GetExtendedKeyUsage()
+ {
+ Asn1OctetString str = this.GetExtensionValue(new DerObjectIdentifier("2.5.29.37"));
+
+ if (str == null)
+ return null;
+
+ try
+ {
+ Asn1Sequence seq = Asn1Sequence.GetInstance(
+ X509ExtensionUtilities.FromExtensionValue(str));
+
+ IList list = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+
+ foreach (DerObjectIdentifier oid in seq)
+ {
+ list.Add(oid.Id);
+ }
+
+ return list;
+ }
+ catch (Exception e)
+ {
+ throw new CertificateParsingException("error processing extended key usage extension", e);
+ }
+ }
+
+ public virtual int GetBasicConstraints()
+ {
+ if (basicConstraints != null && basicConstraints.IsCA())
+ {
+ if (basicConstraints.PathLenConstraint == null)
+ {
+ return int.MaxValue;
+ }
+
+ return basicConstraints.PathLenConstraint.IntValue;
+ }
+
+ return -1;
+ }
+
+ public virtual ICollection GetSubjectAlternativeNames()
+ {
+ return GetAlternativeNames("2.5.29.17");
+ }
+
+ public virtual ICollection GetIssuerAlternativeNames()
+ {
+ return GetAlternativeNames("2.5.29.18");
+ }
+
+ protected virtual ICollection GetAlternativeNames(
+ string oid)
+ {
+ Asn1OctetString altNames = GetExtensionValue(new DerObjectIdentifier(oid));
+
+ if (altNames == null)
+ return null;
+
+ Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(altNames);
+
+ GeneralNames gns = GeneralNames.GetInstance(asn1Object);
+
+ IList result = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ foreach (GeneralName gn in gns.GetNames())
+ {
+ IList entry = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ entry.Add(gn.TagNo);
+ entry.Add(gn.Name.ToString());
+ result.Add(entry);
+ }
+ return result;
+ }
+
+ protected override X509Extensions GetX509Extensions()
+ {
+ return c.Version >= 3
+ ? c.TbsCertificate.Extensions
+ : null;
+ }
+
+ ///
+ /// Get the public key of the subject of the certificate.
+ ///
+ /// The public key parameters.
+ public virtual AsymmetricKeyParameter GetPublicKey()
+ {
+ return PublicKeyFactory.CreateKey(c.SubjectPublicKeyInfo);
+ }
+
+ ///
+ /// Return a Der encoded version of this certificate.
+ ///
+ /// A byte array.
+ public virtual byte[] GetEncoded()
+ {
+ return c.GetDerEncoded();
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return true;
+
+ X509Certificate other = obj as X509Certificate;
+
+ if (other == null)
+ return false;
+
+ return c.Equals(other.c);
+
+ // NB: May prefer this implementation of Equals if more than one certificate implementation in play
+// return Arrays.AreEqual(this.GetEncoded(), other.GetEncoded());
+ }
+
+ public override int GetHashCode()
+ {
+ lock (this)
+ {
+ if (!hashValueSet)
+ {
+ hashValue = c.GetHashCode();
+ hashValueSet = true;
+ }
+ }
+
+ return hashValue;
+ }
+
+// public void setBagAttribute(
+// DERObjectIdentifier oid,
+// DEREncodable attribute)
+// {
+// pkcs12Attributes.put(oid, attribute);
+// pkcs12Ordering.addElement(oid);
+// }
+//
+// public DEREncodable getBagAttribute(
+// DERObjectIdentifier oid)
+// {
+// return (DEREncodable)pkcs12Attributes.get(oid);
+// }
+//
+// public Enumeration getBagAttributeKeys()
+// {
+// return pkcs12Ordering.elements();
+// }
+
+ public override string ToString()
+ {
+ StringBuilder buf = new StringBuilder();
+ string nl = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.NewLine;
+
+ buf.Append(" [0] Version: ").Append(this.Version).Append(nl);
+ buf.Append(" SerialNumber: ").Append(this.SerialNumber).Append(nl);
+ buf.Append(" IssuerDN: ").Append(this.IssuerDN).Append(nl);
+ buf.Append(" Start Date: ").Append(this.NotBefore).Append(nl);
+ buf.Append(" Final Date: ").Append(this.NotAfter).Append(nl);
+ buf.Append(" SubjectDN: ").Append(this.SubjectDN).Append(nl);
+ buf.Append(" Public Key: ").Append(this.GetPublicKey()).Append(nl);
+ buf.Append(" Signature Algorithm: ").Append(this.SigAlgName).Append(nl);
+
+ byte[] sig = this.GetSignature();
+ buf.Append(" Signature: ").Append(Hex.ToHexString(sig, 0, 20)).Append(nl);
+
+ for (int i = 20; i < sig.Length; i += 20)
+ {
+ int len = System.Math.Min(20, sig.Length - i);
+ buf.Append(" ").Append(Hex.ToHexString(sig, i, len)).Append(nl);
+ }
+
+ X509Extensions extensions = c.TbsCertificate.Extensions;
+
+ if (extensions != null)
+ {
+ IEnumerator e = extensions.ExtensionOids.GetEnumerator();
+
+ if (e.MoveNext())
+ {
+ buf.Append(" Extensions: \n");
+ }
+
+ do
+ {
+ DerObjectIdentifier oid = (DerObjectIdentifier)e.Current;
+ X509Extension ext = extensions.GetExtension(oid);
+
+ if (ext.Value != null)
+ {
+ byte[] octs = ext.Value.GetOctets();
+ Asn1Object obj = Asn1Object.FromByteArray(octs);
+ buf.Append(" critical(").Append(ext.IsCritical).Append(") ");
+ try
+ {
+ if (oid.Equals(X509Extensions.BasicConstraints))
+ {
+ buf.Append(BasicConstraints.GetInstance(obj));
+ }
+ else if (oid.Equals(X509Extensions.KeyUsage))
+ {
+ buf.Append(KeyUsage.GetInstance(obj));
+ }
+ else if (oid.Equals(MiscObjectIdentifiers.NetscapeCertType))
+ {
+ buf.Append(new NetscapeCertType((DerBitString) obj));
+ }
+ else if (oid.Equals(MiscObjectIdentifiers.NetscapeRevocationUrl))
+ {
+ buf.Append(new NetscapeRevocationUrl((DerIA5String) obj));
+ }
+ else if (oid.Equals(MiscObjectIdentifiers.VerisignCzagExtension))
+ {
+ buf.Append(new VerisignCzagExtension((DerIA5String) obj));
+ }
+ else
+ {
+ buf.Append(oid.Id);
+ buf.Append(" value = ").Append(Asn1Dump.DumpAsString(obj));
+ //buf.Append(" value = ").Append("*****").Append(nl);
+ }
+ }
+ catch (Exception)
+ {
+ buf.Append(oid.Id);
+ //buf.Append(" value = ").Append(new string(Hex.encode(ext.getValue().getOctets()))).Append(nl);
+ buf.Append(" value = ").Append("*****");
+ }
+ }
+
+ buf.Append(nl);
+ }
+ while (e.MoveNext());
+ }
+
+ return buf.ToString();
+ }
+
+ ///
+ /// Verify the certificate's signature using the nominated public key.
+ ///
+ /// An appropriate public key parameter object, RsaPublicKeyParameters, DsaPublicKeyParameters or ECDsaPublicKeyParameters
+ /// True if the signature is valid.
+ /// If key submitted is not of the above nominated types.
+ public virtual void Verify(
+ AsymmetricKeyParameter key)
+ {
+ CheckSignature(new Asn1VerifierFactory(c.SignatureAlgorithm, key));
+ }
+
+ ///
+ /// Verify the certificate's signature using a verifier created using the passed in verifier provider.
+ ///
+ /// An appropriate provider for verifying the certificate's signature.
+ /// True if the signature is valid.
+ /// If verifier provider is not appropriate or the certificate algorithm is invalid.
+ public virtual void Verify(
+ IVerifierFactoryProvider verifierProvider)
+ {
+ CheckSignature(verifierProvider.CreateVerifierFactory (c.SignatureAlgorithm));
+ }
+
+ protected virtual void CheckSignature(
+ IVerifierFactory verifier)
+ {
+ if (!IsAlgIDEqual(c.SignatureAlgorithm, c.TbsCertificate.Signature))
+ throw new CertificateException("signature algorithm in TBS cert not same as outer cert");
+
+ Asn1Encodable parameters = c.SignatureAlgorithm.Parameters;
+
+ IStreamCalculator streamCalculator = verifier.CreateCalculator();
+
+ byte[] b = this.GetTbsCertificate();
+
+ streamCalculator.Stream.Write(b, 0, b.Length);
+
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(streamCalculator.Stream);
+
+ if (!((IVerifier)streamCalculator.GetResult()).IsVerified(this.GetSignature()))
+ {
+ throw new InvalidKeyException("Public key presented not for certificate signature");
+ }
+ }
+
+ private static bool IsAlgIDEqual(AlgorithmIdentifier id1, AlgorithmIdentifier id2)
+ {
+ if (!id1.Algorithm.Equals(id2.Algorithm))
+ return false;
+
+ Asn1Encodable p1 = id1.Parameters;
+ Asn1Encodable p2 = id2.Parameters;
+
+ if ((p1 == null) == (p2 == null))
+ return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(p1, p2);
+
+ // Exactly one of p1, p2 is null at this point
+ return p1 == null
+ ? p2.ToAsn1Object() is Asn1Null
+ : p1.ToAsn1Object() is Asn1Null;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509Certificate.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509Certificate.cs.meta
new file mode 100644
index 00000000..0711150f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509Certificate.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 6beadff9e85279b4e98431dba56a094f
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CertificatePair.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CertificatePair.cs
new file mode 100644
index 00000000..23c5b3c6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CertificatePair.cs
@@ -0,0 +1,127 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509
+{
+ ///
+ /// This class contains a cross certificate pair. Cross certificates pairs may
+ /// contain two cross signed certificates from two CAs. A certificate from the
+ /// other CA to this CA is contained in the forward certificate, the certificate
+ /// from this CA to the other CA is contained in the reverse certificate.
+ ///
+ public class X509CertificatePair
+ {
+ private readonly X509Certificate forward;
+ private readonly X509Certificate reverse;
+
+ /// Constructor
+ /// Certificate from the other CA to this CA.
+ /// Certificate from this CA to the other CA.
+ public X509CertificatePair(
+ X509Certificate forward,
+ X509Certificate reverse)
+ {
+ this.forward = forward;
+ this.reverse = reverse;
+ }
+
+ /// Constructor from a ASN.1 CertificatePair structure.
+ /// The CertificatePair ASN.1 object.
+ public X509CertificatePair(
+ CertificatePair pair)
+ {
+ if (pair.Forward != null)
+ {
+ this.forward = new X509Certificate(pair.Forward);
+ }
+ if (pair.Reverse != null)
+ {
+ this.reverse = new X509Certificate(pair.Reverse);
+ }
+ }
+
+ public byte[] GetEncoded()
+ {
+ try
+ {
+ X509CertificateStructure f = null, r = null;
+
+ if (forward != null)
+ {
+ f = X509CertificateStructure.GetInstance(
+ Asn1Object.FromByteArray(forward.GetEncoded()));
+
+ if (f == null)
+ throw new CertificateEncodingException("unable to get encoding for forward");
+ }
+
+ if (reverse != null)
+ {
+ r = X509CertificateStructure.GetInstance(
+ Asn1Object.FromByteArray(reverse.GetEncoded()));
+
+ if (r == null)
+ throw new CertificateEncodingException("unable to get encoding for reverse");
+ }
+
+ return new CertificatePair(f, r).GetDerEncoded();
+ }
+ catch (Exception e)
+ {
+ // TODO
+// throw new ExtCertificateEncodingException(e.toString(), e);
+ throw new CertificateEncodingException(e.Message, e);
+ }
+ }
+
+ /// Returns the certificate from the other CA to this CA.
+ public X509Certificate Forward
+ {
+ get { return forward; }
+ }
+
+ /// Returns the certificate from this CA to the other CA.
+ public X509Certificate Reverse
+ {
+ get { return reverse; }
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return true;
+
+ X509CertificatePair other = obj as X509CertificatePair;
+
+ if (other == null)
+ return false;
+
+ return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(this.forward, other.forward)
+ && BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(this.reverse, other.reverse);
+ }
+
+ public override int GetHashCode()
+ {
+ int hash = -1;
+ if (forward != null)
+ {
+ hash ^= forward.GetHashCode();
+ }
+ if (reverse != null)
+ {
+ hash *= 17;
+ hash ^= reverse.GetHashCode();
+ }
+ return hash;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CertificatePair.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CertificatePair.cs.meta
new file mode 100644
index 00000000..cd6b3e30
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CertificatePair.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ebb6773b53a2eae45aff0fc7c7f03d8c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CertificateParser.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CertificateParser.cs
new file mode 100644
index 00000000..4863e700
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CertificateParser.cs
@@ -0,0 +1,187 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509
+{
+ /**
+ * class for dealing with X509 certificates.
+ *
+ * At the moment this will deal with "-----BEGIN CERTIFICATE-----" to "-----END CERTIFICATE-----"
+ * base 64 encoded certs, as well as the BER binaries of certificates and some classes of PKCS#7
+ * objects.
+ */
+ public class X509CertificateParser
+ {
+ private static readonly PemParser PemCertParser = new PemParser("CERTIFICATE");
+
+ private Asn1Set sData;
+ private int sDataObjectCount;
+ private Stream currentStream;
+
+ private X509Certificate ReadDerCertificate(
+ Asn1InputStream dIn)
+ {
+ Asn1Sequence seq = (Asn1Sequence)dIn.ReadObject();
+
+ if (seq.Count > 1 && seq[0] is DerObjectIdentifier)
+ {
+ if (seq[0].Equals(PkcsObjectIdentifiers.SignedData))
+ {
+ sData = SignedData.GetInstance(
+ Asn1Sequence.GetInstance((Asn1TaggedObject) seq[1], true)).Certificates;
+
+ return GetCertificate();
+ }
+ }
+
+ return CreateX509Certificate(X509CertificateStructure.GetInstance(seq));
+ }
+
+ private X509Certificate GetCertificate()
+ {
+ if (sData != null)
+ {
+ while (sDataObjectCount < sData.Count)
+ {
+ object obj = sData[sDataObjectCount++];
+
+ if (obj is Asn1Sequence)
+ {
+ return CreateX509Certificate(
+ X509CertificateStructure.GetInstance(obj));
+ }
+ }
+ }
+
+ return null;
+ }
+
+ private X509Certificate ReadPemCertificate(
+ Stream inStream)
+ {
+ Asn1Sequence seq = PemCertParser.ReadPemObject(inStream);
+
+ return seq == null
+ ? null
+ : CreateX509Certificate(X509CertificateStructure.GetInstance(seq));
+ }
+
+ protected virtual X509Certificate CreateX509Certificate(
+ X509CertificateStructure c)
+ {
+ return new X509Certificate(c);
+ }
+
+ ///
+ /// Create loading data from byte array.
+ ///
+ ///
+ public X509Certificate ReadCertificate(
+ byte[] input)
+ {
+ return ReadCertificate(new MemoryStream(input, false));
+ }
+
+ ///
+ /// Create loading data from byte array.
+ ///
+ ///
+ public ICollection ReadCertificates(
+ byte[] input)
+ {
+ return ReadCertificates(new MemoryStream(input, false));
+ }
+
+ /**
+ * Generates a certificate object and initializes it with the data
+ * read from the input stream inStream.
+ */
+ public X509Certificate ReadCertificate(
+ Stream inStream)
+ {
+ if (inStream == null)
+ throw new ArgumentNullException("inStream");
+ if (!inStream.CanRead)
+ throw new ArgumentException("inStream must be read-able", "inStream");
+
+ if (currentStream == null)
+ {
+ currentStream = inStream;
+ sData = null;
+ sDataObjectCount = 0;
+ }
+ else if (currentStream != inStream) // reset if input stream has changed
+ {
+ currentStream = inStream;
+ sData = null;
+ sDataObjectCount = 0;
+ }
+
+ try
+ {
+ if (sData != null)
+ {
+ if (sDataObjectCount != sData.Count)
+ {
+ return GetCertificate();
+ }
+
+ sData = null;
+ sDataObjectCount = 0;
+ return null;
+ }
+
+ PushbackStream pis = new PushbackStream(inStream);
+ int tag = pis.ReadByte();
+
+ if (tag < 0)
+ return null;
+
+ pis.Unread(tag);
+
+ if (tag != 0x30) // assume ascii PEM encoded.
+ {
+ return ReadPemCertificate(pis);
+ }
+
+ return ReadDerCertificate(new Asn1InputStream(pis));
+ }
+ catch (Exception e)
+ {
+ throw new CertificateException("Failed to read certificate", e);
+ }
+ }
+
+ /**
+ * Returns a (possibly empty) collection view of the certificates
+ * read from the given input stream inStream.
+ */
+ public ICollection ReadCertificates(
+ Stream inStream)
+ {
+ X509Certificate cert;
+ IList certs = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+
+ while ((cert = ReadCertificate(inStream)) != null)
+ {
+ certs.Add(cert);
+ }
+
+ return certs;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CertificateParser.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CertificateParser.cs.meta
new file mode 100644
index 00000000..ac6cfc61
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CertificateParser.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: d7c29c36b4684094d864d3cae4db30f7
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509Crl.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509Crl.cs
new file mode 100644
index 00000000..53a49311
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509Crl.cs
@@ -0,0 +1,430 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Date;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Extension;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Operators;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509
+{
+ /**
+ * The following extensions are listed in RFC 2459 as relevant to CRLs
+ *
+ * Authority Key Identifier
+ * Issuer Alternative Name
+ * CRL Number
+ * Delta CRL Indicator (critical)
+ * Issuing Distribution Point (critical)
+ */
+ public class X509Crl
+ : X509ExtensionBase
+ // TODO Add interface Crl?
+ {
+ private readonly CertificateList c;
+ private readonly string sigAlgName;
+ private readonly byte[] sigAlgParams;
+ private readonly bool isIndirect;
+
+ public X509Crl(
+ CertificateList c)
+ {
+ this.c = c;
+
+ try
+ {
+ this.sigAlgName = X509SignatureUtilities.GetSignatureName(c.SignatureAlgorithm);
+
+ if (c.SignatureAlgorithm.Parameters != null)
+ {
+ this.sigAlgParams = ((Asn1Encodable)c.SignatureAlgorithm.Parameters).GetDerEncoded();
+ }
+ else
+ {
+ this.sigAlgParams = null;
+ }
+
+ this.isIndirect = IsIndirectCrl;
+ }
+ catch (Exception e)
+ {
+ throw new CrlException("CRL contents invalid: " + e);
+ }
+ }
+
+ protected override X509Extensions GetX509Extensions()
+ {
+ return c.Version >= 2
+ ? c.TbsCertList.Extensions
+ : null;
+ }
+
+ public virtual byte[] GetEncoded()
+ {
+ try
+ {
+ return c.GetDerEncoded();
+ }
+ catch (Exception e)
+ {
+ throw new CrlException(e.ToString());
+ }
+ }
+
+ public virtual void Verify(
+ AsymmetricKeyParameter publicKey)
+ {
+ Verify(new Asn1VerifierFactoryProvider(publicKey));
+ }
+
+ ///
+ /// Verify the CRL's signature using a verifier created using the passed in verifier provider.
+ ///
+ /// An appropriate provider for verifying the CRL's signature.
+ /// True if the signature is valid.
+ /// If verifier provider is not appropriate or the CRL algorithm is invalid.
+ public virtual void Verify(
+ IVerifierFactoryProvider verifierProvider)
+ {
+ CheckSignature(verifierProvider.CreateVerifierFactory(c.SignatureAlgorithm));
+ }
+
+ protected virtual void CheckSignature(
+ IVerifierFactory verifier)
+ {
+ if (!c.SignatureAlgorithm.Equals(c.TbsCertList.Signature))
+ {
+ throw new CrlException("Signature algorithm on CertificateList does not match TbsCertList.");
+ }
+
+ Asn1Encodable parameters = c.SignatureAlgorithm.Parameters;
+
+ IStreamCalculator streamCalculator = verifier.CreateCalculator();
+
+ byte[] b = this.GetTbsCertList();
+
+ streamCalculator.Stream.Write(b, 0, b.Length);
+
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(streamCalculator.Stream);
+
+ if (!((IVerifier)streamCalculator.GetResult()).IsVerified(this.GetSignature()))
+ {
+ throw new InvalidKeyException("CRL does not verify with supplied public key.");
+ }
+ }
+
+ public virtual int Version
+ {
+ get { return c.Version; }
+ }
+
+ public virtual X509Name IssuerDN
+ {
+ get { return c.Issuer; }
+ }
+
+ public virtual DateTime ThisUpdate
+ {
+ get { return c.ThisUpdate.ToDateTime(); }
+ }
+
+ public virtual DateTimeObject NextUpdate
+ {
+ get
+ {
+ return c.NextUpdate == null
+ ? null
+ : new DateTimeObject(c.NextUpdate.ToDateTime());
+ }
+ }
+
+ private ISet LoadCrlEntries()
+ {
+ ISet entrySet = new HashSet();
+ IEnumerable certs = c.GetRevokedCertificateEnumeration();
+
+ X509Name previousCertificateIssuer = IssuerDN;
+ foreach (CrlEntry entry in certs)
+ {
+ X509CrlEntry crlEntry = new X509CrlEntry(entry, isIndirect, previousCertificateIssuer);
+ entrySet.Add(crlEntry);
+ previousCertificateIssuer = crlEntry.GetCertificateIssuer();
+ }
+
+ return entrySet;
+ }
+
+ public virtual X509CrlEntry GetRevokedCertificate(
+ BigInteger serialNumber)
+ {
+ IEnumerable certs = c.GetRevokedCertificateEnumeration();
+
+ X509Name previousCertificateIssuer = IssuerDN;
+ foreach (CrlEntry entry in certs)
+ {
+ X509CrlEntry crlEntry = new X509CrlEntry(entry, isIndirect, previousCertificateIssuer);
+
+ if (serialNumber.Equals(entry.UserCertificate.Value))
+ {
+ return crlEntry;
+ }
+
+ previousCertificateIssuer = crlEntry.GetCertificateIssuer();
+ }
+
+ return null;
+ }
+
+ public virtual ISet GetRevokedCertificates()
+ {
+ ISet entrySet = LoadCrlEntries();
+
+ if (entrySet.Count > 0)
+ {
+ return entrySet; // TODO? Collections.unmodifiableSet(entrySet);
+ }
+
+ return null;
+ }
+
+ public virtual byte[] GetTbsCertList()
+ {
+ try
+ {
+ return c.TbsCertList.GetDerEncoded();
+ }
+ catch (Exception e)
+ {
+ throw new CrlException(e.ToString());
+ }
+ }
+
+ public virtual byte[] GetSignature()
+ {
+ return c.GetSignatureOctets();
+ }
+
+ public virtual string SigAlgName
+ {
+ get { return sigAlgName; }
+ }
+
+ public virtual string SigAlgOid
+ {
+ get { return c.SignatureAlgorithm.Algorithm.Id; }
+ }
+
+ public virtual byte[] GetSigAlgParams()
+ {
+ return Arrays.Clone(sigAlgParams);
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return true;
+
+ X509Crl other = obj as X509Crl;
+
+ if (other == null)
+ return false;
+
+ return c.Equals(other.c);
+
+ // NB: May prefer this implementation of Equals if more than one certificate implementation in play
+ //return Arrays.AreEqual(this.GetEncoded(), other.GetEncoded());
+ }
+
+ public override int GetHashCode()
+ {
+ return c.GetHashCode();
+ }
+
+ /**
+ * Returns a string representation of this CRL.
+ *
+ * @return a string representation of this CRL.
+ */
+ public override string ToString()
+ {
+ StringBuilder buf = new StringBuilder();
+ string nl = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.NewLine;
+
+ buf.Append(" Version: ").Append(this.Version).Append(nl);
+ buf.Append(" IssuerDN: ").Append(this.IssuerDN).Append(nl);
+ buf.Append(" This update: ").Append(this.ThisUpdate).Append(nl);
+ buf.Append(" Next update: ").Append(this.NextUpdate).Append(nl);
+ buf.Append(" Signature Algorithm: ").Append(this.SigAlgName).Append(nl);
+
+ byte[] sig = this.GetSignature();
+
+ buf.Append(" Signature: ");
+ buf.Append(Hex.ToHexString(sig, 0, 20)).Append(nl);
+
+ for (int i = 20; i < sig.Length; i += 20)
+ {
+ int count = System.Math.Min(20, sig.Length - i);
+ buf.Append(" ");
+ buf.Append(Hex.ToHexString(sig, i, count)).Append(nl);
+ }
+
+ X509Extensions extensions = c.TbsCertList.Extensions;
+
+ if (extensions != null)
+ {
+ IEnumerator e = extensions.ExtensionOids.GetEnumerator();
+
+ if (e.MoveNext())
+ {
+ buf.Append(" Extensions: ").Append(nl);
+ }
+
+ do
+ {
+ DerObjectIdentifier oid = (DerObjectIdentifier) e.Current;
+ X509Extension ext = extensions.GetExtension(oid);
+
+ if (ext.Value != null)
+ {
+ Asn1Object asn1Value = X509ExtensionUtilities.FromExtensionValue(ext.Value);
+
+ buf.Append(" critical(").Append(ext.IsCritical).Append(") ");
+ try
+ {
+ if (oid.Equals(X509Extensions.CrlNumber))
+ {
+ buf.Append(new CrlNumber(DerInteger.GetInstance(asn1Value).PositiveValue)).Append(nl);
+ }
+ else if (oid.Equals(X509Extensions.DeltaCrlIndicator))
+ {
+ buf.Append(
+ "Base CRL: "
+ + new CrlNumber(DerInteger.GetInstance(
+ asn1Value).PositiveValue))
+ .Append(nl);
+ }
+ else if (oid.Equals(X509Extensions.IssuingDistributionPoint))
+ {
+ buf.Append(IssuingDistributionPoint.GetInstance((Asn1Sequence) asn1Value)).Append(nl);
+ }
+ else if (oid.Equals(X509Extensions.CrlDistributionPoints))
+ {
+ buf.Append(CrlDistPoint.GetInstance((Asn1Sequence) asn1Value)).Append(nl);
+ }
+ else if (oid.Equals(X509Extensions.FreshestCrl))
+ {
+ buf.Append(CrlDistPoint.GetInstance((Asn1Sequence) asn1Value)).Append(nl);
+ }
+ else
+ {
+ buf.Append(oid.Id);
+ buf.Append(" value = ").Append(
+ Asn1Dump.DumpAsString(asn1Value))
+ .Append(nl);
+ }
+ }
+ catch (Exception)
+ {
+ buf.Append(oid.Id);
+ buf.Append(" value = ").Append("*****").Append(nl);
+ }
+ }
+ else
+ {
+ buf.Append(nl);
+ }
+ }
+ while (e.MoveNext());
+ }
+
+ ISet certSet = GetRevokedCertificates();
+ if (certSet != null)
+ {
+ foreach (X509CrlEntry entry in certSet)
+ {
+ buf.Append(entry);
+ buf.Append(nl);
+ }
+ }
+
+ return buf.ToString();
+ }
+
+ /**
+ * Checks whether the given certificate is on this CRL.
+ *
+ * @param cert the certificate to check for.
+ * @return true if the given certificate is on this CRL,
+ * false otherwise.
+ */
+// public bool IsRevoked(
+// Certificate cert)
+// {
+// if (!cert.getType().Equals("X.509"))
+// {
+// throw new RuntimeException("X.509 CRL used with non X.509 Cert");
+// }
+ public virtual bool IsRevoked(
+ X509Certificate cert)
+ {
+ CrlEntry[] certs = c.GetRevokedCertificates();
+
+ if (certs != null)
+ {
+// BigInteger serial = ((X509Certificate)cert).SerialNumber;
+ BigInteger serial = cert.SerialNumber;
+
+ for (int i = 0; i < certs.Length; i++)
+ {
+ if (certs[i].UserCertificate.Value.Equals(serial))
+ {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ protected virtual bool IsIndirectCrl
+ {
+ get
+ {
+ Asn1OctetString idp = GetExtensionValue(X509Extensions.IssuingDistributionPoint);
+ bool isIndirect = false;
+
+ try
+ {
+ if (idp != null)
+ {
+ isIndirect = IssuingDistributionPoint.GetInstance(
+ X509ExtensionUtilities.FromExtensionValue(idp)).IsIndirectCrl;
+ }
+ }
+ catch (Exception e)
+ {
+ // TODO
+// throw new ExtCrlException("Exception reading IssuingDistributionPoint", e);
+ throw new CrlException("Exception reading IssuingDistributionPoint" + e);
+ }
+
+ return isIndirect;
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509Crl.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509Crl.cs.meta
new file mode 100644
index 00000000..a4305b47
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509Crl.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 9a154750ed1601f4b80aa4d215d54e31
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CrlEntry.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CrlEntry.cs
new file mode 100644
index 00000000..f4c2b666
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CrlEntry.cs
@@ -0,0 +1,205 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Extension;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509
+{
+ /**
+ * The following extensions are listed in RFC 2459 as relevant to CRL Entries
+ *
+ * ReasonCode Hode Instruction Code Invalidity Date Certificate Issuer
+ * (critical)
+ */
+ public class X509CrlEntry
+ : X509ExtensionBase
+ {
+ private CrlEntry c;
+ private bool isIndirect;
+ private X509Name previousCertificateIssuer;
+ private X509Name certificateIssuer;
+
+ public X509CrlEntry(
+ CrlEntry c)
+ {
+ this.c = c;
+ this.certificateIssuer = loadCertificateIssuer();
+ }
+
+ /**
+ * Constructor for CRLEntries of indirect CRLs. If isIndirect
+ * is false {@link #getCertificateIssuer()} will always
+ * return null, previousCertificateIssuer is
+ * ignored. If this isIndirect is specified and this CrlEntry
+ * has no certificate issuer CRL entry extension
+ * previousCertificateIssuer is returned by
+ * {@link #getCertificateIssuer()}.
+ *
+ * @param c
+ * TbsCertificateList.CrlEntry object.
+ * @param isIndirect
+ * true if the corresponding CRL is a indirect
+ * CRL.
+ * @param previousCertificateIssuer
+ * Certificate issuer of the previous CrlEntry.
+ */
+ public X509CrlEntry(
+ CrlEntry c,
+ bool isIndirect,
+ X509Name previousCertificateIssuer)
+ {
+ this.c = c;
+ this.isIndirect = isIndirect;
+ this.previousCertificateIssuer = previousCertificateIssuer;
+ this.certificateIssuer = loadCertificateIssuer();
+ }
+
+ private X509Name loadCertificateIssuer()
+ {
+ if (!isIndirect)
+ {
+ return null;
+ }
+
+ Asn1OctetString ext = GetExtensionValue(X509Extensions.CertificateIssuer);
+ if (ext == null)
+ {
+ return previousCertificateIssuer;
+ }
+
+ try
+ {
+ GeneralName[] names = GeneralNames.GetInstance(
+ X509ExtensionUtilities.FromExtensionValue(ext)).GetNames();
+
+ for (int i = 0; i < names.Length; i++)
+ {
+ if (names[i].TagNo == GeneralName.DirectoryName)
+ {
+ return X509Name.GetInstance(names[i].Name);
+ }
+ }
+ }
+ catch (Exception)
+ {
+ }
+
+ return null;
+ }
+
+ public X509Name GetCertificateIssuer()
+ {
+ return certificateIssuer;
+ }
+
+ protected override X509Extensions GetX509Extensions()
+ {
+ return c.Extensions;
+ }
+
+ public byte[] GetEncoded()
+ {
+ try
+ {
+ return c.GetDerEncoded();
+ }
+ catch (Exception e)
+ {
+ throw new CrlException(e.ToString());
+ }
+ }
+
+ public BigInteger SerialNumber
+ {
+ get { return c.UserCertificate.Value; }
+ }
+
+ public DateTime RevocationDate
+ {
+ get { return c.RevocationDate.ToDateTime(); }
+ }
+
+ public bool HasExtensions
+ {
+ get { return c.Extensions != null; }
+ }
+
+ public override string ToString()
+ {
+ StringBuilder buf = new StringBuilder();
+ string nl = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.NewLine;
+
+ buf.Append(" userCertificate: ").Append(this.SerialNumber).Append(nl);
+ buf.Append(" revocationDate: ").Append(this.RevocationDate).Append(nl);
+ buf.Append(" certificateIssuer: ").Append(this.GetCertificateIssuer()).Append(nl);
+
+ X509Extensions extensions = c.Extensions;
+
+ if (extensions != null)
+ {
+ IEnumerator e = extensions.ExtensionOids.GetEnumerator();
+ if (e.MoveNext())
+ {
+ buf.Append(" crlEntryExtensions:").Append(nl);
+
+ do
+ {
+ DerObjectIdentifier oid = (DerObjectIdentifier)e.Current;
+ X509Extension ext = extensions.GetExtension(oid);
+
+ if (ext.Value != null)
+ {
+ Asn1Object obj = Asn1Object.FromByteArray(ext.Value.GetOctets());
+
+ buf.Append(" critical(")
+ .Append(ext.IsCritical)
+ .Append(") ");
+ try
+ {
+ if (oid.Equals(X509Extensions.ReasonCode))
+ {
+ buf.Append(new CrlReason(DerEnumerated.GetInstance(obj)));
+ }
+ else if (oid.Equals(X509Extensions.CertificateIssuer))
+ {
+ buf.Append("Certificate issuer: ").Append(
+ GeneralNames.GetInstance((Asn1Sequence)obj));
+ }
+ else
+ {
+ buf.Append(oid.Id);
+ buf.Append(" value = ").Append(Asn1Dump.DumpAsString(obj));
+ }
+ buf.Append(nl);
+ }
+ catch (Exception)
+ {
+ buf.Append(oid.Id);
+ buf.Append(" value = ").Append("*****").Append(nl);
+ }
+ }
+ else
+ {
+ buf.Append(nl);
+ }
+ }
+ while (e.MoveNext());
+ }
+ }
+
+ return buf.ToString();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CrlEntry.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CrlEntry.cs.meta
new file mode 100644
index 00000000..42d2e430
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CrlEntry.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: bc6c6a5eead859647b11f57143e492fb
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CrlParser.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CrlParser.cs
new file mode 100644
index 00000000..0121cddf
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CrlParser.cs
@@ -0,0 +1,199 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509
+{
+ public class X509CrlParser
+ {
+ private static readonly PemParser PemCrlParser = new PemParser("CRL");
+
+ private readonly bool lazyAsn1;
+
+ private Asn1Set sCrlData;
+ private int sCrlDataObjectCount;
+ private Stream currentCrlStream;
+
+ public X509CrlParser()
+ : this(false)
+ {
+ }
+
+ public X509CrlParser(
+ bool lazyAsn1)
+ {
+ this.lazyAsn1 = lazyAsn1;
+ }
+
+ private X509Crl ReadPemCrl(
+ Stream inStream)
+ {
+ Asn1Sequence seq = PemCrlParser.ReadPemObject(inStream);
+
+ return seq == null
+ ? null
+ : CreateX509Crl(CertificateList.GetInstance(seq));
+ }
+
+ private X509Crl ReadDerCrl(
+ Asn1InputStream dIn)
+ {
+ Asn1Sequence seq = (Asn1Sequence)dIn.ReadObject();
+
+ if (seq.Count > 1 && seq[0] is DerObjectIdentifier)
+ {
+ if (seq[0].Equals(PkcsObjectIdentifiers.SignedData))
+ {
+ sCrlData = SignedData.GetInstance(
+ Asn1Sequence.GetInstance((Asn1TaggedObject) seq[1], true)).Crls;
+
+ return GetCrl();
+ }
+ }
+
+ return CreateX509Crl(CertificateList.GetInstance(seq));
+ }
+
+ private X509Crl GetCrl()
+ {
+ if (sCrlData == null || sCrlDataObjectCount >= sCrlData.Count)
+ {
+ return null;
+ }
+
+ return CreateX509Crl(
+ CertificateList.GetInstance(
+ sCrlData[sCrlDataObjectCount++]));
+ }
+
+ protected virtual X509Crl CreateX509Crl(
+ CertificateList c)
+ {
+ return new X509Crl(c);
+ }
+
+ ///
+ /// Create loading data from byte array.
+ ///
+ ///
+ public X509Crl ReadCrl(
+ byte[] input)
+ {
+ return ReadCrl(new MemoryStream(input, false));
+ }
+
+ ///
+ /// Create loading data from byte array.
+ ///
+ ///
+ public ICollection ReadCrls(
+ byte[] input)
+ {
+ return ReadCrls(new MemoryStream(input, false));
+ }
+
+ /**
+ * Generates a certificate revocation list (CRL) object and initializes
+ * it with the data read from the input stream inStream.
+ */
+ public X509Crl ReadCrl(
+ Stream inStream)
+ {
+ if (inStream == null)
+ throw new ArgumentNullException("inStream");
+ if (!inStream.CanRead)
+ throw new ArgumentException("inStream must be read-able", "inStream");
+
+ if (currentCrlStream == null)
+ {
+ currentCrlStream = inStream;
+ sCrlData = null;
+ sCrlDataObjectCount = 0;
+ }
+ else if (currentCrlStream != inStream) // reset if input stream has changed
+ {
+ currentCrlStream = inStream;
+ sCrlData = null;
+ sCrlDataObjectCount = 0;
+ }
+
+ try
+ {
+ if (sCrlData != null)
+ {
+ if (sCrlDataObjectCount != sCrlData.Count)
+ {
+ return GetCrl();
+ }
+
+ sCrlData = null;
+ sCrlDataObjectCount = 0;
+ return null;
+ }
+
+ PushbackStream pis = new PushbackStream(inStream);
+ int tag = pis.ReadByte();
+
+ if (tag < 0)
+ return null;
+
+ pis.Unread(tag);
+
+ if (tag != 0x30) // assume ascii PEM encoded.
+ {
+ return ReadPemCrl(pis);
+ }
+
+ Asn1InputStream asn1 = lazyAsn1
+ ? new LazyAsn1InputStream(pis)
+ : new Asn1InputStream(pis);
+
+ return ReadDerCrl(asn1);
+ }
+ catch (CrlException e)
+ {
+ throw e;
+ }
+ catch (Exception e)
+ {
+ throw new CrlException(e.ToString());
+ }
+ }
+
+ /**
+ * Returns a (possibly empty) collection view of the CRLs read from
+ * the given input stream inStream.
+ *
+ * The inStream may contain a sequence of DER-encoded CRLs, or
+ * a PKCS#7 CRL set. This is a PKCS#7 SignedData object, with the
+ * only significant field being crls. In particular the signature
+ * and the contents are ignored.
+ */
+ public ICollection ReadCrls(
+ Stream inStream)
+ {
+ X509Crl crl;
+ IList crls = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+
+ while ((crl = ReadCrl(inStream)) != null)
+ {
+ crls.Add(crl);
+ }
+
+ return crls;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CrlParser.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CrlParser.cs.meta
new file mode 100644
index 00000000..c77b331e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509CrlParser.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: e3886777ef4aa57469f8e79b6e1c14ac
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509ExtensionBase.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509ExtensionBase.cs
new file mode 100644
index 00000000..d5bebee5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509ExtensionBase.cs
@@ -0,0 +1,86 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509
+{
+ public abstract class X509ExtensionBase
+ : IX509Extension
+ {
+ protected abstract X509Extensions GetX509Extensions();
+
+ protected virtual ISet GetExtensionOids(
+ bool critical)
+ {
+ X509Extensions extensions = GetX509Extensions();
+ if (extensions != null)
+ {
+ HashSet set = new HashSet();
+ foreach (DerObjectIdentifier oid in extensions.ExtensionOids)
+ {
+ X509Extension ext = extensions.GetExtension(oid);
+ if (ext.IsCritical == critical)
+ {
+ set.Add(oid.Id);
+ }
+ }
+
+ return set;
+ }
+
+ return null;
+ }
+
+ ///
+ /// Get non critical extensions.
+ ///
+ /// A set of non critical extension oids.
+ public virtual ISet GetNonCriticalExtensionOids()
+ {
+ return GetExtensionOids(false);
+ }
+
+ ///
+ /// Get any critical extensions.
+ ///
+ /// A sorted list of critical entension.
+ public virtual ISet GetCriticalExtensionOids()
+ {
+ return GetExtensionOids(true);
+ }
+
+ ///
+ /// Get the value of a given extension.
+ ///
+ /// The object ID of the extension.
+ /// An Asn1OctetString object if that extension is found or null if not.
+ [Obsolete("Use version taking a DerObjectIdentifier instead")]
+ public Asn1OctetString GetExtensionValue(
+ string oid)
+ {
+ return GetExtensionValue(new DerObjectIdentifier(oid));
+ }
+
+ public virtual Asn1OctetString GetExtensionValue(
+ DerObjectIdentifier oid)
+ {
+ X509Extensions exts = GetX509Extensions();
+ if (exts != null)
+ {
+ X509Extension ext = exts.GetExtension(oid);
+ if (ext != null)
+ {
+ return ext.Value;
+ }
+ }
+
+ return null;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509ExtensionBase.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509ExtensionBase.cs.meta
new file mode 100644
index 00000000..7b6af8e6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509ExtensionBase.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c9d43943931445544867d6e0c63383f6
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509KeyUsage.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509KeyUsage.cs
new file mode 100644
index 00000000..44bdc161
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509KeyUsage.cs
@@ -0,0 +1,63 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509
+{
+ /**
+ * A holding class for constructing an X509 Key Usage extension.
+ *
+ *
+ */
+ public class X509KeyUsage
+ : Asn1Encodable
+ {
+ public const int DigitalSignature = 1 << 7;
+ public const int NonRepudiation = 1 << 6;
+ public const int KeyEncipherment = 1 << 5;
+ public const int DataEncipherment = 1 << 4;
+ public const int KeyAgreement = 1 << 3;
+ public const int KeyCertSign = 1 << 2;
+ public const int CrlSign = 1 << 1;
+ public const int EncipherOnly = 1 << 0;
+ public const int DecipherOnly = 1 << 15;
+
+ private readonly int usage;
+
+ /**
+ * Basic constructor.
+ *
+ * @param usage - the bitwise OR of the Key Usage flags giving the
+ * allowed uses for the key.
+ * e.g. (X509KeyUsage.keyEncipherment | X509KeyUsage.dataEncipherment)
+ */
+ public X509KeyUsage(
+ int usage)
+ {
+ this.usage = usage;
+ }
+
+ public override Asn1Object ToAsn1Object()
+ {
+ return new KeyUsage(usage);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509KeyUsage.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509KeyUsage.cs.meta
new file mode 100644
index 00000000..36b9cf81
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509KeyUsage.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 856abba21185f344ba24e505be6a75e4
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509SignatureUtil.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509SignatureUtil.cs
new file mode 100644
index 00000000..eaeaec65
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509SignatureUtil.cs
@@ -0,0 +1,132 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Oiw;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.TeleTrust;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509
+{
+ internal class X509SignatureUtilities
+ {
+ private static readonly Asn1Null derNull = DerNull.Instance;
+
+ internal static void SetSignatureParameters(
+ ISigner signature,
+ Asn1Encodable parameters)
+ {
+ if (parameters != null && !derNull.Equals(parameters))
+ {
+ // TODO Put back in
+// AlgorithmParameters sigParams = AlgorithmParameters.GetInstance(signature.getAlgorithm());
+//
+// try
+// {
+// sigParams.Init(parameters.ToAsn1Object().GetDerEncoded());
+// }
+// catch (IOException e)
+// {
+// throw new SignatureException("IOException decoding parameters: " + e.Message);
+// }
+//
+// if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(signature.getAlgorithm(), "MGF1"))
+// {
+// try
+// {
+// signature.setParameter(sigParams.getParameterSpec(PSSParameterSpec.class));
+// }
+// catch (GeneralSecurityException e)
+// {
+// throw new SignatureException("Exception extracting parameters: " + e.Message);
+// }
+// }
+ }
+ }
+
+ internal static string GetSignatureName(
+ AlgorithmIdentifier sigAlgId)
+ {
+ Asn1Encodable parameters = sigAlgId.Parameters;
+
+ if (parameters != null && !derNull.Equals(parameters))
+ {
+ if (sigAlgId.Algorithm.Equals(PkcsObjectIdentifiers.IdRsassaPss))
+ {
+ RsassaPssParameters rsaParams = RsassaPssParameters.GetInstance(parameters);
+
+ return GetDigestAlgName(rsaParams.HashAlgorithm.Algorithm) + "withRSAandMGF1";
+ }
+ if (sigAlgId.Algorithm.Equals(X9ObjectIdentifiers.ECDsaWithSha2))
+ {
+ Asn1Sequence ecDsaParams = Asn1Sequence.GetInstance(parameters);
+
+ return GetDigestAlgName((DerObjectIdentifier)ecDsaParams[0]) + "withECDSA";
+ }
+ }
+
+ return sigAlgId.Algorithm.Id;
+ }
+
+ /**
+ * Return the digest algorithm using one of the standard JCA string
+ * representations rather than the algorithm identifier (if possible).
+ */
+ private static string GetDigestAlgName(
+ DerObjectIdentifier digestAlgOID)
+ {
+ if (PkcsObjectIdentifiers.MD5.Equals(digestAlgOID))
+ {
+ return "MD5";
+ }
+ else if (OiwObjectIdentifiers.IdSha1.Equals(digestAlgOID))
+ {
+ return "SHA1";
+ }
+ else if (NistObjectIdentifiers.IdSha224.Equals(digestAlgOID))
+ {
+ return "SHA224";
+ }
+ else if (NistObjectIdentifiers.IdSha256.Equals(digestAlgOID))
+ {
+ return "SHA256";
+ }
+ else if (NistObjectIdentifiers.IdSha384.Equals(digestAlgOID))
+ {
+ return "SHA384";
+ }
+ else if (NistObjectIdentifiers.IdSha512.Equals(digestAlgOID))
+ {
+ return "SHA512";
+ }
+ else if (TeleTrusTObjectIdentifiers.RipeMD128.Equals(digestAlgOID))
+ {
+ return "RIPEMD128";
+ }
+ else if (TeleTrusTObjectIdentifiers.RipeMD160.Equals(digestAlgOID))
+ {
+ return "RIPEMD160";
+ }
+ else if (TeleTrusTObjectIdentifiers.RipeMD256.Equals(digestAlgOID))
+ {
+ return "RIPEMD256";
+ }
+ else if (CryptoProObjectIdentifiers.GostR3411.Equals(digestAlgOID))
+ {
+ return "GOST3411";
+ }
+ else
+ {
+ return digestAlgOID.Id;
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509SignatureUtil.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509SignatureUtil.cs.meta
new file mode 100644
index 00000000..22775e86
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509SignatureUtil.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 622a207c30957f04fb37399eac610155
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509Utilities.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509Utilities.cs
new file mode 100644
index 00000000..aa4a8f07
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509Utilities.cs
@@ -0,0 +1,191 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Oiw;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.TeleTrust;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509
+{
+ internal class X509Utilities
+ {
+ private static readonly IDictionary algorithms = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ private static readonly IDictionary exParams = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
+ private static readonly ISet noParams = new HashSet();
+
+ static X509Utilities()
+ {
+ algorithms.Add("MD2WITHRSAENCRYPTION", PkcsObjectIdentifiers.MD2WithRsaEncryption);
+ algorithms.Add("MD2WITHRSA", PkcsObjectIdentifiers.MD2WithRsaEncryption);
+ algorithms.Add("MD5WITHRSAENCRYPTION", PkcsObjectIdentifiers.MD5WithRsaEncryption);
+ algorithms.Add("MD5WITHRSA", PkcsObjectIdentifiers.MD5WithRsaEncryption);
+ algorithms.Add("SHA1WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha1WithRsaEncryption);
+ algorithms.Add("SHA1WITHRSA", PkcsObjectIdentifiers.Sha1WithRsaEncryption);
+ algorithms.Add("SHA224WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha224WithRsaEncryption);
+ algorithms.Add("SHA224WITHRSA", PkcsObjectIdentifiers.Sha224WithRsaEncryption);
+ algorithms.Add("SHA256WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha256WithRsaEncryption);
+ algorithms.Add("SHA256WITHRSA", PkcsObjectIdentifiers.Sha256WithRsaEncryption);
+ algorithms.Add("SHA384WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha384WithRsaEncryption);
+ algorithms.Add("SHA384WITHRSA", PkcsObjectIdentifiers.Sha384WithRsaEncryption);
+ algorithms.Add("SHA512WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512WithRsaEncryption);
+ algorithms.Add("SHA512WITHRSA", PkcsObjectIdentifiers.Sha512WithRsaEncryption);
+ algorithms.Add("SHA1WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss);
+ algorithms.Add("SHA224WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss);
+ algorithms.Add("SHA256WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss);
+ algorithms.Add("SHA384WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss);
+ algorithms.Add("SHA512WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss);
+ algorithms.Add("RIPEMD160WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160);
+ algorithms.Add("RIPEMD160WITHRSA", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160);
+ algorithms.Add("RIPEMD128WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128);
+ algorithms.Add("RIPEMD128WITHRSA", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128);
+ algorithms.Add("RIPEMD256WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256);
+ algorithms.Add("RIPEMD256WITHRSA", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256);
+ algorithms.Add("SHA1WITHDSA", X9ObjectIdentifiers.IdDsaWithSha1);
+ algorithms.Add("DSAWITHSHA1", X9ObjectIdentifiers.IdDsaWithSha1);
+ algorithms.Add("SHA224WITHDSA", NistObjectIdentifiers.DsaWithSha224);
+ algorithms.Add("SHA256WITHDSA", NistObjectIdentifiers.DsaWithSha256);
+ algorithms.Add("SHA384WITHDSA", NistObjectIdentifiers.DsaWithSha384);
+ algorithms.Add("SHA512WITHDSA", NistObjectIdentifiers.DsaWithSha512);
+ algorithms.Add("SHA1WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha1);
+ algorithms.Add("ECDSAWITHSHA1", X9ObjectIdentifiers.ECDsaWithSha1);
+ algorithms.Add("SHA224WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha224);
+ algorithms.Add("SHA256WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha256);
+ algorithms.Add("SHA384WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha384);
+ algorithms.Add("SHA512WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha512);
+ algorithms.Add("GOST3411WITHGOST3410", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94);
+ algorithms.Add("GOST3411WITHGOST3410-94", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94);
+ algorithms.Add("GOST3411WITHECGOST3410", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001);
+ algorithms.Add("GOST3411WITHECGOST3410-2001", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001);
+ algorithms.Add("GOST3411WITHGOST3410-2001", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001);
+
+ //
+ // According to RFC 3279, the ASN.1 encoding SHALL (id-dsa-with-sha1) or MUST (ecdsa-with-SHA*) omit the parameters field.
+ // The parameters field SHALL be NULL for RSA based signature algorithms.
+ //
+ noParams.Add(X9ObjectIdentifiers.ECDsaWithSha1);
+ noParams.Add(X9ObjectIdentifiers.ECDsaWithSha224);
+ noParams.Add(X9ObjectIdentifiers.ECDsaWithSha256);
+ noParams.Add(X9ObjectIdentifiers.ECDsaWithSha384);
+ noParams.Add(X9ObjectIdentifiers.ECDsaWithSha512);
+ noParams.Add(X9ObjectIdentifiers.IdDsaWithSha1);
+ noParams.Add(NistObjectIdentifiers.DsaWithSha224);
+ noParams.Add(NistObjectIdentifiers.DsaWithSha256);
+ noParams.Add(NistObjectIdentifiers.DsaWithSha384);
+ noParams.Add(NistObjectIdentifiers.DsaWithSha512);
+
+ //
+ // RFC 4491
+ //
+ noParams.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94);
+ noParams.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001);
+
+ //
+ // explicit params
+ //
+ AlgorithmIdentifier sha1AlgId = new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance);
+ exParams.Add("SHA1WITHRSAANDMGF1", CreatePssParams(sha1AlgId, 20));
+
+ AlgorithmIdentifier sha224AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha224, DerNull.Instance);
+ exParams.Add("SHA224WITHRSAANDMGF1", CreatePssParams(sha224AlgId, 28));
+
+ AlgorithmIdentifier sha256AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha256, DerNull.Instance);
+ exParams.Add("SHA256WITHRSAANDMGF1", CreatePssParams(sha256AlgId, 32));
+
+ AlgorithmIdentifier sha384AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha384, DerNull.Instance);
+ exParams.Add("SHA384WITHRSAANDMGF1", CreatePssParams(sha384AlgId, 48));
+
+ AlgorithmIdentifier sha512AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha512, DerNull.Instance);
+ exParams.Add("SHA512WITHRSAANDMGF1", CreatePssParams(sha512AlgId, 64));
+ }
+
+ private static RsassaPssParameters CreatePssParams(
+ AlgorithmIdentifier hashAlgId,
+ int saltSize)
+ {
+ return new RsassaPssParameters(
+ hashAlgId,
+ new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, hashAlgId),
+ new DerInteger(saltSize),
+ new DerInteger(1));
+ }
+
+ internal static DerObjectIdentifier GetAlgorithmOid(
+ string algorithmName)
+ {
+ algorithmName = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithmName);
+
+ if (algorithms.Contains(algorithmName))
+ {
+ return (DerObjectIdentifier) algorithms[algorithmName];
+ }
+
+ return new DerObjectIdentifier(algorithmName);
+ }
+
+ internal static AlgorithmIdentifier GetSigAlgID(
+ DerObjectIdentifier sigOid,
+ string algorithmName)
+ {
+ if (noParams.Contains(sigOid))
+ {
+ return new AlgorithmIdentifier(sigOid);
+ }
+
+ algorithmName = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithmName);
+
+ if (exParams.Contains(algorithmName))
+ {
+ return new AlgorithmIdentifier(sigOid, (Asn1Encodable) exParams[algorithmName]);
+ }
+
+ return new AlgorithmIdentifier(sigOid, DerNull.Instance);
+ }
+
+ internal static IEnumerable GetAlgNames()
+ {
+ return new EnumerableProxy(algorithms.Keys);
+ }
+
+ internal static byte[] GetSignatureForObject(
+ DerObjectIdentifier sigOid, // TODO Redundant now?
+ string sigName,
+ AsymmetricKeyParameter privateKey,
+ SecureRandom random,
+ Asn1Encodable ae)
+ {
+ if (sigOid == null)
+ throw new ArgumentNullException("sigOid");
+
+ ISigner sig = SignerUtilities.GetSigner(sigName);
+
+ if (random != null)
+ {
+ sig.Init(true, new ParametersWithRandom(privateKey, random));
+ }
+ else
+ {
+ sig.Init(true, privateKey);
+ }
+
+ byte[] encoded = ae.GetDerEncoded();
+ sig.BlockUpdate(encoded, 0, encoded.Length);
+
+ return sig.GenerateSignature();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509Utilities.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509Utilities.cs.meta
new file mode 100644
index 00000000..891f73cc
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509Utilities.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 05c143c2146115a488ce5733be22c489
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V1CertificateGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V1CertificateGenerator.cs
new file mode 100644
index 00000000..cbd75cbd
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V1CertificateGenerator.cs
@@ -0,0 +1,214 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.IO;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Operators;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509
+{
+ ///
+ /// Class to Generate X509V1 Certificates.
+ ///
+ public class X509V1CertificateGenerator
+ {
+ private V1TbsCertificateGenerator tbsGen;
+ private DerObjectIdentifier sigOID;
+ private AlgorithmIdentifier sigAlgId;
+ private string signatureAlgorithm;
+
+ ///
+ /// Default Constructor.
+ ///
+ public X509V1CertificateGenerator()
+ {
+ tbsGen = new V1TbsCertificateGenerator();
+ }
+
+ ///
+ /// Reset the generator.
+ ///
+ public void Reset()
+ {
+ tbsGen = new V1TbsCertificateGenerator();
+ }
+
+ ///
+ /// Set the certificate's serial number.
+ ///
+ /// Make serial numbers long, if you have no serial number policy make sure the number is at least 16 bytes of secure random data.
+ /// You will be surprised how ugly a serial number collision can get.
+ /// The serial number.
+ public void SetSerialNumber(
+ BigInteger serialNumber)
+ {
+ if (serialNumber.SignValue <= 0)
+ {
+ throw new ArgumentException("serial number must be a positive integer", "serialNumber");
+ }
+
+ tbsGen.SetSerialNumber(new DerInteger(serialNumber));
+ }
+
+ ///
+ /// Set the issuer distinguished name.
+ /// The issuer is the entity whose private key is used to sign the certificate.
+ ///
+ /// The issuers DN.
+ public void SetIssuerDN(
+ X509Name issuer)
+ {
+ tbsGen.SetIssuer(issuer);
+ }
+
+ ///
+ /// Set the date that this certificate is to be valid from.
+ ///
+ ///
+ public void SetNotBefore(
+ DateTime date)
+ {
+ tbsGen.SetStartDate(new Time(date));
+ }
+
+ ///
+ /// Set the date after which this certificate will no longer be valid.
+ ///
+ ///
+ public void SetNotAfter(
+ DateTime date)
+ {
+ tbsGen.SetEndDate(new Time(date));
+ }
+
+ ///
+ /// Set the subject distinguished name.
+ /// The subject describes the entity associated with the public key.
+ ///
+ ///
+ public void SetSubjectDN(
+ X509Name subject)
+ {
+ tbsGen.SetSubject(subject);
+ }
+
+ ///
+ /// Set the public key that this certificate identifies.
+ ///
+ ///
+ public void SetPublicKey(
+ AsymmetricKeyParameter publicKey)
+ {
+ try
+ {
+ tbsGen.SetSubjectPublicKeyInfo(
+ SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey));
+ }
+ catch (Exception e)
+ {
+ throw new ArgumentException("unable to process key - " + e.ToString());
+ }
+ }
+
+ ///
+ /// Set the signature algorithm that will be used to sign this certificate.
+ /// This can be either a name or an OID, names are treated as case insensitive.
+ ///
+ /// string representation of the algorithm name
+ [Obsolete("Not needed if Generate used with an ISignatureFactory")]
+ public void SetSignatureAlgorithm(
+ string signatureAlgorithm)
+ {
+ this.signatureAlgorithm = signatureAlgorithm;
+
+ try
+ {
+ sigOID = X509Utilities.GetAlgorithmOid(signatureAlgorithm);
+ }
+ catch (Exception)
+ {
+ throw new ArgumentException("Unknown signature type requested", "signatureAlgorithm");
+ }
+
+ sigAlgId = X509Utilities.GetSigAlgID(sigOID, signatureAlgorithm);
+
+ tbsGen.SetSignature(sigAlgId);
+ }
+
+ ///
+ /// Generate a new X509Certificate.
+ ///
+ /// The private key of the issuer used to sign this certificate.
+ /// An X509Certificate.
+ [Obsolete("Use Generate with an ISignatureFactory")]
+ public X509Certificate Generate(
+ AsymmetricKeyParameter privateKey)
+ {
+ return Generate(privateKey, null);
+ }
+
+ ///
+ /// Generate a new X509Certificate specifying a SecureRandom instance that you would like to use.
+ ///
+ /// The private key of the issuer used to sign this certificate.
+ /// The Secure Random you want to use.
+ /// An X509Certificate.
+ [Obsolete("Use Generate with an ISignatureFactory")]
+ public X509Certificate Generate(
+ AsymmetricKeyParameter privateKey,
+ SecureRandom random)
+ {
+ return Generate(new Asn1SignatureFactory(signatureAlgorithm, privateKey, random));
+ }
+
+ ///
+ /// Generate a new X509Certificate using the passed in SignatureCalculator.
+ ///
+ /// A signature calculator factory with the necessary algorithm details.
+ /// An X509Certificate.
+ public X509Certificate Generate(ISignatureFactory signatureCalculatorFactory)
+ {
+ tbsGen.SetSignature ((AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails);
+
+ TbsCertificateStructure tbsCert = tbsGen.GenerateTbsCertificate();
+
+ IStreamCalculator streamCalculator = signatureCalculatorFactory.CreateCalculator();
+
+ byte[] encoded = tbsCert.GetDerEncoded();
+
+ streamCalculator.Stream.Write(encoded, 0, encoded.Length);
+
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(streamCalculator.Stream);
+
+ return GenerateJcaObject(tbsCert, (AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails, ((IBlockResult)streamCalculator.GetResult()).Collect());
+ }
+
+ private X509Certificate GenerateJcaObject(
+ TbsCertificateStructure tbsCert,
+ AlgorithmIdentifier sigAlg,
+ byte[] signature)
+ {
+ return new X509Certificate(
+ new X509CertificateStructure(tbsCert, sigAlg, new DerBitString(signature)));
+ }
+
+ ///
+ /// Allows enumeration of the signature names supported by the generator.
+ ///
+ public IEnumerable SignatureAlgNames
+ {
+ get { return X509Utilities.GetAlgNames(); }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V1CertificateGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V1CertificateGenerator.cs.meta
new file mode 100644
index 00000000..76950c8a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V1CertificateGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a9d644b2fa83d85409041f2aa7707d64
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V2AttributeCertificate.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V2AttributeCertificate.cs
new file mode 100644
index 00000000..7d292a84
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V2AttributeCertificate.cs
@@ -0,0 +1,284 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Operators;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509
+{
+ /// An implementation of a version 2 X.509 Attribute Certificate.
+ public class X509V2AttributeCertificate
+ : X509ExtensionBase, IX509AttributeCertificate
+ {
+ private readonly AttributeCertificate cert;
+ private readonly DateTime notBefore;
+ private readonly DateTime notAfter;
+
+ private static AttributeCertificate GetObject(Stream input)
+ {
+ try
+ {
+ return AttributeCertificate.GetInstance(Asn1Object.FromStream(input));
+ }
+ catch (IOException e)
+ {
+ throw e;
+ }
+ catch (Exception e)
+ {
+ throw new IOException("exception decoding certificate structure", e);
+ }
+ }
+
+ public X509V2AttributeCertificate(
+ Stream encIn)
+ : this(GetObject(encIn))
+ {
+ }
+
+ public X509V2AttributeCertificate(
+ byte[] encoded)
+ : this(new MemoryStream(encoded, false))
+ {
+ }
+
+ internal X509V2AttributeCertificate(
+ AttributeCertificate cert)
+ {
+ this.cert = cert;
+
+ try
+ {
+ this.notAfter = cert.ACInfo.AttrCertValidityPeriod.NotAfterTime.ToDateTime();
+ this.notBefore = cert.ACInfo.AttrCertValidityPeriod.NotBeforeTime.ToDateTime();
+ }
+ catch (Exception e)
+ {
+ throw new IOException("invalid data structure in certificate!", e);
+ }
+ }
+
+ public virtual int Version
+ {
+ get { return cert.ACInfo.Version.Value.IntValue + 1; }
+ }
+
+ public virtual BigInteger SerialNumber
+ {
+ get { return cert.ACInfo.SerialNumber.Value; }
+ }
+
+ public virtual AttributeCertificateHolder Holder
+ {
+ get
+ {
+ return new AttributeCertificateHolder((Asn1Sequence)cert.ACInfo.Holder.ToAsn1Object());
+ }
+ }
+
+ public virtual AttributeCertificateIssuer Issuer
+ {
+ get
+ {
+ return new AttributeCertificateIssuer(cert.ACInfo.Issuer);
+ }
+ }
+
+ public virtual DateTime NotBefore
+ {
+ get { return notBefore; }
+ }
+
+ public virtual DateTime NotAfter
+ {
+ get { return notAfter; }
+ }
+
+ public virtual bool[] GetIssuerUniqueID()
+ {
+ DerBitString id = cert.ACInfo.IssuerUniqueID;
+
+ if (id != null)
+ {
+ byte[] bytes = id.GetBytes();
+ bool[] boolId = new bool[bytes.Length * 8 - id.PadBits];
+
+ for (int i = 0; i != boolId.Length; i++)
+ {
+ //boolId[i] = (bytes[i / 8] & (0x80 >>> (i % 8))) != 0;
+ boolId[i] = (bytes[i / 8] & (0x80 >> (i % 8))) != 0;
+ }
+
+ return boolId;
+ }
+
+ return null;
+ }
+
+ public virtual bool IsValidNow
+ {
+ get { return IsValid(DateTime.UtcNow); }
+ }
+
+ public virtual bool IsValid(
+ DateTime date)
+ {
+ return date.CompareTo(NotBefore) >= 0 && date.CompareTo(NotAfter) <= 0;
+ }
+
+ public virtual void CheckValidity()
+ {
+ this.CheckValidity(DateTime.UtcNow);
+ }
+
+ public virtual void CheckValidity(
+ DateTime date)
+ {
+ if (date.CompareTo(NotAfter) > 0)
+ throw new CertificateExpiredException("certificate expired on " + NotAfter);
+ if (date.CompareTo(NotBefore) < 0)
+ throw new CertificateNotYetValidException("certificate not valid until " + NotBefore);
+ }
+
+ public virtual AlgorithmIdentifier SignatureAlgorithm
+ {
+ get { return cert.SignatureAlgorithm; }
+ }
+
+ public virtual byte[] GetSignature()
+ {
+ return cert.GetSignatureOctets();
+ }
+
+ public virtual void Verify(
+ AsymmetricKeyParameter key)
+ {
+ CheckSignature(new Asn1VerifierFactory(cert.SignatureAlgorithm, key));
+ }
+
+ ///
+ /// Verify the certificate's signature using a verifier created using the passed in verifier provider.
+ ///
+ /// An appropriate provider for verifying the certificate's signature.
+ /// True if the signature is valid.
+ /// If verifier provider is not appropriate or the certificate algorithm is invalid.
+ public virtual void Verify(
+ IVerifierFactoryProvider verifierProvider)
+ {
+ CheckSignature(verifierProvider.CreateVerifierFactory(cert.SignatureAlgorithm));
+ }
+
+ protected virtual void CheckSignature(
+ IVerifierFactory verifier)
+ {
+ if (!cert.SignatureAlgorithm.Equals(cert.ACInfo.Signature))
+ {
+ throw new CertificateException("Signature algorithm in certificate info not same as outer certificate");
+ }
+
+ IStreamCalculator streamCalculator = verifier.CreateCalculator();
+
+ try
+ {
+ byte[] b = this.cert.ACInfo.GetEncoded();
+
+ streamCalculator.Stream.Write(b, 0, b.Length);
+
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(streamCalculator.Stream);
+ }
+ catch (IOException e)
+ {
+ throw new SignatureException("Exception encoding certificate info object", e);
+ }
+
+ if (!((IVerifier)streamCalculator.GetResult()).IsVerified(this.GetSignature()))
+ {
+ throw new InvalidKeyException("Public key presented not for certificate signature");
+ }
+ }
+
+ public virtual byte[] GetEncoded()
+ {
+ return cert.GetEncoded();
+ }
+
+ protected override X509Extensions GetX509Extensions()
+ {
+ return cert.ACInfo.Extensions;
+ }
+
+ public virtual X509Attribute[] GetAttributes()
+ {
+ Asn1Sequence seq = cert.ACInfo.Attributes;
+ X509Attribute[] attrs = new X509Attribute[seq.Count];
+
+ for (int i = 0; i != seq.Count; i++)
+ {
+ attrs[i] = new X509Attribute((Asn1Encodable)seq[i]);
+ }
+
+ return attrs;
+ }
+
+ public virtual X509Attribute[] GetAttributes(
+ string oid)
+ {
+ Asn1Sequence seq = cert.ACInfo.Attributes;
+ IList list = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+
+ for (int i = 0; i != seq.Count; i++)
+ {
+ X509Attribute attr = new X509Attribute((Asn1Encodable)seq[i]);
+ if (attr.Oid.Equals(oid))
+ {
+ list.Add(attr);
+ }
+ }
+
+ if (list.Count < 1)
+ {
+ return null;
+ }
+
+ X509Attribute[] result = new X509Attribute[list.Count];
+ for (int i = 0; i < list.Count; ++i)
+ {
+ result[i] = (X509Attribute)list[i];
+ }
+ return result;
+ }
+
+ public override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return true;
+
+ X509V2AttributeCertificate other = obj as X509V2AttributeCertificate;
+
+ if (other == null)
+ return false;
+
+ return cert.Equals(other.cert);
+
+ // NB: May prefer this implementation of Equals if more than one certificate implementation in play
+ //return Arrays.AreEqual(this.GetEncoded(), other.GetEncoded());
+ }
+
+ public override int GetHashCode()
+ {
+ return cert.GetHashCode();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V2AttributeCertificate.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V2AttributeCertificate.cs.meta
new file mode 100644
index 00000000..eccc88bb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V2AttributeCertificate.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 8f91955083bfb1549aefb0e34a5159e0
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V2AttributeCertificateGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V2AttributeCertificateGenerator.cs
new file mode 100644
index 00000000..a88f368a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V2AttributeCertificateGenerator.cs
@@ -0,0 +1,207 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Operators;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509
+{
+ /// Class to produce an X.509 Version 2 AttributeCertificate.
+ public class X509V2AttributeCertificateGenerator
+ {
+ private readonly X509ExtensionsGenerator extGenerator = new X509ExtensionsGenerator();
+
+ private V2AttributeCertificateInfoGenerator acInfoGen;
+ private DerObjectIdentifier sigOID;
+ private AlgorithmIdentifier sigAlgId;
+ private string signatureAlgorithm;
+
+ public X509V2AttributeCertificateGenerator()
+ {
+ acInfoGen = new V2AttributeCertificateInfoGenerator();
+ }
+
+ /// Reset the generator
+ public void Reset()
+ {
+ acInfoGen = new V2AttributeCertificateInfoGenerator();
+ extGenerator.Reset();
+ }
+
+ /// Set the Holder of this Attribute Certificate.
+ public void SetHolder(
+ AttributeCertificateHolder holder)
+ {
+ acInfoGen.SetHolder(holder.holder);
+ }
+
+ /// Set the issuer.
+ public void SetIssuer(
+ AttributeCertificateIssuer issuer)
+ {
+ acInfoGen.SetIssuer(AttCertIssuer.GetInstance(issuer.form));
+ }
+
+ /// Set the serial number for the certificate.
+ public void SetSerialNumber(
+ BigInteger serialNumber)
+ {
+ acInfoGen.SetSerialNumber(new DerInteger(serialNumber));
+ }
+
+ public void SetNotBefore(
+ DateTime date)
+ {
+ acInfoGen.SetStartDate(new DerGeneralizedTime(date));
+ }
+
+ public void SetNotAfter(
+ DateTime date)
+ {
+ acInfoGen.SetEndDate(new DerGeneralizedTime(date));
+ }
+
+ ///
+ /// Set the signature algorithm. This can be either a name or an OID, names
+ /// are treated as case insensitive.
+ ///
+ /// The algorithm name.
+ [Obsolete("Not needed if Generate used with an ISignatureFactory")]
+ public void SetSignatureAlgorithm(
+ string signatureAlgorithm)
+ {
+ this.signatureAlgorithm = signatureAlgorithm;
+
+ try
+ {
+ sigOID = X509Utilities.GetAlgorithmOid(signatureAlgorithm);
+ }
+ catch (Exception)
+ {
+ throw new ArgumentException("Unknown signature type requested");
+ }
+
+ sigAlgId = X509Utilities.GetSigAlgID(sigOID, signatureAlgorithm);
+
+ acInfoGen.SetSignature(sigAlgId);
+ }
+
+ /// Add an attribute.
+ public void AddAttribute(
+ X509Attribute attribute)
+ {
+ acInfoGen.AddAttribute(AttributeX509.GetInstance(attribute.ToAsn1Object()));
+ }
+
+ public void SetIssuerUniqueId(
+ bool[] iui)
+ {
+ // TODO convert bool array to bit string
+ //acInfoGen.SetIssuerUniqueID(iui);
+ throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("SetIssuerUniqueId()");
+ }
+
+ /// Add a given extension field for the standard extensions tag.
+ public void AddExtension(
+ string oid,
+ bool critical,
+ Asn1Encodable extensionValue)
+ {
+ extGenerator.AddExtension(new DerObjectIdentifier(oid), critical, extensionValue);
+ }
+
+ ///
+ /// Add a given extension field for the standard extensions tag.
+ /// The value parameter becomes the contents of the octet string associated
+ /// with the extension.
+ ///
+ public void AddExtension(
+ string oid,
+ bool critical,
+ byte[] extensionValue)
+ {
+ extGenerator.AddExtension(new DerObjectIdentifier(oid), critical, extensionValue);
+ }
+
+ ///
+ /// Generate an X509 certificate, based on the current issuer and subject.
+ ///
+ [Obsolete("Use Generate with an ISignatureFactory")]
+ public IX509AttributeCertificate Generate(
+ AsymmetricKeyParameter privateKey)
+ {
+ return Generate(privateKey, null);
+ }
+
+ ///
+ /// Generate an X509 certificate, based on the current issuer and subject,
+ /// using the supplied source of randomness, if required.
+ ///
+ [Obsolete("Use Generate with an ISignatureFactory")]
+ public IX509AttributeCertificate Generate(
+ AsymmetricKeyParameter privateKey,
+ SecureRandom random)
+ {
+ return Generate(new Asn1SignatureFactory(signatureAlgorithm, privateKey, random));
+ }
+
+ ///
+ /// Generate a new X.509 Attribute Certificate using the passed in SignatureCalculator.
+ ///
+ /// A signature calculator factory with the necessary algorithm details.
+ /// An IX509AttributeCertificate.
+ public IX509AttributeCertificate Generate(ISignatureFactory signatureCalculatorFactory)
+ {
+ if (!extGenerator.IsEmpty)
+ {
+ acInfoGen.SetExtensions(extGenerator.Generate());
+ }
+
+ AlgorithmIdentifier sigAlgID = (AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails;
+
+ acInfoGen.SetSignature(sigAlgID);
+
+ AttributeCertificateInfo acInfo = acInfoGen.GenerateAttributeCertificateInfo();
+
+ byte[] encoded = acInfo.GetDerEncoded();
+
+ IStreamCalculator streamCalculator = signatureCalculatorFactory.CreateCalculator();
+
+ streamCalculator.Stream.Write(encoded, 0, encoded.Length);
+
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(streamCalculator.Stream);
+
+ try
+ {
+ DerBitString signatureValue = new DerBitString(((IBlockResult)streamCalculator.GetResult()).Collect());
+
+ return new X509V2AttributeCertificate(new AttributeCertificate(acInfo, sigAlgID, signatureValue));
+ }
+ catch (Exception e)
+ {
+ // TODO
+// throw new ExtCertificateEncodingException("constructed invalid certificate", e);
+ throw new CertificateEncodingException("constructed invalid certificate", e);
+ }
+ }
+
+ ///
+ /// Allows enumeration of the signature names supported by the generator.
+ ///
+ public IEnumerable SignatureAlgNames
+ {
+ get { return X509Utilities.GetAlgNames(); }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V2AttributeCertificateGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V2AttributeCertificateGenerator.cs.meta
new file mode 100644
index 00000000..71394ac7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V2AttributeCertificateGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 443d99da7fa37d344b2315855b869d71
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V2CRLGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V2CRLGenerator.cs
new file mode 100644
index 00000000..b2071474
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V2CRLGenerator.cs
@@ -0,0 +1,282 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Operators;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509
+{
+ /**
+ * class to produce an X.509 Version 2 CRL.
+ */
+ public class X509V2CrlGenerator
+ {
+ private readonly X509ExtensionsGenerator extGenerator = new X509ExtensionsGenerator();
+
+ private V2TbsCertListGenerator tbsGen;
+ private DerObjectIdentifier sigOID;
+ private AlgorithmIdentifier sigAlgId;
+ private string signatureAlgorithm;
+
+ public X509V2CrlGenerator()
+ {
+ tbsGen = new V2TbsCertListGenerator();
+ }
+
+ /**
+ * reset the generator
+ */
+ public void Reset()
+ {
+ tbsGen = new V2TbsCertListGenerator();
+ extGenerator.Reset();
+ }
+
+ /**
+ * Set the issuer distinguished name - the issuer is the entity whose private key is used to sign the
+ * certificate.
+ */
+ public void SetIssuerDN(
+ X509Name issuer)
+ {
+ tbsGen.SetIssuer(issuer);
+ }
+
+ public void SetThisUpdate(
+ DateTime date)
+ {
+ tbsGen.SetThisUpdate(new Time(date));
+ }
+
+ public void SetNextUpdate(
+ DateTime date)
+ {
+ tbsGen.SetNextUpdate(new Time(date));
+ }
+
+ /**
+ * Reason being as indicated by CrlReason, i.e. CrlReason.KeyCompromise
+ * or 0 if CrlReason is not to be used
+ **/
+ public void AddCrlEntry(
+ BigInteger userCertificate,
+ DateTime revocationDate,
+ int reason)
+ {
+ tbsGen.AddCrlEntry(new DerInteger(userCertificate), new Time(revocationDate), reason);
+ }
+
+ /**
+ * Add a CRL entry with an Invalidity Date extension as well as a CrlReason extension.
+ * Reason being as indicated by CrlReason, i.e. CrlReason.KeyCompromise
+ * or 0 if CrlReason is not to be used
+ **/
+ public void AddCrlEntry(
+ BigInteger userCertificate,
+ DateTime revocationDate,
+ int reason,
+ DateTime invalidityDate)
+ {
+ tbsGen.AddCrlEntry(new DerInteger(userCertificate), new Time(revocationDate), reason, new DerGeneralizedTime(invalidityDate));
+ }
+
+ /**
+ * Add a CRL entry with extensions.
+ **/
+ public void AddCrlEntry(
+ BigInteger userCertificate,
+ DateTime revocationDate,
+ X509Extensions extensions)
+ {
+ tbsGen.AddCrlEntry(new DerInteger(userCertificate), new Time(revocationDate), extensions);
+ }
+
+ /**
+ * Add the CRLEntry objects contained in a previous CRL.
+ *
+ * @param other the X509Crl to source the other entries from.
+ */
+ public void AddCrl(
+ X509Crl other)
+ {
+ if (other == null)
+ throw new ArgumentNullException("other");
+
+ ISet revocations = other.GetRevokedCertificates();
+
+ if (revocations != null)
+ {
+ foreach (X509CrlEntry entry in revocations)
+ {
+ try
+ {
+ tbsGen.AddCrlEntry(
+ Asn1Sequence.GetInstance(
+ Asn1Object.FromByteArray(entry.GetEncoded())));
+ }
+ catch (IOException e)
+ {
+ throw new CrlException("exception processing encoding of CRL", e);
+ }
+ }
+ }
+ }
+
+ ///
+ /// Set the signature algorithm that will be used to sign this CRL.
+ ///
+ ///
+ [Obsolete("Not needed if Generate used with an ISignatureFactory")]
+ public void SetSignatureAlgorithm(
+ string signatureAlgorithm)
+ {
+ this.signatureAlgorithm = signatureAlgorithm;
+
+ try
+ {
+ sigOID = X509Utilities.GetAlgorithmOid(signatureAlgorithm);
+ }
+ catch (Exception e)
+ {
+ throw new ArgumentException("Unknown signature type requested", e);
+ }
+
+ sigAlgId = X509Utilities.GetSigAlgID(sigOID, signatureAlgorithm);
+
+ tbsGen.SetSignature(sigAlgId);
+ }
+
+ /**
+ * add a given extension field for the standard extensions tag (tag 0)
+ */
+ public void AddExtension(
+ string oid,
+ bool critical,
+ Asn1Encodable extensionValue)
+ {
+ extGenerator.AddExtension(new DerObjectIdentifier(oid), critical, extensionValue);
+ }
+
+ /**
+ * add a given extension field for the standard extensions tag (tag 0)
+ */
+ public void AddExtension(
+ DerObjectIdentifier oid,
+ bool critical,
+ Asn1Encodable extensionValue)
+ {
+ extGenerator.AddExtension(oid, critical, extensionValue);
+ }
+
+ /**
+ * add a given extension field for the standard extensions tag (tag 0)
+ */
+ public void AddExtension(
+ string oid,
+ bool critical,
+ byte[] extensionValue)
+ {
+ extGenerator.AddExtension(new DerObjectIdentifier(oid), critical, new DerOctetString(extensionValue));
+ }
+
+ /**
+ * add a given extension field for the standard extensions tag (tag 0)
+ */
+ public void AddExtension(
+ DerObjectIdentifier oid,
+ bool critical,
+ byte[] extensionValue)
+ {
+ extGenerator.AddExtension(oid, critical, new DerOctetString(extensionValue));
+ }
+
+ ///
+ /// Generate an X.509 CRL, based on the current issuer and subject.
+ ///
+ /// The private key of the issuer that is signing this certificate.
+ /// An X509Crl.
+ [Obsolete("Use Generate with an ISignatureFactory")]
+ public X509Crl Generate(
+ AsymmetricKeyParameter privateKey)
+ {
+ return Generate(privateKey, null);
+ }
+
+ ///
+ /// Generate an X.509 CRL, based on the current issuer and subject using the specified secure random.
+ ///
+ /// The private key of the issuer that is signing this certificate.
+ /// Your Secure Random instance.
+ /// An X509Crl.
+ [Obsolete("Use Generate with an ISignatureFactory")]
+ public X509Crl Generate(
+ AsymmetricKeyParameter privateKey,
+ SecureRandom random)
+ {
+ return Generate(new Asn1SignatureFactory(signatureAlgorithm, privateKey, random));
+ }
+
+ ///
+ /// Generate a new X509Crl using the passed in SignatureCalculator.
+ ///
+ /// A signature calculator factory with the necessary algorithm details.
+ /// An X509Crl.
+ public X509Crl Generate(ISignatureFactory signatureCalculatorFactory)
+ {
+ tbsGen.SetSignature((AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails);
+
+ TbsCertificateList tbsCertList = GenerateCertList();
+
+ IStreamCalculator streamCalculator = signatureCalculatorFactory.CreateCalculator();
+
+ byte[] encoded = tbsCertList.GetDerEncoded();
+
+ streamCalculator.Stream.Write(encoded, 0, encoded.Length);
+
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(streamCalculator.Stream);
+
+ return GenerateJcaObject(tbsCertList, (AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails, ((IBlockResult)streamCalculator.GetResult()).Collect());
+ }
+
+ private TbsCertificateList GenerateCertList()
+ {
+ if (!extGenerator.IsEmpty)
+ {
+ tbsGen.SetExtensions(extGenerator.Generate());
+ }
+
+ return tbsGen.GenerateTbsCertList();
+ }
+
+ private X509Crl GenerateJcaObject(
+ TbsCertificateList tbsCrl,
+ AlgorithmIdentifier algId,
+ byte[] signature)
+ {
+ return new X509Crl(
+ CertificateList.GetInstance(
+ new DerSequence(tbsCrl, algId, new DerBitString(signature))));
+ }
+
+ ///
+ /// Allows enumeration of the signature names supported by the generator.
+ ///
+ public IEnumerable SignatureAlgNames
+ {
+ get { return X509Utilities.GetAlgNames(); }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V2CRLGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V2CRLGenerator.cs.meta
new file mode 100644
index 00000000..d45336d7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V2CRLGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 4967cc865d9366a41bc51c9bc1a36da0
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V3CertificateGenerator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V3CertificateGenerator.cs
new file mode 100644
index 00000000..e4894a37
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V3CertificateGenerator.cs
@@ -0,0 +1,348 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Operators;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Extension;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509
+{
+ ///
+ /// A class to Generate Version 3 X509Certificates.
+ ///
+ public class X509V3CertificateGenerator
+ {
+ private readonly X509ExtensionsGenerator extGenerator = new X509ExtensionsGenerator();
+
+ private V3TbsCertificateGenerator tbsGen;
+ private DerObjectIdentifier sigOid;
+ private AlgorithmIdentifier sigAlgId;
+ private string signatureAlgorithm;
+
+ public X509V3CertificateGenerator()
+ {
+ tbsGen = new V3TbsCertificateGenerator();
+ }
+
+ ///
+ /// Reset the Generator.
+ ///
+ public void Reset()
+ {
+ tbsGen = new V3TbsCertificateGenerator();
+ extGenerator.Reset();
+ }
+
+ ///
+ /// Set the certificate's serial number.
+ ///
+ /// Make serial numbers long, if you have no serial number policy make sure the number is at least 16 bytes of secure random data.
+ /// You will be surprised how ugly a serial number collision can Get.
+ /// The serial number.
+ public void SetSerialNumber(
+ BigInteger serialNumber)
+ {
+ if (serialNumber.SignValue <= 0)
+ {
+ throw new ArgumentException("serial number must be a positive integer", "serialNumber");
+ }
+
+ tbsGen.SetSerialNumber(new DerInteger(serialNumber));
+ }
+
+ ///
+ /// Set the distinguished name of the issuer.
+ /// The issuer is the entity which is signing the certificate.
+ ///
+ /// The issuer's DN.
+ public void SetIssuerDN(
+ X509Name issuer)
+ {
+ tbsGen.SetIssuer(issuer);
+ }
+
+ ///
+ /// Set the date that this certificate is to be valid from.
+ ///
+ ///
+ public void SetNotBefore(
+ DateTime date)
+ {
+ tbsGen.SetStartDate(new Time(date));
+ }
+
+ ///
+ /// Set the date after which this certificate will no longer be valid.
+ ///
+ ///
+ public void SetNotAfter(
+ DateTime date)
+ {
+ tbsGen.SetEndDate(new Time(date));
+ }
+
+ ///
+ /// Set the DN of the entity that this certificate is about.
+ ///
+ ///
+ public void SetSubjectDN(
+ X509Name subject)
+ {
+ tbsGen.SetSubject(subject);
+ }
+
+ ///
+ /// Set the public key that this certificate identifies.
+ ///
+ ///
+ public void SetPublicKey(
+ AsymmetricKeyParameter publicKey)
+ {
+ tbsGen.SetSubjectPublicKeyInfo(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey));
+ }
+
+ ///
+ /// Set the signature algorithm that will be used to sign this certificate.
+ ///
+ ///
+ [Obsolete("Not needed if Generate used with an ISignatureFactory")]
+ public void SetSignatureAlgorithm(
+ string signatureAlgorithm)
+ {
+ this.signatureAlgorithm = signatureAlgorithm;
+
+ try
+ {
+ sigOid = X509Utilities.GetAlgorithmOid(signatureAlgorithm);
+ }
+ catch (Exception)
+ {
+ throw new ArgumentException("Unknown signature type requested: " + signatureAlgorithm);
+ }
+
+ sigAlgId = X509Utilities.GetSigAlgID(sigOid, signatureAlgorithm);
+
+ tbsGen.SetSignature(sigAlgId);
+ }
+
+ ///
+ /// Set the subject unique ID - note: it is very rare that it is correct to do this.
+ ///
+ ///
+ public void SetSubjectUniqueID(
+ bool[] uniqueID)
+ {
+ tbsGen.SetSubjectUniqueID(booleanToBitString(uniqueID));
+ }
+
+ ///
+ /// Set the issuer unique ID - note: it is very rare that it is correct to do this.
+ ///
+ ///
+ public void SetIssuerUniqueID(
+ bool[] uniqueID)
+ {
+ tbsGen.SetIssuerUniqueID(booleanToBitString(uniqueID));
+ }
+
+ private DerBitString booleanToBitString(
+ bool[] id)
+ {
+ byte[] bytes = new byte[(id.Length + 7) / 8];
+
+ for (int i = 0; i != id.Length; i++)
+ {
+ if (id[i])
+ {
+ bytes[i / 8] |= (byte)(1 << ((7 - (i % 8))));
+ }
+ }
+
+ int pad = id.Length % 8;
+
+ if (pad == 0)
+ {
+ return new DerBitString(bytes);
+ }
+
+ return new DerBitString(bytes, 8 - pad);
+ }
+
+ ///
+ /// Add a given extension field for the standard extensions tag (tag 3).
+ ///
+ /// string containing a dotted decimal Object Identifier.
+ /// Is it critical.
+ /// The value.
+ public void AddExtension(
+ string oid,
+ bool critical,
+ Asn1Encodable extensionValue)
+ {
+ extGenerator.AddExtension(new DerObjectIdentifier(oid), critical, extensionValue);
+ }
+
+ ///
+ /// Add an extension to this certificate.
+ ///
+ /// Its Object Identifier.
+ /// Is it critical.
+ /// The value.
+ public void AddExtension(
+ DerObjectIdentifier oid,
+ bool critical,
+ Asn1Encodable extensionValue)
+ {
+ extGenerator.AddExtension(oid, critical, extensionValue);
+ }
+
+ ///
+ /// Add an extension using a string with a dotted decimal OID.
+ ///
+ /// string containing a dotted decimal Object Identifier.
+ /// Is it critical.
+ /// byte[] containing the value of this extension.
+ public void AddExtension(
+ string oid,
+ bool critical,
+ byte[] extensionValue)
+ {
+ extGenerator.AddExtension(new DerObjectIdentifier(oid), critical, new DerOctetString(extensionValue));
+ }
+
+ ///
+ /// Add an extension to this certificate.
+ ///
+ /// Its Object Identifier.
+ /// Is it critical.
+ /// byte[] containing the value of this extension.
+ public void AddExtension(
+ DerObjectIdentifier oid,
+ bool critical,
+ byte[] extensionValue)
+ {
+ extGenerator.AddExtension(oid, critical, new DerOctetString(extensionValue));
+ }
+
+ ///
+ /// Add a given extension field for the standard extensions tag (tag 3),
+ /// copying the extension value from another certificate.
+ ///
+ public void CopyAndAddExtension(
+ string oid,
+ bool critical,
+ X509Certificate cert)
+ {
+ CopyAndAddExtension(new DerObjectIdentifier(oid), critical, cert);
+ }
+
+ /**
+ * add a given extension field for the standard extensions tag (tag 3)
+ * copying the extension value from another certificate.
+ * @throws CertificateParsingException if the extension cannot be extracted.
+ */
+ public void CopyAndAddExtension(
+ DerObjectIdentifier oid,
+ bool critical,
+ X509Certificate cert)
+ {
+ Asn1OctetString extValue = cert.GetExtensionValue(oid);
+
+ if (extValue == null)
+ {
+ throw new CertificateParsingException("extension " + oid + " not present");
+ }
+
+ try
+ {
+ Asn1Encodable value = X509ExtensionUtilities.FromExtensionValue(extValue);
+
+ this.AddExtension(oid, critical, value);
+ }
+ catch (Exception e)
+ {
+ throw new CertificateParsingException(e.Message, e);
+ }
+ }
+
+ ///
+ /// Generate an X509Certificate.
+ ///
+ /// The private key of the issuer that is signing this certificate.
+ /// An X509Certificate.
+ [Obsolete("Use Generate with an ISignatureFactory")]
+ public X509Certificate Generate(
+ AsymmetricKeyParameter privateKey)
+ {
+ return Generate(privateKey, null);
+ }
+
+ ///
+ /// Generate an X509Certificate using your own SecureRandom.
+ ///
+ /// The private key of the issuer that is signing this certificate.
+ /// You Secure Random instance.
+ /// An X509Certificate.
+ [Obsolete("Use Generate with an ISignatureFactory")]
+ public X509Certificate Generate(
+ AsymmetricKeyParameter privateKey,
+ SecureRandom random)
+ {
+ return Generate(new Asn1SignatureFactory(signatureAlgorithm, privateKey, random));
+ }
+
+ ///
+ /// Generate a new X509Certificate using the passed in SignatureCalculator.
+ ///
+ /// A signature calculator factory with the necessary algorithm details.
+ /// An X509Certificate.
+ public X509Certificate Generate(ISignatureFactory signatureCalculatorFactory)
+ {
+ tbsGen.SetSignature ((AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails);
+
+ if (!extGenerator.IsEmpty)
+ {
+ tbsGen.SetExtensions(extGenerator.Generate());
+ }
+
+ TbsCertificateStructure tbsCert = tbsGen.GenerateTbsCertificate();
+
+ IStreamCalculator streamCalculator = signatureCalculatorFactory.CreateCalculator();
+
+ byte[] encoded = tbsCert.GetDerEncoded();
+
+ streamCalculator.Stream.Write(encoded, 0, encoded.Length);
+
+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(streamCalculator.Stream);
+
+ return GenerateJcaObject(tbsCert, (AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails, ((IBlockResult)streamCalculator.GetResult()).Collect());
+ }
+
+ private X509Certificate GenerateJcaObject(
+ TbsCertificateStructure tbsCert,
+ AlgorithmIdentifier sigAlg,
+ byte[] signature)
+ {
+ return new X509Certificate(
+ new X509CertificateStructure(tbsCert, sigAlg, new DerBitString(signature)));
+ }
+
+ ///
+ /// Allows enumeration of the signature names supported by the generator.
+ ///
+ public IEnumerable SignatureAlgNames
+ {
+ get { return X509Utilities.GetAlgNames(); }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V3CertificateGenerator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V3CertificateGenerator.cs.meta
new file mode 100644
index 00000000..51287d94
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/X509V3CertificateGenerator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 6a3594cad87c9b4439139843a48e223c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/extension.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/extension.meta
new file mode 100644
index 00000000..66f95145
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/extension.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 26902280df03e254eb103b0cc513363f
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/extension/AuthorityKeyIdentifierStructure.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/extension/AuthorityKeyIdentifierStructure.cs
new file mode 100644
index 00000000..27d80f78
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/extension/AuthorityKeyIdentifierStructure.cs
@@ -0,0 +1,106 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Extension
+{
+ /// A high level authority key identifier.
+ public class AuthorityKeyIdentifierStructure
+ : AuthorityKeyIdentifier
+ {
+ /**
+ * Constructor which will take the byte[] returned from getExtensionValue()
+ *
+ * @param encodedValue a DER octet encoded string with the extension structure in it.
+ * @throws IOException on parsing errors.
+ */
+ // TODO Add a functional constructor from byte[]?
+ public AuthorityKeyIdentifierStructure(
+ Asn1OctetString encodedValue)
+ : base((Asn1Sequence) X509ExtensionUtilities.FromExtensionValue(encodedValue))
+ {
+ }
+
+ private static Asn1Sequence FromCertificate(
+ X509Certificate certificate)
+ {
+ try
+ {
+ GeneralName genName = new GeneralName(
+ PrincipalUtilities.GetIssuerX509Principal(certificate));
+
+ if (certificate.Version == 3)
+ {
+ Asn1OctetString ext = certificate.GetExtensionValue(X509Extensions.SubjectKeyIdentifier);
+
+ if (ext != null)
+ {
+ Asn1OctetString str = (Asn1OctetString) X509ExtensionUtilities.FromExtensionValue(ext);
+
+ return (Asn1Sequence) new AuthorityKeyIdentifier(
+ str.GetOctets(), new GeneralNames(genName), certificate.SerialNumber).ToAsn1Object();
+ }
+ }
+
+ SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(
+ certificate.GetPublicKey());
+
+ return (Asn1Sequence) new AuthorityKeyIdentifier(
+ info, new GeneralNames(genName), certificate.SerialNumber).ToAsn1Object();
+ }
+ catch (Exception e)
+ {
+ throw new CertificateParsingException("Exception extracting certificate details", e);
+ }
+ }
+
+ private static Asn1Sequence FromKey(
+ AsymmetricKeyParameter pubKey)
+ {
+ try
+ {
+ SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pubKey);
+
+ return (Asn1Sequence) new AuthorityKeyIdentifier(info).ToAsn1Object();
+ }
+ catch (Exception e)
+ {
+ throw new InvalidKeyException("can't process key: " + e);
+ }
+ }
+
+ /**
+ * Create an AuthorityKeyIdentifier using the passed in certificate's public
+ * key, issuer and serial number.
+ *
+ * @param certificate the certificate providing the information.
+ * @throws CertificateParsingException if there is a problem processing the certificate
+ */
+ public AuthorityKeyIdentifierStructure(
+ X509Certificate certificate)
+ : base(FromCertificate(certificate))
+ {
+ }
+
+ /**
+ * Create an AuthorityKeyIdentifier using just the hash of the
+ * public key.
+ *
+ * @param pubKey the key to generate the hash from.
+ * @throws InvalidKeyException if there is a problem using the key.
+ */
+ public AuthorityKeyIdentifierStructure(
+ AsymmetricKeyParameter pubKey)
+ : base(FromKey(pubKey))
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/extension/AuthorityKeyIdentifierStructure.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/extension/AuthorityKeyIdentifierStructure.cs.meta
new file mode 100644
index 00000000..f12de944
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/extension/AuthorityKeyIdentifierStructure.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: bb0f4335ed25d2a4a9fd365799fdd64a
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/extension/SubjectKeyIdentifierStructure.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/extension/SubjectKeyIdentifierStructure.cs
new file mode 100644
index 00000000..cfd8d4c0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/extension/SubjectKeyIdentifierStructure.cs
@@ -0,0 +1,53 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Extension
+{
+ /**
+ * A high level subject key identifier.
+ */
+ public class SubjectKeyIdentifierStructure
+ : SubjectKeyIdentifier
+ {
+ /**
+ * Constructor which will take the byte[] returned from getExtensionValue()
+ *
+ * @param encodedValue a DER octet encoded string with the extension structure in it.
+ * @throws IOException on parsing errors.
+ */
+ public SubjectKeyIdentifierStructure(
+ Asn1OctetString encodedValue)
+ : base((Asn1OctetString) X509ExtensionUtilities.FromExtensionValue(encodedValue))
+ {
+ }
+
+ private static Asn1OctetString FromPublicKey(
+ AsymmetricKeyParameter pubKey)
+ {
+ try
+ {
+ SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pubKey);
+
+ return (Asn1OctetString) new SubjectKeyIdentifier(info).ToAsn1Object();
+ }
+ catch (Exception e)
+ {
+ throw new CertificateParsingException("Exception extracting certificate details: " + e.ToString());
+ }
+ }
+
+ public SubjectKeyIdentifierStructure(
+ AsymmetricKeyParameter pubKey)
+ : base(FromPublicKey(pubKey))
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/extension/SubjectKeyIdentifierStructure.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/extension/SubjectKeyIdentifierStructure.cs.meta
new file mode 100644
index 00000000..d21d9e24
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/extension/SubjectKeyIdentifierStructure.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 004dfdf815abe524093ddfebf9234b73
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/extension/X509ExtensionUtil.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/extension/X509ExtensionUtil.cs
new file mode 100644
index 00000000..de059e76
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/extension/X509ExtensionUtil.cs
@@ -0,0 +1,95 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Security.Certificates;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Extension
+{
+ public class X509ExtensionUtilities
+ {
+ public static Asn1Object FromExtensionValue(
+ Asn1OctetString extensionValue)
+ {
+ return Asn1Object.FromByteArray(extensionValue.GetOctets());
+ }
+
+ public static ICollection GetIssuerAlternativeNames(
+ X509Certificate cert)
+ {
+ Asn1OctetString extVal = cert.GetExtensionValue(X509Extensions.IssuerAlternativeName);
+
+ return GetAlternativeName(extVal);
+ }
+
+ public static ICollection GetSubjectAlternativeNames(
+ X509Certificate cert)
+ {
+ Asn1OctetString extVal = cert.GetExtensionValue(X509Extensions.SubjectAlternativeName);
+
+ return GetAlternativeName(extVal);
+ }
+
+ private static ICollection GetAlternativeName(
+ Asn1OctetString extVal)
+ {
+ IList temp = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+
+ if (extVal != null)
+ {
+ try
+ {
+ Asn1Sequence seq = DerSequence.GetInstance(FromExtensionValue(extVal));
+
+ foreach (Asn1Encodable primName in seq)
+ {
+ IList list = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ GeneralName genName = GeneralName.GetInstance(primName);
+
+ list.Add(genName.TagNo);
+
+ switch (genName.TagNo)
+ {
+ case GeneralName.EdiPartyName:
+ case GeneralName.X400Address:
+ case GeneralName.OtherName:
+ list.Add(genName.Name.ToAsn1Object());
+ break;
+ case GeneralName.DirectoryName:
+ list.Add(X509Name.GetInstance(genName.Name).ToString());
+ break;
+ case GeneralName.DnsName:
+ case GeneralName.Rfc822Name:
+ case GeneralName.UniformResourceIdentifier:
+ list.Add(((IAsn1String)genName.Name).GetString());
+ break;
+ case GeneralName.RegisteredID:
+ list.Add(DerObjectIdentifier.GetInstance(genName.Name).Id);
+ break;
+ case GeneralName.IPAddress:
+ list.Add(DerOctetString.GetInstance(genName.Name).GetOctets());
+ break;
+ default:
+ throw new IOException("Bad tag number: " + genName.TagNo);
+ }
+
+ temp.Add(list);
+ }
+ }
+ catch (Exception e)
+ {
+ throw new CertificateParsingException(e.Message);
+ }
+ }
+
+ return temp;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/extension/X509ExtensionUtil.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/extension/X509ExtensionUtil.cs.meta
new file mode 100644
index 00000000..0435a514
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/extension/X509ExtensionUtil.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c1e9b9d84df723247b8211204f278332
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store.meta
new file mode 100644
index 00000000..4cb4dab6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 5b7983a5c52108d458439861101ff522
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/IX509Selector.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/IX509Selector.cs
new file mode 100644
index 00000000..e33824b5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/IX509Selector.cs
@@ -0,0 +1,19 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store
+{
+ public interface IX509Selector
+#if !(SILVERLIGHT || PORTABLE || NETFX_CORE)
+ : ICloneable
+#endif
+ {
+#if SILVERLIGHT || PORTABLE || NETFX_CORE
+ object Clone();
+#endif
+ bool Match(object obj);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/IX509Selector.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/IX509Selector.cs.meta
new file mode 100644
index 00000000..3aeedb70
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/IX509Selector.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 9ea6ae6bb5e274842b2a0eb9f889f24e
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/IX509Store.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/IX509Store.cs
new file mode 100644
index 00000000..b839b396
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/IX509Store.cs
@@ -0,0 +1,15 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store
+{
+ public interface IX509Store
+ {
+// void Init(IX509StoreParameters parameters);
+ ICollection GetMatches(IX509Selector selector);
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/IX509Store.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/IX509Store.cs.meta
new file mode 100644
index 00000000..96a2acf3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/IX509Store.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ea9951e0032af704bb0991a2df9a955f
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/IX509StoreParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/IX509StoreParameters.cs
new file mode 100644
index 00000000..90c06bbc
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/IX509StoreParameters.cs
@@ -0,0 +1,12 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store
+{
+ public interface IX509StoreParameters
+ {
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/IX509StoreParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/IX509StoreParameters.cs.meta
new file mode 100644
index 00000000..d8479906
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/IX509StoreParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: b0773463c26ca0540a74bb976fa32696
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/NoSuchStoreException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/NoSuchStoreException.cs
new file mode 100644
index 00000000..aff39e51
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/NoSuchStoreException.cs
@@ -0,0 +1,32 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store
+{
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class NoSuchStoreException
+ : X509StoreException
+ {
+ public NoSuchStoreException()
+ {
+ }
+
+ public NoSuchStoreException(
+ string message)
+ : base(message)
+ {
+ }
+
+ public NoSuchStoreException(
+ string message,
+ Exception e)
+ : base(message, e)
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/NoSuchStoreException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/NoSuchStoreException.cs.meta
new file mode 100644
index 00000000..2917b7ac
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/NoSuchStoreException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 01fab1b9163bc3e4e80d844d33d1f405
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509AttrCertStoreSelector.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509AttrCertStoreSelector.cs
new file mode 100644
index 00000000..ef0005ef
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509AttrCertStoreSelector.cs
@@ -0,0 +1,380 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.IO;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Date;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Extension;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store
+{
+ /**
+ * This class is an Selector like implementation to select
+ * attribute certificates from a given set of criteria.
+ *
+ * @see org.bouncycastle.x509.X509AttributeCertificate
+ * @see org.bouncycastle.x509.X509Store
+ */
+ public class X509AttrCertStoreSelector
+ : IX509Selector
+ {
+ // TODO: name constraints???
+
+ private IX509AttributeCertificate attributeCert;
+ private DateTimeObject attributeCertificateValid;
+ private AttributeCertificateHolder holder;
+ private AttributeCertificateIssuer issuer;
+ private BigInteger serialNumber;
+ private ISet targetNames = new HashSet();
+ private ISet targetGroups = new HashSet();
+
+ public X509AttrCertStoreSelector()
+ {
+ }
+
+ private X509AttrCertStoreSelector(
+ X509AttrCertStoreSelector o)
+ {
+ this.attributeCert = o.attributeCert;
+ this.attributeCertificateValid = o.attributeCertificateValid;
+ this.holder = o.holder;
+ this.issuer = o.issuer;
+ this.serialNumber = o.serialNumber;
+ this.targetGroups = new HashSet(o.targetGroups);
+ this.targetNames = new HashSet(o.targetNames);
+ }
+
+ ///
+ /// Decides if the given attribute certificate should be selected.
+ ///
+ /// The attribute certificate to be checked.
+ /// true if the object matches this selector.
+ public bool Match(
+ object obj)
+ {
+ if (obj == null)
+ throw new ArgumentNullException("obj");
+
+ IX509AttributeCertificate attrCert = obj as IX509AttributeCertificate;
+
+ if (attrCert == null)
+ return false;
+
+ if (this.attributeCert != null && !this.attributeCert.Equals(attrCert))
+ return false;
+
+ if (serialNumber != null && !attrCert.SerialNumber.Equals(serialNumber))
+ return false;
+
+ if (holder != null && !attrCert.Holder.Equals(holder))
+ return false;
+
+ if (issuer != null && !attrCert.Issuer.Equals(issuer))
+ return false;
+
+ if (attributeCertificateValid != null && !attrCert.IsValid(attributeCertificateValid.Value))
+ return false;
+
+ if (targetNames.Count > 0 || targetGroups.Count > 0)
+ {
+ Asn1OctetString targetInfoExt = attrCert.GetExtensionValue(
+ X509Extensions.TargetInformation);
+
+ if (targetInfoExt != null)
+ {
+ TargetInformation targetinfo;
+ try
+ {
+ targetinfo = TargetInformation.GetInstance(
+ X509ExtensionUtilities.FromExtensionValue(targetInfoExt));
+ }
+ catch (Exception)
+ {
+ return false;
+ }
+
+ Targets[] targetss = targetinfo.GetTargetsObjects();
+
+ if (targetNames.Count > 0)
+ {
+ bool found = false;
+
+ for (int i = 0; i < targetss.Length && !found; i++)
+ {
+ Target[] targets = targetss[i].GetTargets();
+
+ for (int j = 0; j < targets.Length; j++)
+ {
+ GeneralName targetName = targets[j].TargetName;
+
+ if (targetName != null && targetNames.Contains(targetName))
+ {
+ found = true;
+ break;
+ }
+ }
+ }
+ if (!found)
+ {
+ return false;
+ }
+ }
+
+ if (targetGroups.Count > 0)
+ {
+ bool found = false;
+
+ for (int i = 0; i < targetss.Length && !found; i++)
+ {
+ Target[] targets = targetss[i].GetTargets();
+
+ for (int j = 0; j < targets.Length; j++)
+ {
+ GeneralName targetGroup = targets[j].TargetGroup;
+
+ if (targetGroup != null && targetGroups.Contains(targetGroup))
+ {
+ found = true;
+ break;
+ }
+ }
+ }
+
+ if (!found)
+ {
+ return false;
+ }
+ }
+ }
+ }
+
+ return true;
+ }
+
+ public object Clone()
+ {
+ return new X509AttrCertStoreSelector(this);
+ }
+
+ /// The attribute certificate which must be matched.
+ /// If null is given, any will do.
+ public IX509AttributeCertificate AttributeCert
+ {
+ get { return attributeCert; }
+ set { this.attributeCert = value; }
+ }
+
+ [Obsolete("Use AttributeCertificateValid instead")]
+ public DateTimeObject AttribueCertificateValid
+ {
+ get { return attributeCertificateValid; }
+ set { this.attributeCertificateValid = value; }
+ }
+
+ /// The criteria for validity
+ /// If null is given any will do.
+ public DateTimeObject AttributeCertificateValid
+ {
+ get { return attributeCertificateValid; }
+ set { this.attributeCertificateValid = value; }
+ }
+
+ /// The holder.
+ /// If null is given any will do.
+ public AttributeCertificateHolder Holder
+ {
+ get { return holder; }
+ set { this.holder = value; }
+ }
+
+ /// The issuer.
+ /// If null is given any will do.
+ public AttributeCertificateIssuer Issuer
+ {
+ get { return issuer; }
+ set { this.issuer = value; }
+ }
+
+ /// The serial number.
+ /// If null is given any will do.
+ public BigInteger SerialNumber
+ {
+ get { return serialNumber; }
+ set { this.serialNumber = value; }
+ }
+
+ /**
+ * Adds a target name criterion for the attribute certificate to the target
+ * information extension criteria. The X509AttributeCertificate
+ * must contain at least one of the specified target names.
+ *
+ * Each attribute certificate may contain a target information extension
+ * limiting the servers where this attribute certificate can be used. If
+ * this extension is not present, the attribute certificate is not targeted
+ * and may be accepted by any server.
+ *
+ *
+ * @param name The name as a GeneralName (not null)
+ */
+ public void AddTargetName(
+ GeneralName name)
+ {
+ targetNames.Add(name);
+ }
+
+ /**
+ * Adds a target name criterion for the attribute certificate to the target
+ * information extension criteria. The X509AttributeCertificate
+ * must contain at least one of the specified target names.
+ *
+ * Each attribute certificate may contain a target information extension
+ * limiting the servers where this attribute certificate can be used. If
+ * this extension is not present, the attribute certificate is not targeted
+ * and may be accepted by any server.
+ *
+ *
+ * @param name a byte array containing the name in ASN.1 DER encoded form of a GeneralName
+ * @throws IOException if a parsing error occurs.
+ */
+ public void AddTargetName(
+ byte[] name)
+ {
+ AddTargetName(GeneralName.GetInstance(Asn1Object.FromByteArray(name)));
+ }
+
+ /**
+ * Adds a collection with target names criteria. If null is
+ * given any will do.
+ *
+ * The collection consists of either GeneralName objects or byte[] arrays representing
+ * DER encoded GeneralName structures.
+ *
+ *
+ * @param names A collection of target names.
+ * @throws IOException if a parsing error occurs.
+ * @see #AddTargetName(byte[])
+ * @see #AddTargetName(GeneralName)
+ */
+ public void SetTargetNames(
+ IEnumerable names)
+ {
+ targetNames = ExtractGeneralNames(names);
+ }
+
+ /**
+ * Gets the target names. The collection consists of Lists
+ * made up of an Integer in the first entry and a DER encoded
+ * byte array or a String in the second entry.
+ *
The returned collection is immutable.
+ *
+ * @return The collection of target names
+ * @see #setTargetNames(Collection)
+ */
+ public IEnumerable GetTargetNames()
+ {
+ return new EnumerableProxy(targetNames);
+ }
+
+ /**
+ * Adds a target group criterion for the attribute certificate to the target
+ * information extension criteria. The X509AttributeCertificate
+ * must contain at least one of the specified target groups.
+ *
+ * Each attribute certificate may contain a target information extension
+ * limiting the servers where this attribute certificate can be used. If
+ * this extension is not present, the attribute certificate is not targeted
+ * and may be accepted by any server.
+ *
+ *
+ * @param group The group as GeneralName form (not null)
+ */
+ public void AddTargetGroup(
+ GeneralName group)
+ {
+ targetGroups.Add(group);
+ }
+
+ /**
+ * Adds a target group criterion for the attribute certificate to the target
+ * information extension criteria. The X509AttributeCertificate
+ * must contain at least one of the specified target groups.
+ *
+ * Each attribute certificate may contain a target information extension
+ * limiting the servers where this attribute certificate can be used. If
+ * this extension is not present, the attribute certificate is not targeted
+ * and may be accepted by any server.
+ *
+ *
+ * @param name a byte array containing the group in ASN.1 DER encoded form of a GeneralName
+ * @throws IOException if a parsing error occurs.
+ */
+ public void AddTargetGroup(
+ byte[] name)
+ {
+ AddTargetGroup(GeneralName.GetInstance(Asn1Object.FromByteArray(name)));
+ }
+
+ /**
+ * Adds a collection with target groups criteria. If null is
+ * given any will do.
+ *
+ * The collection consists of GeneralName objects or byte[]
+ * representing DER encoded GeneralNames.
+ *
+ *
+ * @param names A collection of target groups.
+ * @throws IOException if a parsing error occurs.
+ * @see #AddTargetGroup(byte[])
+ * @see #AddTargetGroup(GeneralName)
+ */
+ public void SetTargetGroups(
+ IEnumerable names)
+ {
+ targetGroups = ExtractGeneralNames(names);
+ }
+
+ /**
+ * Gets the target groups. The collection consists of Lists
+ * made up of an Integer in the first entry and a DER encoded
+ * byte array or a String in the second entry.
+ *
The returned collection is immutable.
+ *
+ * @return The collection of target groups.
+ * @see #setTargetGroups(Collection)
+ */
+ public IEnumerable GetTargetGroups()
+ {
+ return new EnumerableProxy(targetGroups);
+ }
+
+ private ISet ExtractGeneralNames(
+ IEnumerable names)
+ {
+ ISet result = new HashSet();
+
+ if (names != null)
+ {
+ foreach (object o in names)
+ {
+ if (o is GeneralName)
+ {
+ result.Add(o);
+ }
+ else
+ {
+ result.Add(GeneralName.GetInstance(Asn1Object.FromByteArray((byte[]) o)));
+ }
+ }
+ }
+
+ return result;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509AttrCertStoreSelector.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509AttrCertStoreSelector.cs.meta
new file mode 100644
index 00000000..22ca0207
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509AttrCertStoreSelector.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 05a1711d73cac0449a5f694102783ad4
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CertPairStoreSelector.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CertPairStoreSelector.cs
new file mode 100644
index 00000000..f2a2687d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CertPairStoreSelector.cs
@@ -0,0 +1,96 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store
+{
+ ///
+ /// This class is an IX509Selector implementation to select
+ /// certificate pairs, which are e.g. used for cross certificates. The set of
+ /// criteria is given from two X509CertStoreSelector objects,
+ /// each of which, if present, must match the respective component of a pair.
+ ///
+ public class X509CertPairStoreSelector
+ : IX509Selector
+ {
+ private static X509CertStoreSelector CloneSelector(
+ X509CertStoreSelector s)
+ {
+ return s == null ? null : (X509CertStoreSelector) s.Clone();
+ }
+
+ private X509CertificatePair certPair;
+ private X509CertStoreSelector forwardSelector;
+ private X509CertStoreSelector reverseSelector;
+
+ public X509CertPairStoreSelector()
+ {
+ }
+
+ private X509CertPairStoreSelector(
+ X509CertPairStoreSelector o)
+ {
+ this.certPair = o.CertPair;
+ this.forwardSelector = o.ForwardSelector;
+ this.reverseSelector = o.ReverseSelector;
+ }
+
+ /// The certificate pair which is used for testing on equality.
+ public X509CertificatePair CertPair
+ {
+ get { return certPair; }
+ set { this.certPair = value; }
+ }
+
+ /// The certificate selector for the forward part.
+ public X509CertStoreSelector ForwardSelector
+ {
+ get { return CloneSelector(forwardSelector); }
+ set { this.forwardSelector = CloneSelector(value); }
+ }
+
+ /// The certificate selector for the reverse part.
+ public X509CertStoreSelector ReverseSelector
+ {
+ get { return CloneSelector(reverseSelector); }
+ set { this.reverseSelector = CloneSelector(value); }
+ }
+
+ ///
+ /// Decides if the given certificate pair should be selected. If
+ /// obj is not a X509CertificatePair, this method
+ /// returns false.
+ ///
+ /// The X509CertificatePair to be tested.
+ /// true if the object matches this selector.
+ public bool Match(
+ object obj)
+ {
+ if (obj == null)
+ throw new ArgumentNullException("obj");
+
+ X509CertificatePair pair = obj as X509CertificatePair;
+
+ if (pair == null)
+ return false;
+
+ if (certPair != null && !certPair.Equals(pair))
+ return false;
+
+ if (forwardSelector != null && !forwardSelector.Match(pair.Forward))
+ return false;
+
+ if (reverseSelector != null && !reverseSelector.Match(pair.Reverse))
+ return false;
+
+ return true;
+ }
+
+ public object Clone()
+ {
+ return new X509CertPairStoreSelector(this);
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CertPairStoreSelector.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CertPairStoreSelector.cs.meta
new file mode 100644
index 00000000..e6732f57
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CertPairStoreSelector.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 4b519c06b0ed0da4e8bca4f63037fea6
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CertStoreSelector.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CertStoreSelector.cs
new file mode 100644
index 00000000..936d9130
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CertStoreSelector.cs
@@ -0,0 +1,350 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Date;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Extension;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store
+{
+ public class X509CertStoreSelector
+ : IX509Selector
+ {
+ // TODO Missing criteria?
+
+ private byte[] authorityKeyIdentifier;
+ private int basicConstraints = -1;
+ private X509Certificate certificate;
+ private DateTimeObject certificateValid;
+ private ISet extendedKeyUsage;
+ private bool ignoreX509NameOrdering;
+ private X509Name issuer;
+ private bool[] keyUsage;
+ private ISet policy;
+ private DateTimeObject privateKeyValid;
+ private BigInteger serialNumber;
+ private X509Name subject;
+ private byte[] subjectKeyIdentifier;
+ private SubjectPublicKeyInfo subjectPublicKey;
+ private DerObjectIdentifier subjectPublicKeyAlgID;
+
+ public X509CertStoreSelector()
+ {
+ }
+
+ public X509CertStoreSelector(
+ X509CertStoreSelector o)
+ {
+ this.authorityKeyIdentifier = o.AuthorityKeyIdentifier;
+ this.basicConstraints = o.BasicConstraints;
+ this.certificate = o.Certificate;
+ this.certificateValid = o.CertificateValid;
+ this.extendedKeyUsage = o.ExtendedKeyUsage;
+ this.ignoreX509NameOrdering = o.IgnoreX509NameOrdering;
+ this.issuer = o.Issuer;
+ this.keyUsage = o.KeyUsage;
+ this.policy = o.Policy;
+ this.privateKeyValid = o.PrivateKeyValid;
+ this.serialNumber = o.SerialNumber;
+ this.subject = o.Subject;
+ this.subjectKeyIdentifier = o.SubjectKeyIdentifier;
+ this.subjectPublicKey = o.SubjectPublicKey;
+ this.subjectPublicKeyAlgID = o.SubjectPublicKeyAlgID;
+ }
+
+ public virtual object Clone()
+ {
+ return new X509CertStoreSelector(this);
+ }
+
+ public byte[] AuthorityKeyIdentifier
+ {
+ get { return Arrays.Clone(authorityKeyIdentifier); }
+ set { authorityKeyIdentifier = Arrays.Clone(value); }
+ }
+
+ public int BasicConstraints
+ {
+ get { return basicConstraints; }
+ set
+ {
+ if (value < -2)
+ throw new ArgumentException("value can't be less than -2", "value");
+
+ basicConstraints = value;
+ }
+ }
+
+ public X509Certificate Certificate
+ {
+ get { return certificate; }
+ set { this.certificate = value; }
+ }
+
+ public DateTimeObject CertificateValid
+ {
+ get { return certificateValid; }
+ set { certificateValid = value; }
+ }
+
+ public ISet ExtendedKeyUsage
+ {
+ get { return CopySet(extendedKeyUsage); }
+ set { extendedKeyUsage = CopySet(value); }
+ }
+
+ public bool IgnoreX509NameOrdering
+ {
+ get { return ignoreX509NameOrdering; }
+ set { this.ignoreX509NameOrdering = value; }
+ }
+
+ public X509Name Issuer
+ {
+ get { return issuer; }
+ set { issuer = value; }
+ }
+
+ [Obsolete("Avoid working with X509Name objects in string form")]
+ public string IssuerAsString
+ {
+ get { return issuer != null ? issuer.ToString() : null; }
+ }
+
+ public bool[] KeyUsage
+ {
+ get { return CopyBoolArray(keyUsage); }
+ set { keyUsage = CopyBoolArray(value); }
+ }
+
+ ///
+ /// An ISet of DerObjectIdentifier objects.
+ ///
+ public ISet Policy
+ {
+ get { return CopySet(policy); }
+ set { policy = CopySet(value); }
+ }
+
+ public DateTimeObject PrivateKeyValid
+ {
+ get { return privateKeyValid; }
+ set { privateKeyValid = value; }
+ }
+
+ public BigInteger SerialNumber
+ {
+ get { return serialNumber; }
+ set { serialNumber = value; }
+ }
+
+ public X509Name Subject
+ {
+ get { return subject; }
+ set { subject = value; }
+ }
+
+ [Obsolete("Avoid working with X509Name objects in string form")]
+ public string SubjectAsString
+ {
+ get { return subject != null ? subject.ToString() : null; }
+ }
+
+ public byte[] SubjectKeyIdentifier
+ {
+ get { return Arrays.Clone(subjectKeyIdentifier); }
+ set { subjectKeyIdentifier = Arrays.Clone(value); }
+ }
+
+ public SubjectPublicKeyInfo SubjectPublicKey
+ {
+ get { return subjectPublicKey; }
+ set { subjectPublicKey = value; }
+ }
+
+ public DerObjectIdentifier SubjectPublicKeyAlgID
+ {
+ get { return subjectPublicKeyAlgID; }
+ set { subjectPublicKeyAlgID = value; }
+ }
+
+ public virtual bool Match(
+ object obj)
+ {
+ X509Certificate c = obj as X509Certificate;
+
+ if (c == null)
+ return false;
+
+ if (!MatchExtension(authorityKeyIdentifier, c, X509Extensions.AuthorityKeyIdentifier))
+ return false;
+
+ if (basicConstraints != -1)
+ {
+ int bc = c.GetBasicConstraints();
+
+ if (basicConstraints == -2)
+ {
+ if (bc != -1)
+ return false;
+ }
+ else
+ {
+ if (bc < basicConstraints)
+ return false;
+ }
+ }
+
+ if (certificate != null && !certificate.Equals(c))
+ return false;
+
+ if (certificateValid != null && !c.IsValid(certificateValid.Value))
+ return false;
+
+ if (extendedKeyUsage != null)
+ {
+ IList eku = c.GetExtendedKeyUsage();
+
+ // Note: if no extended key usage set, all key purposes are implicitly allowed
+
+ if (eku != null)
+ {
+ foreach (DerObjectIdentifier oid in extendedKeyUsage)
+ {
+ if (!eku.Contains(oid.Id))
+ return false;
+ }
+ }
+ }
+
+ if (issuer != null && !issuer.Equivalent(c.IssuerDN, !ignoreX509NameOrdering))
+ return false;
+
+ if (keyUsage != null)
+ {
+ bool[] ku = c.GetKeyUsage();
+
+ // Note: if no key usage set, all key purposes are implicitly allowed
+
+ if (ku != null)
+ {
+ for (int i = 0; i < 9; ++i)
+ {
+ if (keyUsage[i] && !ku[i])
+ return false;
+ }
+ }
+ }
+
+ if (policy != null)
+ {
+ Asn1OctetString extVal = c.GetExtensionValue(X509Extensions.CertificatePolicies);
+ if (extVal == null)
+ return false;
+
+ Asn1Sequence certPolicies = Asn1Sequence.GetInstance(
+ X509ExtensionUtilities.FromExtensionValue(extVal));
+
+ if (policy.Count < 1 && certPolicies.Count < 1)
+ return false;
+
+ bool found = false;
+ foreach (PolicyInformation pi in certPolicies)
+ {
+ if (policy.Contains(pi.PolicyIdentifier))
+ {
+ found = true;
+ break;
+ }
+ }
+
+ if (!found)
+ return false;
+ }
+
+ if (privateKeyValid != null)
+ {
+ Asn1OctetString extVal = c.GetExtensionValue(X509Extensions.PrivateKeyUsagePeriod);
+ if (extVal == null)
+ return false;
+
+ PrivateKeyUsagePeriod pkup = PrivateKeyUsagePeriod.GetInstance(
+ X509ExtensionUtilities.FromExtensionValue(extVal));
+
+ DateTime dt = privateKeyValid.Value;
+ DateTime notAfter = pkup.NotAfter.ToDateTime();
+ DateTime notBefore = pkup.NotBefore.ToDateTime();
+
+ if (dt.CompareTo(notAfter) > 0 || dt.CompareTo(notBefore) < 0)
+ return false;
+ }
+
+ if (serialNumber != null && !serialNumber.Equals(c.SerialNumber))
+ return false;
+
+ if (subject != null && !subject.Equivalent(c.SubjectDN, !ignoreX509NameOrdering))
+ return false;
+
+ if (!MatchExtension(subjectKeyIdentifier, c, X509Extensions.SubjectKeyIdentifier))
+ return false;
+
+ if (subjectPublicKey != null && !subjectPublicKey.Equals(GetSubjectPublicKey(c)))
+ return false;
+
+ if (subjectPublicKeyAlgID != null
+ && !subjectPublicKeyAlgID.Equals(GetSubjectPublicKey(c).AlgorithmID))
+ return false;
+
+ return true;
+ }
+
+ internal static bool IssuersMatch(
+ X509Name a,
+ X509Name b)
+ {
+ return a == null ? b == null : a.Equivalent(b, true);
+ }
+
+ private static bool[] CopyBoolArray(
+ bool[] b)
+ {
+ return b == null ? null : (bool[]) b.Clone();
+ }
+
+ private static ISet CopySet(
+ ISet s)
+ {
+ return s == null ? null : new HashSet(s);
+ }
+
+ private static SubjectPublicKeyInfo GetSubjectPublicKey(
+ X509Certificate c)
+ {
+ return SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(c.GetPublicKey());
+ }
+
+ private static bool MatchExtension(
+ byte[] b,
+ X509Certificate c,
+ DerObjectIdentifier oid)
+ {
+ if (b == null)
+ return true;
+
+ Asn1OctetString extVal = c.GetExtensionValue(oid);
+
+ if (extVal == null)
+ return false;
+
+ return Arrays.AreEqual(b, extVal.GetOctets());
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CertStoreSelector.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CertStoreSelector.cs.meta
new file mode 100644
index 00000000..abdadd30
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CertStoreSelector.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 12b4022923dff834aa70b6c746f2e976
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CollectionStore.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CollectionStore.cs
new file mode 100644
index 00000000..79d680f7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CollectionStore.cs
@@ -0,0 +1,55 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store
+{
+ /**
+ * A simple collection backed store.
+ */
+ internal class X509CollectionStore
+ : IX509Store
+ {
+ private ICollection _local;
+
+ /**
+ * Basic constructor.
+ *
+ * @param collection - initial contents for the store, this is copied.
+ */
+ internal X509CollectionStore(
+ ICollection collection)
+ {
+ _local = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(collection);
+ }
+
+ /**
+ * Return the matches in the collection for the passed in selector.
+ *
+ * @param selector the selector to match against.
+ * @return a possibly empty collection of matching objects.
+ */
+ public ICollection GetMatches(
+ IX509Selector selector)
+ {
+ if (selector == null)
+ {
+ return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(_local);
+ }
+
+ IList result = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+ foreach (object obj in _local)
+ {
+ if (selector.Match(obj))
+ result.Add(obj);
+ }
+
+ return result;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CollectionStore.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CollectionStore.cs.meta
new file mode 100644
index 00000000..e5def697
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CollectionStore.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: c62d23a23e8e043429d9fdb60117aee8
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CollectionStoreParameters.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CollectionStoreParameters.cs
new file mode 100644
index 00000000..16d7abf0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CollectionStoreParameters.cs
@@ -0,0 +1,64 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+using System.Text;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store
+{
+ /// This class contains a collection for collection based X509Stores.
+ public class X509CollectionStoreParameters
+ : IX509StoreParameters
+ {
+ private readonly IList collection;
+
+ ///
+ /// Constructor.
+ ///
+ /// The collection is copied.
+ ///
+ ///
+ /// The collection containing X.509 object types.
+ /// If collection is null.
+ public X509CollectionStoreParameters(
+ ICollection collection)
+ {
+ if (collection == null)
+ throw new ArgumentNullException("collection");
+
+ this.collection = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(collection);
+ }
+
+ // TODO Do we need to be able to Clone() these, and should it really be shallow?
+// /**
+// * Returns a shallow clone. The returned contents are not copied, so adding
+// * or removing objects will effect this.
+// *
+// * @return a shallow clone.
+// */
+// public object Clone()
+// {
+// return new X509CollectionStoreParameters(collection);
+// }
+
+ /// Returns a copy of the ICollection.
+ public ICollection GetCollection()
+ {
+ return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(collection);
+ }
+
+ /// Returns a formatted string describing the parameters.
+ public override string ToString()
+ {
+ StringBuilder sb = new StringBuilder();
+ sb.Append("X509CollectionStoreParameters: [\n");
+ sb.Append(" collection: " + collection + "\n");
+ sb.Append("]");
+ return sb.ToString();
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CollectionStoreParameters.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CollectionStoreParameters.cs.meta
new file mode 100644
index 00000000..d48c033d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CollectionStoreParameters.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: e09969b5dbb57ba4f89c0de6827cd0e3
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CrlStoreSelector.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CrlStoreSelector.cs
new file mode 100644
index 00000000..725967b9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CrlStoreSelector.cs
@@ -0,0 +1,287 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Date;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Extension;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store
+{
+ public class X509CrlStoreSelector
+ : IX509Selector
+ {
+ // TODO Missing criteria?
+
+ private X509Certificate certificateChecking;
+ private DateTimeObject dateAndTime;
+ private ICollection issuers;
+ private BigInteger maxCrlNumber;
+ private BigInteger minCrlNumber;
+
+ private IX509AttributeCertificate attrCertChecking;
+ private bool completeCrlEnabled;
+ private bool deltaCrlIndicatorEnabled;
+ private byte[] issuingDistributionPoint;
+ private bool issuingDistributionPointEnabled;
+ private BigInteger maxBaseCrlNumber;
+
+ public X509CrlStoreSelector()
+ {
+ }
+
+ public X509CrlStoreSelector(
+ X509CrlStoreSelector o)
+ {
+ this.certificateChecking = o.CertificateChecking;
+ this.dateAndTime = o.DateAndTime;
+ this.issuers = o.Issuers;
+ this.maxCrlNumber = o.MaxCrlNumber;
+ this.minCrlNumber = o.MinCrlNumber;
+
+ this.deltaCrlIndicatorEnabled = o.DeltaCrlIndicatorEnabled;
+ this.completeCrlEnabled = o.CompleteCrlEnabled;
+ this.maxBaseCrlNumber = o.MaxBaseCrlNumber;
+ this.attrCertChecking = o.AttrCertChecking;
+ this.issuingDistributionPointEnabled = o.IssuingDistributionPointEnabled;
+ this.issuingDistributionPoint = o.IssuingDistributionPoint;
+ }
+
+ public virtual object Clone()
+ {
+ return new X509CrlStoreSelector(this);
+ }
+
+ public X509Certificate CertificateChecking
+ {
+ get { return certificateChecking; }
+ set { certificateChecking = value; }
+ }
+
+ public DateTimeObject DateAndTime
+ {
+ get { return dateAndTime; }
+ set { dateAndTime = value; }
+ }
+
+ ///
+ /// An ICollection of X509Name objects
+ ///
+ public ICollection Issuers
+ {
+ get { return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(issuers); }
+ set { issuers = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(value); }
+ }
+
+ public BigInteger MaxCrlNumber
+ {
+ get { return maxCrlNumber; }
+ set { maxCrlNumber = value; }
+ }
+
+ public BigInteger MinCrlNumber
+ {
+ get { return minCrlNumber; }
+ set { minCrlNumber = value; }
+ }
+
+ /**
+ * The attribute certificate being checked. This is not a criterion.
+ * Rather, it is optional information that may help a {@link X509Store} find
+ * CRLs that would be relevant when checking revocation for the specified
+ * attribute certificate. If null is specified, then no such
+ * optional information is provided.
+ *
+ * @param attrCert the IX509AttributeCertificate being checked (or
+ * null)
+ * @see #getAttrCertificateChecking()
+ */
+ public IX509AttributeCertificate AttrCertChecking
+ {
+ get { return attrCertChecking; }
+ set { this.attrCertChecking = value; }
+ }
+
+ /**
+ * If true only complete CRLs are returned. Defaults to
+ * false.
+ *
+ * @return true if only complete CRLs are returned.
+ */
+ public bool CompleteCrlEnabled
+ {
+ get { return completeCrlEnabled; }
+ set { this.completeCrlEnabled = value; }
+ }
+
+ /**
+ * Returns if this selector must match CRLs with the delta CRL indicator
+ * extension set. Defaults to false.
+ *
+ * @return Returns true if only CRLs with the delta CRL
+ * indicator extension are selected.
+ */
+ public bool DeltaCrlIndicatorEnabled
+ {
+ get { return deltaCrlIndicatorEnabled; }
+ set { this.deltaCrlIndicatorEnabled = value; }
+ }
+
+ /**
+ * The issuing distribution point.
+ *
+ * The issuing distribution point extension is a CRL extension which
+ * identifies the scope and the distribution point of a CRL. The scope
+ * contains among others information about revocation reasons contained in
+ * the CRL. Delta CRLs and complete CRLs must have matching issuing
+ * distribution points.
+ *
+ * The byte array is cloned to protect against subsequent modifications.
+ *
+ * You must also enable or disable this criteria with
+ * {@link #setIssuingDistributionPointEnabled(bool)}.
+ *
+ * @param issuingDistributionPoint The issuing distribution point to set.
+ * This is the DER encoded OCTET STRING extension value.
+ * @see #getIssuingDistributionPoint()
+ */
+ public byte[] IssuingDistributionPoint
+ {
+ get { return Arrays.Clone(issuingDistributionPoint); }
+ set { this.issuingDistributionPoint = Arrays.Clone(value); }
+ }
+
+ /**
+ * Whether the issuing distribution point criteria should be applied.
+ * Defaults to false.
+ *
+ * You may also set the issuing distribution point criteria if not a missing
+ * issuing distribution point should be assumed.
+ *
+ * @return Returns if the issuing distribution point check is enabled.
+ */
+ public bool IssuingDistributionPointEnabled
+ {
+ get { return issuingDistributionPointEnabled; }
+ set { this.issuingDistributionPointEnabled = value; }
+ }
+
+ /**
+ * The maximum base CRL number. Defaults to null.
+ *
+ * @return Returns the maximum base CRL number.
+ * @see #setMaxBaseCRLNumber(BigInteger)
+ */
+ public BigInteger MaxBaseCrlNumber
+ {
+ get { return maxBaseCrlNumber; }
+ set { this.maxBaseCrlNumber = value; }
+ }
+
+ public virtual bool Match(
+ object obj)
+ {
+ X509Crl c = obj as X509Crl;
+
+ if (c == null)
+ return false;
+
+ if (dateAndTime != null)
+ {
+ DateTime dt = dateAndTime.Value;
+ DateTime tu = c.ThisUpdate;
+ DateTimeObject nu = c.NextUpdate;
+
+ if (dt.CompareTo(tu) < 0 || nu == null || dt.CompareTo(nu.Value) >= 0)
+ return false;
+ }
+
+ if (issuers != null)
+ {
+ X509Name i = c.IssuerDN;
+
+ bool found = false;
+
+ foreach (X509Name issuer in issuers)
+ {
+ if (issuer.Equivalent(i, true))
+ {
+ found = true;
+ break;
+ }
+ }
+
+ if (!found)
+ return false;
+ }
+
+ if (maxCrlNumber != null || minCrlNumber != null)
+ {
+ Asn1OctetString extVal = c.GetExtensionValue(X509Extensions.CrlNumber);
+ if (extVal == null)
+ return false;
+
+ BigInteger cn = CrlNumber.GetInstance(
+ X509ExtensionUtilities.FromExtensionValue(extVal)).PositiveValue;
+
+ if (maxCrlNumber != null && cn.CompareTo(maxCrlNumber) > 0)
+ return false;
+
+ if (minCrlNumber != null && cn.CompareTo(minCrlNumber) < 0)
+ return false;
+ }
+
+ DerInteger dci = null;
+ try
+ {
+ Asn1OctetString bytes = c.GetExtensionValue(X509Extensions.DeltaCrlIndicator);
+ if (bytes != null)
+ {
+ dci = DerInteger.GetInstance(X509ExtensionUtilities.FromExtensionValue(bytes));
+ }
+ }
+ catch (Exception)
+ {
+ return false;
+ }
+
+ if (dci == null)
+ {
+ if (DeltaCrlIndicatorEnabled)
+ return false;
+ }
+ else
+ {
+ if (CompleteCrlEnabled)
+ return false;
+
+ if (maxBaseCrlNumber != null && dci.PositiveValue.CompareTo(maxBaseCrlNumber) > 0)
+ return false;
+ }
+
+ if (issuingDistributionPointEnabled)
+ {
+ Asn1OctetString idp = c.GetExtensionValue(X509Extensions.IssuingDistributionPoint);
+ if (issuingDistributionPoint == null)
+ {
+ if (idp != null)
+ return false;
+ }
+ else
+ {
+ if (!Arrays.AreEqual(idp.GetOctets(), issuingDistributionPoint))
+ return false;
+ }
+ }
+
+ return true;
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CrlStoreSelector.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CrlStoreSelector.cs.meta
new file mode 100644
index 00000000..2fda8c23
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509CrlStoreSelector.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: d8a2c8ce56d49414a89fd32d343d68c2
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509StoreException.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509StoreException.cs
new file mode 100644
index 00000000..39aeae96
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509StoreException.cs
@@ -0,0 +1,32 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+using System;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store
+{
+#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE)
+ [Serializable]
+#endif
+ public class X509StoreException
+ : Exception
+ {
+ public X509StoreException()
+ {
+ }
+
+ public X509StoreException(
+ string message)
+ : base(message)
+ {
+ }
+
+ public X509StoreException(
+ string message,
+ Exception e)
+ : base(message, e)
+ {
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509StoreException.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509StoreException.cs.meta
new file mode 100644
index 00000000..5cf72e03
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509StoreException.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ae4da7235cd49c4479cc07619ce3e51e
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509StoreFactory.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509StoreFactory.cs
new file mode 100644
index 00000000..03eba431
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509StoreFactory.cs
@@ -0,0 +1,69 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+#if UNITY_WSA && !UNITY_EDITOR && !ENABLE_IL2CPP
+using System.TypeFix;
+#endif
+using System;
+using System.Collections;
+
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store
+{
+ public sealed class X509StoreFactory
+ {
+ private X509StoreFactory()
+ {
+ }
+
+ public static IX509Store Create(
+ string type,
+ IX509StoreParameters parameters)
+ {
+ if (type == null)
+ throw new ArgumentNullException("type");
+
+ string[] parts = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(type).Split('/');
+
+ if (parts.Length < 2)
+ throw new ArgumentException("type");
+
+ if (parts[1] != "COLLECTION")
+ throw new NoSuchStoreException("X.509 store type '" + type + "' not available.");
+
+ X509CollectionStoreParameters p = (X509CollectionStoreParameters) parameters;
+ ICollection coll = p.GetCollection();
+
+ switch (parts[0])
+ {
+ case "ATTRIBUTECERTIFICATE":
+ checkCorrectType(coll, typeof(IX509AttributeCertificate));
+ break;
+ case "CERTIFICATE":
+ checkCorrectType(coll, typeof(X509Certificate));
+ break;
+ case "CERTIFICATEPAIR":
+ checkCorrectType(coll, typeof(X509CertificatePair));
+ break;
+ case "CRL":
+ checkCorrectType(coll, typeof(X509Crl));
+ break;
+ default:
+ throw new NoSuchStoreException("X.509 store type '" + type + "' not available.");
+ }
+
+ return new X509CollectionStore(coll);
+ }
+
+ private static void checkCorrectType(ICollection coll, Type t)
+ {
+ foreach (object o in coll)
+ {
+ if (!t.IsInstanceOfType(o))
+ throw new InvalidCastException("Can't cast object to type: " + t.FullName);
+ }
+ }
+ }
+}
+#pragma warning restore
+#endif
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509StoreFactory.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509StoreFactory.cs.meta
new file mode 100644
index 00000000..f60d9498
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SecureProtocol/x509/store/X509StoreFactory.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 7fe5a804c6168c344a5147f544de5a2f
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/ServerSentEvents.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/ServerSentEvents.meta
new file mode 100644
index 00000000..628329f9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/ServerSentEvents.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: c39b33f2c686550498ca5741c9e33690
+folderAsset: yes
+DefaultImporter:
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/ServerSentEvents/EventSource.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/ServerSentEvents/EventSource.cs
new file mode 100644
index 00000000..d3653cb3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/ServerSentEvents/EventSource.cs
@@ -0,0 +1,649 @@
+#if !BESTHTTP_DISABLE_SERVERSENT_EVENTS
+
+using System;
+using System.Collections.Generic;
+
+using BestHTTP.Extensions;
+
+#if UNITY_WEBGL && !UNITY_EDITOR
+ using System.Runtime.InteropServices;
+#endif
+
+namespace BestHTTP.ServerSentEvents
+{
+ ///
+ /// Possible states of an EventSource object.
+ ///
+ public enum States
+ {
+ Initial,
+ Connecting,
+ Open,
+ Retrying,
+ Closing,
+ Closed
+ }
+
+ public delegate void OnGeneralEventDelegate(EventSource eventSource);
+ public delegate void OnMessageDelegate(EventSource eventSource, BestHTTP.ServerSentEvents.Message message);
+ public delegate void OnErrorDelegate(EventSource eventSource, string error);
+ public delegate bool OnRetryDelegate(EventSource eventSource);
+ public delegate void OnEventDelegate(EventSource eventSource, BestHTTP.ServerSentEvents.Message message);
+ public delegate void OnStateChangedDelegate(EventSource eventSource, States oldState, States newState);
+
+#if UNITY_WEBGL && !UNITY_EDITOR
+
+ delegate void OnWebGLEventSourceOpenDelegate(uint id);
+ delegate void OnWebGLEventSourceMessageDelegate(uint id, string eventStr, string data, string eventId, int retry);
+ delegate void OnWebGLEventSourceErrorDelegate(uint id, string reason);
+#endif
+
+ ///
+ /// http://www.w3.org/TR/eventsource/
+ ///
+ public class EventSource
+#if !UNITY_WEBGL || UNITY_EDITOR
+ : IHeartbeat
+#endif
+ {
+#region Public Properties
+
+ ///
+ /// Uri of the remote endpoint.
+ ///
+ public Uri Uri { get; private set; }
+
+ ///
+ /// Current state of the EventSource object.
+ ///
+ public States State
+ {
+ get
+ {
+ return _state;
+ }
+ private set
+ {
+ States oldState = _state;
+ _state = value;
+
+ if (OnStateChanged != null)
+ {
+ try
+ {
+ OnStateChanged(this, oldState, _state);
+ }
+ catch(Exception ex)
+ {
+ HTTPManager.Logger.Exception("EventSource", "OnStateChanged", ex);
+ }
+ }
+ }
+ }
+ private States _state;
+
+ ///
+ /// Time to wait to do a reconnect attempt. Default to 2 sec. The server can overwrite this setting.
+ ///
+ public TimeSpan ReconnectionTime { get; set; }
+
+ ///
+ /// The last successfully received event's id.
+ ///
+ public string LastEventId { get; private set; }
+
+#if !UNITY_WEBGL || UNITY_EDITOR
+ ///
+ /// The internal request object of the EventSource.
+ ///
+ public HTTPRequest InternalRequest { get; private set; }
+#else
+ public bool WithCredentials { get; set; }
+#endif
+
+#endregion
+
+#region Public Events
+
+ ///
+ /// Called when successfully connected to the server.
+ ///
+ public event OnGeneralEventDelegate OnOpen;
+
+ ///
+ /// Called on every message received from the server.
+ ///
+ public event OnMessageDelegate OnMessage;
+
+ ///
+ /// Called when an error occurs.
+ ///
+ public event OnErrorDelegate OnError;
+
+#if !UNITY_WEBGL || UNITY_EDITOR
+ ///
+ /// Called when the EventSource will try to do a retry attempt. If this function returns with false, it will cancel the attempt.
+ ///
+ public event OnRetryDelegate OnRetry;
+#endif
+
+ ///
+ /// Called when the EventSource object closed.
+ ///
+ public event OnGeneralEventDelegate OnClosed;
+
+ ///
+ /// Called every time when the State property changed.
+ ///
+ public event OnStateChangedDelegate OnStateChanged;
+
+#endregion
+
+#region Privates
+
+ ///
+ /// A dictionary to store eventName => delegate mapping.
+ ///
+ private Dictionary EventTable;
+
+#if !UNITY_WEBGL || UNITY_EDITOR
+ ///
+ /// Number of retry attempts made.
+ ///
+ private byte RetryCount;
+
+ ///
+ /// When we called the Retry function. We will delay the Open call from here.
+ ///
+ private DateTime RetryCalled;
+#else
+ private static Dictionary EventSources = new Dictionary();
+ private uint Id;
+#endif
+
+#endregion
+
+ public EventSource(Uri uri)
+ {
+ this.Uri = uri;
+ this.ReconnectionTime = TimeSpan.FromMilliseconds(2000);
+
+#if !UNITY_WEBGL || UNITY_EDITOR
+ this.InternalRequest = new HTTPRequest(Uri, HTTPMethods.Get, true, true, OnRequestFinished);
+
+ // Set headers
+ this.InternalRequest.SetHeader("Accept", "text/event-stream");
+ this.InternalRequest.SetHeader("Cache-Control", "no-cache");
+ this.InternalRequest.SetHeader("Accept-Encoding", "identity");
+
+ // Set protocol stuff
+ this.InternalRequest.ProtocolHandler = SupportedProtocols.ServerSentEvents;
+ this.InternalRequest.OnUpgraded = OnUpgraded;
+
+ // Disable internal retry
+ this.InternalRequest.DisableRetry = true;
+#else
+ if (!ES_IsSupported())
+ throw new NotSupportedException("This browser isn't support the EventSource protocol!");
+
+ this.Id = ES_Create(this.Uri.ToString(), WithCredentials, OnOpenCallback, OnMessageCallback, OnErrorCallback);
+
+ EventSources.Add(this.Id, this);
+#endif
+ }
+
+#region Public Functions
+
+ ///
+ /// Start to connect to the remote server.
+ ///
+ public void Open()
+ {
+ if (this.State != States.Initial &&
+ this.State != States.Retrying &&
+ this.State != States.Closed)
+ return;
+
+ this.State = States.Connecting;
+
+#if !UNITY_WEBGL || UNITY_EDITOR
+ if (!string.IsNullOrEmpty(this.LastEventId))
+ this.InternalRequest.SetHeader("Last-Event-ID", this.LastEventId);
+
+ this.InternalRequest.Send();
+#endif
+ }
+
+ ///
+ /// Start to close the connection.
+ ///
+ public void Close()
+ {
+ if (this.State == States.Closing ||
+ this.State == States.Closed)
+ return;
+
+ this.State = States.Closing;
+#if !UNITY_WEBGL || UNITY_EDITOR
+ if (this.InternalRequest != null)
+ this.InternalRequest.Abort();
+ else
+ this.State = States.Closed;
+#else
+ ES_Close(this.Id);
+
+ SetClosed("Close");
+
+ EventSources.Remove(this.Id);
+
+ ES_Release(this.Id);
+#endif
+ }
+
+ ///
+ /// With this function an event handler can be subscribed for an event name.
+ ///
+ public void On(string eventName, OnEventDelegate action)
+ {
+ if (EventTable == null)
+ EventTable = new Dictionary();
+
+ EventTable[eventName] = action;
+#if UNITY_WEBGL && !UNITY_EDITOR
+ ES_AddEventHandler(this.Id, eventName);
+#endif
+ }
+
+ ///
+ /// With this function the event handler can be removed for the given event name.
+ ///
+ ///
+ public void Off(string eventName)
+ {
+ if (eventName == null || EventTable == null)
+ return;
+
+ EventTable.Remove(eventName);
+ }
+
+#endregion
+
+#region Private Helper Functions
+
+ private void CallOnError(string error, string msg)
+ {
+ if (OnError != null)
+ {
+ try
+ {
+ OnError(this, error);
+ }
+ catch (Exception ex)
+ {
+ HTTPManager.Logger.Exception("EventSource", msg + " - OnError", ex);
+ }
+ }
+ }
+
+#if !UNITY_WEBGL || UNITY_EDITOR
+ private bool CallOnRetry()
+ {
+ if (OnRetry != null)
+ {
+ try
+ {
+ return OnRetry(this);
+ }
+ catch(Exception ex)
+ {
+ HTTPManager.Logger.Exception("EventSource", "CallOnRetry", ex);
+ }
+ }
+
+ return true;
+ }
+#endif
+
+ private void SetClosed(string msg)
+ {
+ this.State = States.Closed;
+
+ if (OnClosed != null)
+ {
+ try
+ {
+ OnClosed(this);
+ }
+ catch (Exception ex)
+ {
+ HTTPManager.Logger.Exception("EventSource", msg + " - OnClosed", ex);
+ }
+ }
+ }
+
+#if !UNITY_WEBGL || UNITY_EDITOR
+ private void Retry()
+ {
+ if (RetryCount > 0 ||
+ !CallOnRetry())
+ {
+ SetClosed("Retry");
+ return;
+ }
+
+ RetryCount++;
+ RetryCalled = DateTime.UtcNow;
+
+ HTTPManager.Heartbeats.Subscribe(this);
+
+ this.State = States.Retrying;
+ }
+#endif
+
+#endregion
+
+#region HTTP Request Implementation
+#if !UNITY_WEBGL || UNITY_EDITOR
+
+ ///
+ /// We are successfully upgraded to the EventSource protocol, we can start to receive and parse the incoming data.
+ ///
+ private void OnUpgraded(HTTPRequest originalRequest, HTTPResponse response)
+ {
+ EventSourceResponse esResponse = response as EventSourceResponse;
+
+ if (esResponse == null)
+ {
+ CallOnError("Not an EventSourceResponse!", "OnUpgraded");
+ return;
+ }
+
+ if (OnOpen != null)
+ {
+ try
+ {
+ OnOpen(this);
+ }
+ catch (Exception ex)
+ {
+ HTTPManager.Logger.Exception("EventSource", "OnOpen", ex);
+ }
+ }
+
+ esResponse.OnMessage += OnMessageReceived;
+ esResponse.StartReceive();
+
+ this.RetryCount = 0;
+ this.State = States.Open;
+ }
+
+ private void OnRequestFinished(HTTPRequest req, HTTPResponse resp)
+ {
+ if (this.State == States.Closed)
+ return;
+
+ if (this.State == States.Closing ||
+ req.State == HTTPRequestStates.Aborted)
+ {
+ SetClosed("OnRequestFinished");
+
+ return;
+ }
+
+ string reason = string.Empty;
+
+ // In some cases retry is prohibited
+ bool canRetry = true;
+
+ switch (req.State)
+ {
+ // The server sent all the data it's wanted.
+ case HTTPRequestStates.Processing:
+ canRetry = !resp.HasHeader("content-length");
+ break;
+
+ // The request finished without any problem.
+ case HTTPRequestStates.Finished:
+ // HTTP 200 OK responses that have a Content-Type specifying an unsupported type, or that have no Content-Type at all, must cause the user agent to fail the connection.
+ if (resp.StatusCode == 200 && !resp.HasHeaderWithValue("content-type", "text/event-stream"))
+ {
+ reason = "No Content-Type header with value 'text/event-stream' present.";
+ canRetry = false;
+ }
+
+ // HTTP 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable, and 504 Gateway Timeout responses, and any network error that prevents the connection
+ // from being established in the first place (e.g. DNS errors), must cause the user agent to asynchronously reestablish the connection.
+ // Any other HTTP response code not listed here must cause the user agent to fail the connection.
+ if (canRetry &&
+ resp.StatusCode != 500 &&
+ resp.StatusCode != 502 &&
+ resp.StatusCode != 503 &&
+ resp.StatusCode != 504)
+ {
+ canRetry = false;
+
+ reason = string.Format("Request Finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
+ resp.StatusCode,
+ resp.Message,
+ resp.DataAsText);
+ }
+ break;
+
+ // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
+ case HTTPRequestStates.Error:
+ reason = "Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception");
+ break;
+
+ // The request aborted, initiated by the user.
+ case HTTPRequestStates.Aborted:
+ // If the state is Closing, then it's a normal behaviour, and we close the EventSource
+ reason = "OnRequestFinished - Aborted without request. EventSource's State: " + this.State;
+ break;
+
+ // Connecting to the server is timed out.
+ case HTTPRequestStates.ConnectionTimedOut:
+ reason = "Connection Timed Out!";
+ break;
+
+ // The request didn't finished in the given time.
+ case HTTPRequestStates.TimedOut:
+ reason = "Processing the request Timed Out!";
+ break;
+ }
+
+ // If we are not closing the EventSource, then we will try to reconnect.
+ if (this.State < States.Closing)
+ {
+ if (!string.IsNullOrEmpty(reason))
+ CallOnError(reason, "OnRequestFinished");
+
+ if (canRetry)
+ Retry();
+ else
+ SetClosed("OnRequestFinished");
+ }
+ else
+ SetClosed("OnRequestFinished");
+ }
+#endif
+#endregion
+
+#region EventStreamResponse Event Handlers
+
+ private void OnMessageReceived(
+#if !UNITY_WEBGL || UNITY_EDITOR
+ EventSourceResponse resp,
+#endif
+ BestHTTP.ServerSentEvents.Message message)
+ {
+ if (this.State >= States.Closing)
+ return;
+
+ // 1.) Set the last event ID string of the event source to value of the last event ID buffer.
+ // The buffer does not get reset, so the last event ID string of the event source remains set to this value until the next time it is set by the server.
+ // We check here only for null, because it can be a non-null but empty string.
+ if (message.Id != null)
+ this.LastEventId = message.Id;
+
+ if (message.Retry.TotalMilliseconds > 0)
+ this.ReconnectionTime = message.Retry;
+
+ // 2.) If the data buffer is an empty string, set the data buffer and the event type buffer to the empty string and abort these steps.
+ if (string.IsNullOrEmpty(message.Data))
+ return;
+
+ // 3.) If the data buffer's last character is a U+000A LINE FEED (LF) character, then remove the last character from the data buffer.
+ // This step can be ignored. We constructed the string to be able to skip this step.
+
+ if (OnMessage != null)
+ {
+ try
+ {
+ OnMessage(this, message);
+ }
+ catch (Exception ex)
+ {
+ HTTPManager.Logger.Exception("EventSource", "OnMessageReceived - OnMessage", ex);
+ }
+ }
+
+ if (EventTable != null && !string.IsNullOrEmpty(message.Event))
+ {
+ OnEventDelegate action;
+ if (EventTable.TryGetValue(message.Event, out action))
+ {
+ if (action != null)
+ {
+ try
+ {
+ action(this, message);
+ }
+ catch(Exception ex)
+ {
+ HTTPManager.Logger.Exception("EventSource", "OnMessageReceived - action", ex);
+ }
+ }
+ }
+ }
+ }
+
+#endregion
+
+#region IHeartbeat Implementation
+#if !UNITY_WEBGL || UNITY_EDITOR
+
+ void IHeartbeat.OnHeartbeatUpdate(TimeSpan dif)
+ {
+ if (this.State != States.Retrying)
+ {
+ HTTPManager.Heartbeats.Unsubscribe(this);
+
+ return;
+ }
+
+ if (DateTime.UtcNow - RetryCalled >= ReconnectionTime)
+ {
+ Open();
+
+ if (this.State != States.Connecting)
+ SetClosed("OnHeartbeatUpdate");
+
+ HTTPManager.Heartbeats.Unsubscribe(this);
+ }
+ }
+#endif
+#endregion
+
+#region WebGL Static Callbacks
+#if UNITY_WEBGL && !UNITY_EDITOR
+
+ [AOT.MonoPInvokeCallback(typeof(OnWebGLEventSourceOpenDelegate))]
+ static void OnOpenCallback(uint id)
+ {
+ EventSource es;
+ if (EventSources.TryGetValue(id, out es))
+ {
+ if (es.OnOpen != null)
+ {
+ try
+ {
+ es.OnOpen(es);
+ }
+ catch(Exception ex)
+ {
+ HTTPManager.Logger.Exception("EventSource", "OnOpen", ex);
+ }
+ }
+
+ es.State = States.Open;
+ }
+ else
+ HTTPManager.Logger.Warning("EventSource", "OnOpenCallback - No EventSource found for id: " + id.ToString());
+ }
+
+ [AOT.MonoPInvokeCallback(typeof(OnWebGLEventSourceMessageDelegate))]
+ static void OnMessageCallback(uint id, string eventStr, string data, string eventId, int retry)
+ {
+ EventSource es;
+ if (EventSources.TryGetValue(id, out es))
+ {
+ var msg = new BestHTTP.ServerSentEvents.Message();
+ msg.Id = eventId;
+ msg.Data = data;
+ msg.Event = eventStr;
+ msg.Retry = TimeSpan.FromSeconds(retry);
+
+ es.OnMessageReceived(msg);
+ }
+ }
+
+ [AOT.MonoPInvokeCallback(typeof(OnWebGLEventSourceErrorDelegate))]
+ static void OnErrorCallback(uint id, string reason)
+ {
+ EventSource es;
+ if (EventSources.TryGetValue(id, out es))
+ {
+ es.CallOnError(reason, "OnErrorCallback");
+ es.SetClosed("OnError");
+
+ EventSources.Remove(id);
+ }
+
+ try
+ {
+ ES_Release(id);
+ }
+ catch (Exception ex)
+ {
+ HTTPManager.Logger.Exception("EventSource", "ES_Release", ex);
+ }
+ }
+
+#endif
+#endregion
+
+#region WebGL Interface
+#if UNITY_WEBGL && !UNITY_EDITOR
+
+ [DllImport("__Internal")]
+ static extern bool ES_IsSupported();
+
+ [DllImport("__Internal")]
+ static extern uint ES_Create(string url, bool withCred, OnWebGLEventSourceOpenDelegate onOpen, OnWebGLEventSourceMessageDelegate onMessage, OnWebGLEventSourceErrorDelegate onError);
+
+ [DllImport("__Internal")]
+ static extern void ES_AddEventHandler(uint id, string eventName);
+
+ [DllImport("__Internal")]
+ static extern void ES_Close(uint id);
+
+ [DllImport("__Internal")]
+ static extern void ES_Release(uint id);
+
+#endif
+#endregion
+
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/ServerSentEvents/EventSource.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/ServerSentEvents/EventSource.cs.meta
new file mode 100644
index 00000000..6a2ba68b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/ServerSentEvents/EventSource.cs.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: 49e4cc3acf485d644887e96e5a2d1219
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/ServerSentEvents/EventSourceResponse.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/ServerSentEvents/EventSourceResponse.cs
new file mode 100644
index 00000000..e2a8aeb9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/ServerSentEvents/EventSourceResponse.cs
@@ -0,0 +1,390 @@
+#if !BESTHTTP_DISABLE_SERVERSENT_EVENTS && (!UNITY_WEBGL || UNITY_EDITOR)
+
+using System;
+using System.IO;
+using System.Threading;
+
+using System.Text;
+using System.Collections.Generic;
+
+namespace BestHTTP.ServerSentEvents
+{
+ ///
+ /// A low-level class to receive and parse an EventSource(http://www.w3.org/TR/eventsource/) stream.
+ /// Higher level protocol representation is implemented in the EventSource class.
+ ///
+ public sealed class EventSourceResponse : HTTPResponse, IProtocol
+ {
+ public bool IsClosed { get; private set; }
+
+ #region Public Events
+
+ public Action OnMessage;
+ public Action OnClosed;
+
+ #endregion
+
+ #region Privates
+
+ ///
+ /// Thread sync object
+ ///
+ private object FrameLock = new object();
+
+ ///
+ /// Buffer for the read data.
+ ///
+ private byte[] LineBuffer;
+
+ ///
+ /// Buffer position.
+ ///
+ private int LineBufferPos = 0;
+
+ ///
+ /// The currently receiving and parsing message
+ ///
+ private BestHTTP.ServerSentEvents.Message CurrentMessage;
+
+ ///
+ /// Completed messages that waiting to be dispatched
+ ///
+ private List CompletedMessages = new List();
+
+ #endregion
+
+ public EventSourceResponse(HTTPRequest request, Stream stream, bool isStreamed, bool isFromCache)
+ :base(request, stream, isStreamed, isFromCache)
+ {
+ base.IsClosedManually = true;
+ }
+
+ public override bool Receive(int forceReadRawContentLength = -1, bool readPayloadData = true)
+ {
+ bool received = base.Receive(forceReadRawContentLength, false);
+
+ string contentType = this.GetFirstHeaderValue("content-type");
+ base.IsUpgraded = received &&
+ this.StatusCode == 200 &&
+ !string.IsNullOrEmpty(contentType) &&
+ contentType.ToLower().StartsWith("text/event-stream");
+
+ // If we didn't upgraded to the protocol we have to read all the sent payload because
+ // next requests may read these datas as HTTP headers and will fail
+ if (!IsUpgraded)
+ ReadPayload(forceReadRawContentLength);
+
+ return received;
+ }
+
+ internal void StartReceive()
+ {
+ if (IsUpgraded)
+ {
+#if NETFX_CORE
+ #pragma warning disable 4014
+ Windows.System.Threading.ThreadPool.RunAsync(ReceiveThreadFunc);
+ #pragma warning restore 4014
+#else
+ ThreadPool.QueueUserWorkItem(ReceiveThreadFunc);
+ //new Thread(ReceiveThreadFunc)
+ // .Start();
+#endif
+ }
+ }
+
+ #region Private Threading Functions
+
+ private void ReceiveThreadFunc(object param)
+ {
+ try
+ {
+ if (HasHeaderWithValue("transfer-encoding", "chunked"))
+ ReadChunked(Stream);
+ else
+ ReadRaw(Stream, -1);
+ }
+#if !NETFX_CORE
+ catch (ThreadAbortException)
+ {
+ this.baseRequest.State = HTTPRequestStates.Aborted;
+ }
+#endif
+ catch (Exception e)
+ {
+ if (HTTPUpdateDelegator.IsCreated)
+ {
+ this.baseRequest.Exception = e;
+ this.baseRequest.State = HTTPRequestStates.Error;
+ }
+ else
+ this.baseRequest.State = HTTPRequestStates.Aborted;
+ }
+ finally
+ {
+ IsClosed = true;
+ }
+ }
+
+ #endregion
+
+ #region Read Implementations
+
+ // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1
+ private new void ReadChunked(Stream stream)
+ {
+ int chunkLength = ReadChunkLength(stream);
+ byte[] buffer = Extensions.VariableSizedBufferPool.Get(chunkLength, true);
+
+ while (chunkLength != 0)
+ {
+ // To avoid more GC garbage we use only one buffer, and resize only if the next chunk doesn't fit.
+ if (buffer.Length < chunkLength)
+ Extensions.VariableSizedBufferPool.Resize(ref buffer, chunkLength, true);
+
+ int readBytes = 0;
+
+ // Fill up the buffer
+ do
+ {
+ int bytes = stream.Read(buffer, readBytes, chunkLength - readBytes);
+ if (bytes == 0)
+ throw new Exception("The remote server closed the connection unexpectedly!");
+
+ readBytes += bytes;
+ } while (readBytes < chunkLength);
+
+ FeedData(buffer, readBytes);
+
+ // Every chunk data has a trailing CRLF
+ ReadTo(stream, LF);
+
+ // read the next chunk's length
+ chunkLength = ReadChunkLength(stream);
+ }
+
+ Extensions.VariableSizedBufferPool.Release(buffer);
+
+ // Read the trailing headers or the CRLF
+ ReadHeaders(stream);
+ }
+
+ private new void ReadRaw(Stream stream, long contentLength)
+ {
+ byte[] buffer = Extensions.VariableSizedBufferPool.Get(1024, true);
+ int bytes;
+
+ do
+ {
+ bytes = stream.Read(buffer, 0, buffer.Length);
+
+ FeedData(buffer, bytes);
+ } while(bytes > 0);
+
+ Extensions.VariableSizedBufferPool.Release(buffer);
+ }
+
+ #endregion
+
+ #region Data Parsing
+
+ public void FeedData(byte[] buffer, int count)
+ {
+ if (count == -1)
+ count = buffer.Length;
+
+ if (count == 0)
+ return;
+
+ if (LineBuffer == null)
+ LineBuffer = Extensions.VariableSizedBufferPool.Get(1024, true);
+
+ int newlineIdx;
+ int pos = 0;
+
+ do {
+
+ newlineIdx = -1;
+ int skipCount = 1; // to skip CR and/or LF
+
+ for (int i = pos; i < count && newlineIdx == -1; ++i)
+ {
+ // Lines must be separated by either a U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pair, a single U+000A LINE FEED (LF) character, or a single U+000D CARRIAGE RETURN (CR) character.
+ if (buffer[i] == HTTPResponse.CR)
+ {
+ if (i + 1 < count && buffer[i + 1] == HTTPResponse.LF)
+ skipCount = 2;
+ newlineIdx = i;
+ }
+ else if (buffer[i] == HTTPResponse.LF)
+ newlineIdx = i;
+ }
+
+ int copyIndex = newlineIdx == -1 ? count : newlineIdx;
+
+ if (LineBuffer.Length < LineBufferPos + (copyIndex - pos))
+ {
+ int newSize = LineBufferPos + (copyIndex - pos);
+ Extensions.VariableSizedBufferPool.Resize(ref LineBuffer, newSize, true);
+ }
+
+ Array.Copy(buffer, pos, LineBuffer, LineBufferPos, copyIndex - pos);
+
+ LineBufferPos += copyIndex - pos;
+
+ if (newlineIdx == -1)
+ return;
+
+ ParseLine(LineBuffer, LineBufferPos);
+
+ LineBufferPos = 0;
+ //pos += newlineIdx + skipCount;
+ pos = newlineIdx + skipCount;
+
+ }while(newlineIdx != -1 && pos < count);
+ }
+
+ void ParseLine(byte[] buffer, int count)
+ {
+ // If the line is empty (a blank line) => Dispatch the event
+ if (count == 0)
+ {
+ if (CurrentMessage != null)
+ {
+ lock (FrameLock)
+ CompletedMessages.Add(CurrentMessage);
+ CurrentMessage = null;
+ }
+
+ return;
+ }
+
+ // If the line starts with a U+003A COLON character (:) => Ignore the line.
+ if (buffer[0] == 0x3A)
+ return;
+
+ //If the line contains a U+003A COLON character (:)
+ int colonIdx = -1;
+ for (int i = 0; i < count && colonIdx == -1; ++i)
+ if (buffer[i] == 0x3A)
+ colonIdx = i;
+
+ string field;
+ string value;
+
+ if (colonIdx != -1)
+ {
+ // Collect the characters on the line before the first U+003A COLON character (:), and let field be that string.
+ field = Encoding.UTF8.GetString(buffer, 0, colonIdx);
+
+ //Collect the characters on the line after the first U+003A COLON character (:), and let value be that string. If value starts with a U+0020 SPACE character, remove it from value.
+ if (colonIdx + 1 < count && buffer[colonIdx + 1] == 0x20)
+ colonIdx++;
+
+ colonIdx++;
+
+ // discarded because it is not followed by a blank line
+ if (colonIdx >= count)
+ return;
+
+ value = Encoding.UTF8.GetString(buffer, colonIdx, count - colonIdx);
+ }
+ else
+ {
+ // Otherwise, the string is not empty but does not contain a U+003A COLON character (:) =>
+ // Process the field using the whole line as the field name, and the empty string as the field value.
+ field = Encoding.UTF8.GetString(buffer, 0, count);
+ value = string.Empty;
+ }
+
+ if (CurrentMessage == null)
+ CurrentMessage = new BestHTTP.ServerSentEvents.Message();
+
+ switch(field)
+ {
+ // If the field name is "id" => Set the last event ID buffer to the field value.
+ case "id":
+ CurrentMessage.Id = value;
+ break;
+
+ // If the field name is "event" => Set the event type buffer to field value.
+ case "event":
+ CurrentMessage.Event = value;
+ break;
+
+ // If the field name is "data" => Append the field value to the data buffer, then append a single U+000A LINE FEED (LF) character to the data buffer.
+ case "data":
+ // Append a new line if we already have some data. This way we can skip step 3.) in the EventSource's OnMessageReceived.
+ // We do only null check, because empty string can be valid payload
+ if (CurrentMessage.Data != null)
+ CurrentMessage.Data += Environment.NewLine;
+
+ CurrentMessage.Data += value;
+ break;
+
+ // If the field name is "retry" => If the field value consists of only ASCII digits, then interpret the field value as an integer in base ten,
+ // and set the event stream's reconnection time to that integer. Otherwise, ignore the field.
+ case "retry":
+ int result;
+ if (int.TryParse(value, out result))
+ CurrentMessage.Retry = TimeSpan.FromMilliseconds(result);
+ break;
+
+ // Otherwise: The field is ignored.
+ default:
+ break;
+ }
+ }
+
+ #endregion
+
+ void IProtocol.HandleEvents()
+ {
+ lock(FrameLock)
+ {
+ // Send out messages.
+ if (CompletedMessages.Count > 0)
+ {
+ if (OnMessage != null)
+ for (int i = 0; i < CompletedMessages.Count; ++i)
+ {
+ try
+ {
+ OnMessage(this, CompletedMessages[i]);
+ }
+ catch(Exception ex)
+ {
+ HTTPManager.Logger.Exception("EventSourceMessage", "HandleEvents - OnMessage", ex);
+ }
+ }
+
+ CompletedMessages.Clear();
+ }
+ }
+
+ // We are closed
+ if (IsClosed)
+ {
+ CompletedMessages.Clear();
+
+ if (OnClosed != null)
+ {
+ try
+ {
+ OnClosed(this);
+ }
+ catch (Exception ex)
+ {
+ HTTPManager.Logger.Exception("EventSourceMessage", "HandleEvents - OnClosed", ex);
+ }
+ finally
+ {
+ OnClosed = null;
+ }
+ }
+ }
+ }
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/ServerSentEvents/EventSourceResponse.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/ServerSentEvents/EventSourceResponse.cs.meta
new file mode 100644
index 00000000..9dfa393e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/ServerSentEvents/EventSourceResponse.cs.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: f1346db7284d3a04e8edd33864f9231c
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/ServerSentEvents/Message.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/ServerSentEvents/Message.cs
new file mode 100644
index 00000000..7679052c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/ServerSentEvents/Message.cs
@@ -0,0 +1,36 @@
+#if !BESTHTTP_DISABLE_SERVERSENT_EVENTS
+
+using System;
+
+namespace BestHTTP.ServerSentEvents
+{
+ public sealed class Message
+ {
+ ///
+ /// Event Id of the message. If it's null, then it's not present.
+ ///
+ public string Id { get; internal set; }
+
+ ///
+ /// Name of the event, or an empty string.
+ ///
+ public string Event { get; internal set; }
+
+ ///
+ /// The actual payload of the message.
+ ///
+ public string Data { get; internal set; }
+
+ ///
+ /// A reconnection time, in milliseconds. This must initially be a user-agent-defined value, probably in the region of a few seconds.
+ ///
+ public TimeSpan Retry { get; internal set; }
+
+ public override string ToString()
+ {
+ return string.Format("\"{0}\": \"{1}\"", Event, Data);
+ }
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/ServerSentEvents/Message.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/ServerSentEvents/Message.cs.meta
new file mode 100644
index 00000000..05418380
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/ServerSentEvents/Message.cs.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: 9a3820c17c331374a82799277eb9ede0
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR.meta
new file mode 100644
index 00000000..121d8934
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: e2d987f043f34ae48a80a57c82fa4193
+folderAsset: yes
+DefaultImporter:
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Authentication.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Authentication.meta
new file mode 100644
index 00000000..38db0371
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Authentication.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 008d5591a2cd6704fb39796bd33ff71a
+folderAsset: yes
+DefaultImporter:
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Authentication/IAuthenticationProvider.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Authentication/IAuthenticationProvider.cs
new file mode 100644
index 00000000..a632f051
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Authentication/IAuthenticationProvider.cs
@@ -0,0 +1,37 @@
+#if !BESTHTTP_DISABLE_SIGNALR
+
+namespace BestHTTP.SignalR.Authentication
+{
+ public delegate void OnAuthenticationSuccededDelegate(IAuthenticationProvider provider);
+ public delegate void OnAuthenticationFailedDelegate(IAuthenticationProvider provider, string reason);
+
+ public interface IAuthenticationProvider
+ {
+ ///
+ /// The authentication must be run before any request made to build up the SignalR protocol
+ ///
+ bool IsPreAuthRequired { get; }
+
+ ///
+ /// This event must be called when the pre-authentication succeded. When IsPreAuthRequired is false, no-one will subscribe to this event.
+ ///
+ event OnAuthenticationSuccededDelegate OnAuthenticationSucceded;
+
+ ///
+ /// This event must be called when the pre-authentication failed. When IsPreAuthRequired is false, no-one will subscribe to this event.
+ ///
+ event OnAuthenticationFailedDelegate OnAuthenticationFailed;
+
+ ///
+ /// This function called once, when the before the SignalR negotiation begins. If IsPreAuthRequired is false, then this step will be skipped.
+ ///
+ void StartAuthentication();
+
+ ///
+ /// This function will be called for every request before sending it.
+ ///
+ void PrepareRequest(HTTPRequest request, RequestTypes type);
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Authentication/IAuthenticationProvider.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Authentication/IAuthenticationProvider.cs.meta
new file mode 100644
index 00000000..94bb950f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Authentication/IAuthenticationProvider.cs.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: e95e3e74ee7feaf4b872a3d4d23dc0a6
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Connection.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Connection.cs
new file mode 100644
index 00000000..acf658bf
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Connection.cs
@@ -0,0 +1,1306 @@
+#if !BESTHTTP_DISABLE_SIGNALR
+
+using System;
+using System.Text;
+using System.Collections.Generic;
+
+using BestHTTP.Extensions;
+using BestHTTP.SignalR.Hubs;
+using BestHTTP.SignalR.Messages;
+using BestHTTP.SignalR.Transports;
+using BestHTTP.SignalR.JsonEncoders;
+using BestHTTP.SignalR.Authentication;
+
+using PlatformSupport.Collections.ObjectModel;
+
+#if !NETFX_CORE
+ using PlatformSupport.Collections.Specialized;
+#else
+ using System.Collections.Specialized;
+#endif
+
+namespace BestHTTP.SignalR
+{
+ public delegate void OnNonHubMessageDelegate(Connection connection, object data);
+ public delegate void OnConnectedDelegate(Connection connection);
+ public delegate void OnClosedDelegate(Connection connection);
+ public delegate void OnErrorDelegate(Connection connection, string error);
+ public delegate void OnStateChanged(Connection connection, ConnectionStates oldState, ConnectionStates newState);
+ public delegate void OnPrepareRequestDelegate(Connection connection, HTTPRequest req, RequestTypes type);
+
+ ///
+ /// Interface to be able to hide internally used functions and properties.
+ ///
+ public interface IConnection
+ {
+ ProtocolVersions Protocol { get; }
+ NegotiationData NegotiationResult { get; }
+ IJsonEncoder JsonEncoder { get; set; }
+
+ void OnMessage(IServerMessage msg);
+ void TransportStarted();
+ void TransportReconnected();
+ void TransportAborted();
+ void Error(string reason);
+ Uri BuildUri(RequestTypes type);
+ Uri BuildUri(RequestTypes type, TransportBase transport);
+ HTTPRequest PrepareRequest(HTTPRequest req, RequestTypes type);
+ string ParseResponse(string responseStr);
+ }
+
+ ///
+ /// Supported versions of the SignalR protocol.
+ ///
+ public enum ProtocolVersions : byte
+ {
+ Protocol_2_0,
+ Protocol_2_1,
+ Protocol_2_2
+ }
+
+ ///
+ /// The main SignalR class. This is the entry point to connect to a SignalR service.
+ ///
+ public sealed class Connection : IHeartbeat, IConnection
+ {
+ #region Public Properties
+
+ ///
+ /// The default Json encode/decoder that will be used to encode/decode the event arguments.
+ ///
+ public static IJsonEncoder DefaultEncoder =
+#if BESTHTTP_SIGNALR_WITH_JSONDOTNET
+ new JSonDotnetEncoder();
+#else
+ new DefaultJsonEncoder();
+#endif
+
+ ///
+ /// The base url endpoint where the SignalR service can be found.
+ ///
+ public Uri Uri { get; private set; }
+
+ ///
+ /// Current State of the SignalR connection.
+ ///
+ public ConnectionStates State
+ {
+ get { return _state; }
+ private set
+ {
+ ConnectionStates old = _state;
+ _state = value;
+
+ if (OnStateChanged != null)
+ OnStateChanged(this, old, _state);
+ }
+ }
+ private ConnectionStates _state;
+
+ ///
+ /// Result of the negotiation request from the server.
+ ///
+ public NegotiationData NegotiationResult { get; private set; }
+
+ ///
+ /// The hubs that the client is connected to.
+ ///
+ public Hub[] Hubs { get; private set; }
+
+ ///
+ /// The transport that is used to send and receive messages.
+ ///
+ public TransportBase Transport { get; private set; }
+
+ ///
+ /// Current client protocol in use.
+ ///
+ public ProtocolVersions Protocol { get; private set; }
+
+ ///
+ /// Additional query parameters that will be passed for the handshake uri. If the value is null, or an empty string it will be not appended to the query only the key.
+ /// The keys and values must be escaped properly, as the plugin will not escape these.
+ ///
+ public ObservableDictionary AdditionalQueryParams
+ {
+ get { return additionalQueryParams; }
+ set
+ {
+ // Unsubscribe from previous dictionary's events
+ if (additionalQueryParams != null)
+ additionalQueryParams.CollectionChanged -= AdditionalQueryParams_CollectionChanged;
+
+ additionalQueryParams = value;
+
+ // Clear out the cached value
+ BuiltQueryParams = null;
+
+ // Subscribe to the collection changed event
+ if (value != null)
+ value.CollectionChanged += AdditionalQueryParams_CollectionChanged;
+ }
+ }
+ private ObservableDictionary additionalQueryParams;
+
+ ///
+ /// If it's false, the parameters in the AdditionalQueryParams will be passed for all http requests. Its default value is true.
+ ///
+ public bool QueryParamsOnlyForHandshake { get; set; }
+
+ ///
+ /// The Json encoder that will be used by the connection and the transport.
+ ///
+ public IJsonEncoder JsonEncoder { get; set; }
+
+ ///
+ /// An IAuthenticationProvider implementation that will be used to authenticate the connection.
+ ///
+ public IAuthenticationProvider AuthenticationProvider { get; set; }
+
+ ///
+ /// How much time we have to wait between two pings.
+ ///
+ public TimeSpan PingInterval { get; set; }
+
+ ///
+ /// Wait time before the plugin should do a reconnect attempt. Its default value is 5 seconds.
+ ///
+ public TimeSpan ReconnectDelay { get; set; }
+
+ #endregion
+
+ #region Public Events
+
+ ///
+ /// Called when the protocol is open for communication.
+ ///
+ public event OnConnectedDelegate OnConnected;
+
+ ///
+ /// Called when the connection is closed, and no further messages are sent or received.
+ ///
+ public event OnClosedDelegate OnClosed;
+
+ ///
+ /// Called when an error occures. If the connection is already Started, it will try to do a reconnect, otherwise it will close the connection.
+ ///
+ public event OnErrorDelegate OnError;
+
+ ///
+ /// This event called when a reconnection attempt are started. If fails to reconnect an OnError and OnClosed events are called.
+ ///
+ public event OnConnectedDelegate OnReconnecting;
+
+ ///
+ /// This event called when the reconnection attempt succeded.
+ ///
+ public event OnConnectedDelegate OnReconnected;
+
+ ///
+ /// Called every time when the connection's state changes.
+ ///
+ public event OnStateChanged OnStateChanged;
+
+ ///
+ /// It's called when a non-Hub message received. The data can be anything from primitive types to array of complex objects.
+ ///
+ public event OnNonHubMessageDelegate OnNonHubMessage;
+
+ ///
+ /// With this delegate all requests can be further customized.
+ ///
+ public OnPrepareRequestDelegate RequestPreparator { get; set; }
+
+ #endregion
+
+ #region Indexers
+
+ ///
+ /// Indexer property the access hubs by index.
+ ///
+ public Hub this[int idx] { get { return Hubs[idx] as Hub; } }
+
+ ///
+ /// Indexer property the access hubs by name.
+ ///
+ public Hub this[string hubName]
+ {
+ get
+ {
+ for (int i = 0; i < Hubs.Length; ++i)
+ {
+ Hub hub = Hubs[i] as Hub;
+ if (hub.Name.Equals(hubName, StringComparison.OrdinalIgnoreCase))
+ return hub;
+ }
+
+ return null;
+ }
+ }
+
+ #endregion
+
+ #region Internals
+
+ ///
+ /// An object to be able maintain thread safety.
+ ///
+ internal object SyncRoot = new object();
+
+ ///
+ /// Unique ID for all message sent by the client.
+ ///
+ internal UInt64 ClientMessageCounter { get; set; }
+
+ #endregion
+
+ #region Privates
+
+ ///
+ /// Supported client protocol versions.
+ ///
+ private readonly string[] ClientProtocols = new string[] { "1.3", "1.4", "1.5" };
+
+ ///
+ /// A timestamp that will be sent with all request for easier debugging.
+ ///
+ private UInt32 Timestamp { get { return (UInt32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).Ticks; } }
+
+ ///
+ /// Request counter sent with all request for easier debugging.
+ ///
+ private UInt64 RequestCounter;
+
+ ///
+ /// Instance of the last received message. Used for its MessageId.
+ ///
+ private MultiMessage LastReceivedMessage;
+
+ ///
+ /// The GroupsToken sent by the server that stores what groups we are joined to.
+ /// We will send it with the reconnect request.
+ ///
+ private string GroupsToken;
+
+ ///
+ /// Received messages before the Start request finishes.
+ ///
+ private List BufferedMessages;
+
+ ///
+ /// When the last message received from the server. Used for reconnecting.
+ ///
+ private DateTime LastMessageReceivedAt;
+
+ ///
+ /// When we started to reconnect. When too much time passes without a successful reconnect, we will close the connection.
+ ///
+ private DateTime ReconnectStartedAt;
+
+ private DateTime ReconnectDelayStartedAt;
+
+ ///
+ /// True, if the reconnect process started.
+ ///
+ private bool ReconnectStarted;
+
+ ///
+ /// When the last ping request sent out.
+ ///
+ private DateTime LastPingSentAt;
+
+ ///
+ /// Reference to the ping request.
+ ///
+ private HTTPRequest PingRequest;
+
+ ///
+ /// When the transport started the connection process
+ ///
+ private DateTime? TransportConnectionStartedAt;
+
+ ///
+ /// Cached StringBuilder instance used in BuildUri
+ ///
+ private StringBuilder queryBuilder = new StringBuilder();
+
+ ///
+ /// Builds and returns with the connection data made from the hub names.
+ ///
+ private string ConnectionData
+ {
+ get
+ {
+ if (!string.IsNullOrEmpty(BuiltConnectionData))
+ return BuiltConnectionData;
+
+ StringBuilder sb = new StringBuilder("[", Hubs.Length * 4);
+
+ if (Hubs != null)
+ for (int i = 0; i < Hubs.Length; ++i)
+ {
+ sb.Append(@"{""Name"":""");
+ sb.Append(Hubs[i].Name);
+ sb.Append(@"""}");
+
+ if (i < Hubs.Length - 1)
+ sb.Append(",");
+ }
+
+ sb.Append("]");
+
+ return BuiltConnectionData = Uri.EscapeUriString(sb.ToString());
+ }
+ }
+
+ ///
+ /// The cached value of the result of the ConnectionData property call.
+ ///
+ private string BuiltConnectionData;
+
+ ///
+ /// Builds the keys and values from the AdditionalQueryParams to an key=value form. If AdditionalQueryParams is null or empty, it will return an empty string.
+ ///
+ private string QueryParams
+ {
+ get
+ {
+ if (AdditionalQueryParams == null || AdditionalQueryParams.Count == 0)
+ return string.Empty;
+
+ if (!string.IsNullOrEmpty(BuiltQueryParams))
+ return BuiltQueryParams;
+
+ StringBuilder sb = new StringBuilder(AdditionalQueryParams.Count * 4);
+
+ foreach (var kvp in AdditionalQueryParams)
+ {
+ sb.Append("&");
+ sb.Append(kvp.Key);
+
+ if (!string.IsNullOrEmpty(kvp.Value))
+ {
+ sb.Append("=");
+ sb.Append(Uri.EscapeDataString(kvp.Value));
+ }
+ }
+
+ return BuiltQueryParams = sb.ToString();
+ }
+ }
+
+ ///
+ /// The cached value of the result of the QueryParams property call.
+ ///
+ private string BuiltQueryParams;
+
+ private SupportedProtocols NextProtocolToTry;
+
+ #endregion
+
+ #region Constructors
+
+ public Connection(Uri uri, params string[] hubNames)
+ : this(uri)
+ {
+ if (hubNames != null && hubNames.Length > 0)
+ {
+ this.Hubs = new Hub[hubNames.Length];
+
+ for (int i = 0; i < hubNames.Length; ++i)
+ this.Hubs[i] = new Hub(hubNames[i], this);
+ }
+ }
+
+ public Connection(Uri uri, params Hub[] hubs)
+ :this(uri)
+ {
+ this.Hubs = hubs;
+ if (hubs != null)
+ for (int i = 0; i < hubs.Length; ++i)
+ (hubs[i] as IHub).Connection = this;
+ }
+
+ public Connection(Uri uri)
+ {
+ this.State = ConnectionStates.Initial;
+ this.Uri = uri;
+
+ this.JsonEncoder = Connection.DefaultEncoder;
+ this.PingInterval = TimeSpan.FromMinutes(5);
+
+ // Expected protocol
+ this.Protocol = ProtocolVersions.Protocol_2_2;
+
+ this.ReconnectDelay = TimeSpan.FromSeconds(5);
+ }
+
+ #endregion
+
+ #region Starting the protocol
+
+ ///
+ /// This function will start to authenticate if required, and the SignalR protocol negotiation.
+ ///
+ public void Open()
+ {
+ if (State != ConnectionStates.Initial && State != ConnectionStates.Closed)
+ return;
+
+ if (AuthenticationProvider != null && AuthenticationProvider.IsPreAuthRequired)
+ {
+ this.State = ConnectionStates.Authenticating;
+
+ AuthenticationProvider.OnAuthenticationSucceded += OnAuthenticationSucceded;
+ AuthenticationProvider.OnAuthenticationFailed += OnAuthenticationFailed;
+
+ // Start the authentication process
+ AuthenticationProvider.StartAuthentication();
+ }
+ else
+ StartImpl();
+ }
+
+ ///
+ /// Called when the authentication succeeded.
+ ///
+ ///
+ private void OnAuthenticationSucceded(IAuthenticationProvider provider)
+ {
+ provider.OnAuthenticationSucceded -= OnAuthenticationSucceded;
+ provider.OnAuthenticationFailed -= OnAuthenticationFailed;
+
+ StartImpl();
+ }
+
+ ///
+ /// Called when the authentication failed.
+ ///
+ private void OnAuthenticationFailed(IAuthenticationProvider provider, string reason)
+ {
+ provider.OnAuthenticationSucceded -= OnAuthenticationSucceded;
+ provider.OnAuthenticationFailed -= OnAuthenticationFailed;
+
+ (this as IConnection).Error(reason);
+ }
+
+ ///
+ /// It's the real Start implementation. It will start the negotiation
+ ///
+ private void StartImpl()
+ {
+ this.State = ConnectionStates.Negotiating;
+
+ NegotiationResult = new NegotiationData(this);
+ NegotiationResult.OnReceived = OnNegotiationDataReceived;
+ NegotiationResult.OnError = OnNegotiationError;
+ NegotiationResult.Start();
+ }
+
+ #region Negotiation Event Handlers
+
+ ///
+ /// Protocol negotiation finished successfully.
+ ///
+ private void OnNegotiationDataReceived(NegotiationData data)
+ {
+ // Find out what supported protocol the server speak
+ int protocolIdx = -1;
+ for (int i = 0; i < ClientProtocols.Length && protocolIdx == -1; ++i)
+ if (data.ProtocolVersion == ClientProtocols[i])
+ protocolIdx = i;
+
+ // No supported protocol found? Try using the latest one.
+ if (protocolIdx == -1)
+ {
+ protocolIdx = (byte)ProtocolVersions.Protocol_2_2;
+ HTTPManager.Logger.Warning("SignalR Connection", "Unknown protocol version: " + data.ProtocolVersion);
+ }
+
+ this.Protocol = (ProtocolVersions)protocolIdx;
+
+ #if !BESTHTTP_DISABLE_WEBSOCKET
+ if (data.TryWebSockets)
+ {
+ Transport = new WebSocketTransport(this);
+
+ #if !BESTHTTP_DISABLE_SERVERSENT_EVENTS
+ NextProtocolToTry = SupportedProtocols.ServerSentEvents;
+ #else
+ NextProtocolToTry = SupportedProtocols.HTTP;
+ #endif
+ }
+ else
+ #endif
+ {
+ #if !BESTHTTP_DISABLE_SERVERSENT_EVENTS
+ Transport = new ServerSentEventsTransport(this);
+
+ // Long-Poll
+ NextProtocolToTry = SupportedProtocols.HTTP;
+ #else
+
+ Transport = new PollingTransport(this);
+
+ NextProtocolToTry = SupportedProtocols.Unknown;
+ #endif
+ }
+
+ this.State = ConnectionStates.Connecting;
+ TransportConnectionStartedAt = DateTime.UtcNow;
+
+ Transport.Connect();
+ }
+
+ ///
+ /// Protocol negotiation failed.
+ ///
+ private void OnNegotiationError(NegotiationData data, string error)
+ {
+ (this as IConnection).Error(error);
+ }
+
+ #endregion
+
+ #endregion
+
+ #region Public Interface
+
+ ///
+ /// Closes the connection and shuts down the transport.
+ ///
+ public void Close()
+ {
+ if (this.State == ConnectionStates.Closed)
+ return;
+
+ this.State = ConnectionStates.Closed;
+
+ //ReconnectStartedAt = null;
+ ReconnectStarted = false;
+
+ TransportConnectionStartedAt = null;
+
+ if (Transport != null)
+ {
+ Transport.Abort();
+ Transport = null;
+ }
+
+ NegotiationResult = null;
+
+ HTTPManager.Heartbeats.Unsubscribe(this);
+
+ LastReceivedMessage = null;
+
+ if (Hubs != null)
+ for (int i = 0; i < Hubs.Length; ++i)
+ (Hubs[i] as IHub).Close();
+
+ if (BufferedMessages != null)
+ {
+ BufferedMessages.Clear();
+ BufferedMessages = null;
+ }
+
+ if (OnClosed != null)
+ {
+ try
+ {
+ OnClosed(this);
+ }
+ catch (Exception ex)
+ {
+ HTTPManager.Logger.Exception("SignalR Connection", "OnClosed", ex);
+ }
+ }
+ }
+
+ ///
+ /// Initiates a reconnect to the SignalR server.
+ ///
+ public void Reconnect()
+ {
+ // Return if reconnect process already started.
+ if (ReconnectStarted)
+ return;
+ ReconnectStarted = true;
+
+ // Set ReconnectStartedAt only when the previous State is not Reconnecting,
+ // so we keep the first date&time when we started reconnecting
+ if (this.State != ConnectionStates.Reconnecting)
+ ReconnectStartedAt = DateTime.UtcNow;
+
+ this.State = ConnectionStates.Reconnecting;
+
+ HTTPManager.Logger.Warning("SignalR Connection", "Reconnecting");
+
+ Transport.Reconnect();
+
+ if (PingRequest != null)
+ PingRequest.Abort();
+
+ if (OnReconnecting != null)
+ {
+ try
+ {
+ OnReconnecting(this);
+ }
+ catch (Exception ex)
+ {
+ HTTPManager.Logger.Exception("SignalR Connection", "OnReconnecting", ex);
+ }
+ }
+ }
+
+
+ ///
+ /// Will encode the argument to a Json string using the Connection's JsonEncoder, then will send it to the server.
+ ///
+ /// True if the plugin was able to send out the message
+ public bool Send(object arg)
+ {
+ if (arg == null)
+ throw new ArgumentNullException("arg");
+
+ lock(SyncRoot)
+ {
+ if (this.State != ConnectionStates.Connected)
+ return false;
+
+ string json = JsonEncoder.Encode(arg);
+
+ if (string.IsNullOrEmpty(json))
+ HTTPManager.Logger.Error("SignalR Connection", "Failed to JSon encode the given argument. Please try to use an advanced JSon encoder(check the documentation how you can do it).");
+ else
+ Transport.Send(json);
+ }
+
+ return true;
+ }
+
+ ///
+ /// Sends the given json string to the server.
+ ///
+ /// True if the plugin was able to send out the message
+ public bool SendJson(string json)
+ {
+ if (json == null)
+ throw new ArgumentNullException("json");
+
+ lock(SyncRoot)
+ {
+ if (this.State != ConnectionStates.Connected)
+ return false;
+
+ Transport.Send(json);
+ }
+
+ return true;
+ }
+
+ #endregion
+
+ #region IManager Functions
+
+ ///
+ /// Called when we receive a message from the server
+ ///
+ void IConnection.OnMessage(IServerMessage msg)
+ {
+ if (this.State == ConnectionStates.Closed)
+ return;
+
+ // Store messages that we receive while we are connecting
+ if (this.State == ConnectionStates.Connecting)
+ {
+ if (BufferedMessages == null)
+ BufferedMessages = new List();
+
+ BufferedMessages.Add(msg);
+
+ return;
+ }
+
+ LastMessageReceivedAt = DateTime.UtcNow;
+
+ switch(msg.Type)
+ {
+ case MessageTypes.Multiple:
+ LastReceivedMessage = msg as MultiMessage;
+
+ // Not received in the reconnect process, so we can't rely on it
+ if (LastReceivedMessage.IsInitialization)
+ HTTPManager.Logger.Information("SignalR Connection", "OnMessage - Init");
+
+ if (LastReceivedMessage.GroupsToken != null)
+ GroupsToken = LastReceivedMessage.GroupsToken;
+
+ if (LastReceivedMessage.ShouldReconnect)
+ {
+ HTTPManager.Logger.Information("SignalR Connection", "OnMessage - Should Reconnect");
+
+ Reconnect();
+
+ // Should we return here not processing the messages that may come with it?
+ //return;
+ }
+
+ if (LastReceivedMessage.Data != null)
+ for (int i = 0; i < LastReceivedMessage.Data.Count; ++i)
+ (this as IConnection).OnMessage(LastReceivedMessage.Data[i]);
+
+ break;
+
+ case MessageTypes.MethodCall:
+ MethodCallMessage methodCall = msg as MethodCallMessage;
+
+ Hub hub = this[methodCall.Hub];
+
+ if (hub != null)
+ (hub as IHub).OnMethod(methodCall);
+ else
+ HTTPManager.Logger.Warning("SignalR Connection", string.Format("Hub \"{0}\" not found!", methodCall.Hub));
+
+ break;
+
+ case MessageTypes.Result:
+ case MessageTypes.Failure:
+ case MessageTypes.Progress:
+ UInt64 id = (msg as IHubMessage).InvocationId;
+ hub = FindHub(id);
+ if (hub != null)
+ (hub as IHub).OnMessage(msg);
+ else
+ HTTPManager.Logger.Warning("SignalR Connection", string.Format("No Hub found for Progress message! Id: {0}", id.ToString()));
+ break;
+
+ case MessageTypes.Data:
+ if (OnNonHubMessage != null)
+ OnNonHubMessage(this, (msg as DataMessage).Data);
+ break;
+
+ case MessageTypes.KeepAlive:
+ break;
+
+ default:
+ HTTPManager.Logger.Warning("SignalR Connection", "Unknown message type received: " + msg.Type.ToString());
+ break;
+ }
+ }
+
+ ///
+ /// Called from the transport implementations when the Start request finishes successfully.
+ ///
+ void IConnection.TransportStarted()
+ {
+ if (this.State != ConnectionStates.Connecting)
+ return;
+
+ InitOnStart();
+
+ if (OnConnected != null)
+ {
+ try
+ {
+ OnConnected(this);
+ }
+ catch (Exception ex)
+ {
+ HTTPManager.Logger.Exception("SignalR Connection", "OnOpened", ex);
+ }
+ }
+
+ // Deliver messages that we received before the /start request returned.
+ // This must be after the OnStarted call, to let the clients to subrscribe to these events.
+ if (BufferedMessages != null)
+ {
+ for (int i = 0; i < BufferedMessages.Count; ++i)
+ (this as IConnection).OnMessage(BufferedMessages[i]);
+
+ BufferedMessages.Clear();
+ BufferedMessages = null;
+ }
+ }
+
+ ///
+ /// Called when the transport sucessfully reconnected to the server.
+ ///
+ void IConnection.TransportReconnected()
+ {
+ if (this.State != ConnectionStates.Reconnecting)
+ return;
+
+ HTTPManager.Logger.Information("SignalR Connection", "Transport Reconnected");
+
+ InitOnStart();
+
+ if (OnReconnected != null)
+ {
+ try
+ {
+ OnReconnected(this);
+ }
+ catch (Exception ex)
+ {
+ HTTPManager.Logger.Exception("SignalR Connection", "OnReconnected", ex);
+ }
+ }
+ }
+
+ ///
+ /// Called from the transport implementation when the Abort request finishes successfully.
+ ///
+ void IConnection.TransportAborted()
+ {
+ Close();
+ }
+
+ ///
+ /// Called when an error occures. If the connection is in the Connected state, it will start the reconnect process, otherwise it will close the connection.
+ ///
+ void IConnection.Error(string reason)
+ {
+ // Not interested about errors we received after we already closed
+ if (this.State == ConnectionStates.Closed)
+ return;
+
+ // If we are just quitting, don't try to reconnect.
+ if (HTTPManager.IsQuitting)
+ {
+ Close();
+ return;
+ }
+
+ HTTPManager.Logger.Error("SignalR Connection", reason);
+
+ ReconnectStarted = false;
+
+ if (OnError != null)
+ OnError(this, reason);
+
+ if (this.State == ConnectionStates.Connected || this.State == ConnectionStates.Reconnecting)
+ {
+ this.ReconnectDelayStartedAt = DateTime.UtcNow;
+ if (this.State != ConnectionStates.Reconnecting)
+ this.ReconnectStartedAt = DateTime.UtcNow;
+
+ //Reconnect();
+ }
+ else
+ {
+ // Fall back if possible
+ if (this.State != ConnectionStates.Connecting || !TryFallbackTransport())
+ Close();
+ }
+ }
+
+ ///
+ /// Creates an Uri instance for the given request type.
+ ///
+ Uri IConnection.BuildUri(RequestTypes type)
+ {
+ return (this as IConnection).BuildUri(type, null);
+ }
+
+ ///
+ /// Creates an Uri instance from the given parameters.
+ ///
+ Uri IConnection.BuildUri(RequestTypes type, TransportBase transport)
+ {
+ lock (SyncRoot)
+ {
+ // make sure that the queryBuilder is reseted
+ queryBuilder.Length = 0;
+
+ UriBuilder uriBuilder = new UriBuilder(Uri);
+
+ if (!uriBuilder.Path.EndsWith("/"))
+ uriBuilder.Path += "/";
+
+ this.RequestCounter %= UInt64.MaxValue;
+
+ switch (type)
+ {
+ case RequestTypes.Negotiate:
+ uriBuilder.Path += "negotiate";
+ goto default;
+
+ case RequestTypes.Connect:
+#if !BESTHTTP_DISABLE_WEBSOCKET
+ if (transport != null && transport.Type == TransportTypes.WebSocket)
+ uriBuilder.Scheme = HTTPProtocolFactory.IsSecureProtocol(Uri) ? "wss" : "ws";
+#endif
+
+ uriBuilder.Path += "connect";
+ goto default;
+
+ case RequestTypes.Start:
+ uriBuilder.Path += "start";
+ goto default;
+
+ case RequestTypes.Poll:
+ uriBuilder.Path += "poll";
+
+ if (this.LastReceivedMessage != null)
+ {
+ queryBuilder.Append("messageId=");
+ queryBuilder.Append(this.LastReceivedMessage.MessageId);
+ }
+
+ if (!string.IsNullOrEmpty(GroupsToken))
+ {
+ if (queryBuilder.Length > 0)
+ queryBuilder.Append("&");
+
+ queryBuilder.Append("groupsToken=");
+ queryBuilder.Append(GroupsToken);
+ }
+
+ goto default;
+
+ case RequestTypes.Send:
+ uriBuilder.Path += "send";
+ goto default;
+
+ case RequestTypes.Reconnect:
+#if !BESTHTTP_DISABLE_WEBSOCKET
+ if (transport != null && transport.Type == TransportTypes.WebSocket)
+ uriBuilder.Scheme = HTTPProtocolFactory.IsSecureProtocol(Uri) ? "wss" : "ws";
+#endif
+
+ uriBuilder.Path += "reconnect";
+
+ if (this.LastReceivedMessage != null)
+ {
+ queryBuilder.Append("messageId=");
+ queryBuilder.Append(this.LastReceivedMessage.MessageId);
+ }
+
+ if (!string.IsNullOrEmpty(GroupsToken))
+ {
+ if (queryBuilder.Length > 0)
+ queryBuilder.Append("&");
+
+ queryBuilder.Append("groupsToken=");
+ queryBuilder.Append(GroupsToken);
+ }
+
+ goto default;
+
+ case RequestTypes.Abort:
+ uriBuilder.Path += "abort";
+ goto default;
+
+ case RequestTypes.Ping:
+ uriBuilder.Path += "ping";
+
+ queryBuilder.Append("&tid=");
+ queryBuilder.Append(this.RequestCounter++.ToString());
+
+ queryBuilder.Append("&_=");
+ queryBuilder.Append(Timestamp.ToString());
+
+ break;
+
+ default:
+ if (queryBuilder.Length > 0)
+ queryBuilder.Append("&");
+
+ queryBuilder.Append("tid=");
+ queryBuilder.Append(this.RequestCounter++.ToString());
+
+ queryBuilder.Append("&_=");
+ queryBuilder.Append(Timestamp.ToString());
+
+ if (transport != null)
+ {
+ queryBuilder.Append("&transport=");
+ queryBuilder.Append(transport.Name);
+ }
+
+ queryBuilder.Append("&clientProtocol=");
+ queryBuilder.Append(ClientProtocols[(byte)Protocol]);
+
+ if (NegotiationResult != null && !string.IsNullOrEmpty(this.NegotiationResult.ConnectionToken))
+ {
+ queryBuilder.Append("&connectionToken=");
+ queryBuilder.Append(this.NegotiationResult.ConnectionToken);
+ }
+
+ if (this.Hubs != null && this.Hubs.Length > 0)
+ {
+ queryBuilder.Append("&connectionData=");
+ queryBuilder.Append(this.ConnectionData);
+ }
+
+ break;
+ }
+
+ // Query params are added to all uri
+ if (this.AdditionalQueryParams != null && this.AdditionalQueryParams.Count > 0)
+ queryBuilder.Append(this.QueryParams);
+
+ uriBuilder.Query = queryBuilder.ToString();
+
+ // reset the string builder
+ queryBuilder.Length = 0;
+
+ return uriBuilder.Uri;
+ }
+ }
+
+ ///
+ /// It's called on every request before sending it out to the server.
+ ///
+ HTTPRequest IConnection.PrepareRequest(HTTPRequest req, RequestTypes type)
+ {
+ if (req != null && AuthenticationProvider != null)
+ AuthenticationProvider.PrepareRequest(req, type);
+
+ if (RequestPreparator != null)
+ RequestPreparator(this, req, type);
+
+ return req;
+ }
+
+ ///
+ /// Will parse a "{ 'Response': 'xyz' }" object and returns with 'xyz'. If it fails to parse, or getting the 'Response' key, it will call the Error function.
+ ///
+ string IConnection.ParseResponse(string responseStr)
+ {
+ Dictionary dic = JSON.Json.Decode(responseStr) as Dictionary;
+
+ if (dic == null)
+ {
+ (this as IConnection).Error("Failed to parse Start response: " + responseStr);
+ return string.Empty;
+ }
+
+ object value;
+ if (!dic.TryGetValue("Response", out value) || value == null)
+ {
+ (this as IConnection).Error("No 'Response' key found in response: " + responseStr);
+ return string.Empty;
+ }
+
+ return value.ToString();
+ }
+
+ #endregion
+
+ #region IHeartbeat Implementation
+
+ ///
+ /// IHeartbeat implementation to manage timeouts.
+ ///
+ void IHeartbeat.OnHeartbeatUpdate(TimeSpan dif)
+ {
+ switch(this.State)
+ {
+ case ConnectionStates.Connected:
+ if (Transport.SupportsKeepAlive && NegotiationResult.KeepAliveTimeout != null && DateTime.UtcNow - LastMessageReceivedAt >= NegotiationResult.KeepAliveTimeout)
+ Reconnect();
+
+ if (PingRequest == null && DateTime.UtcNow - LastPingSentAt >= PingInterval)
+ Ping();
+
+ break;
+
+ case ConnectionStates.Reconnecting:
+ if ( DateTime.UtcNow - ReconnectStartedAt >= NegotiationResult.DisconnectTimeout)
+ {
+ HTTPManager.Logger.Warning("SignalR Connection", "OnHeartbeatUpdate - Failed to reconnect in the given time!");
+
+ Close();
+ }
+ else if (DateTime.UtcNow - ReconnectDelayStartedAt >= ReconnectDelay)
+ {
+ if (HTTPManager.Logger.Level <= Logger.Loglevels.Warning)
+ HTTPManager.Logger.Warning("SignalR Connection", this.ReconnectStarted.ToString() + " " + this.ReconnectStartedAt.ToString() + " " + NegotiationResult.DisconnectTimeout.ToString());
+ Reconnect();
+ }
+ break;
+
+ default:
+
+ if (TransportConnectionStartedAt != null && DateTime.UtcNow - TransportConnectionStartedAt >= NegotiationResult.TransportConnectTimeout)
+ {
+ HTTPManager.Logger.Warning("SignalR Connection", "OnHeartbeatUpdate - Transport failed to connect in the given time!");
+
+ // Using the Error function here instead of Close() will enable us to try to do a transport fallback.
+ (this as IConnection).Error("Transport failed to connect in the given time!");
+ }
+
+ break;
+ }
+ }
+
+ #endregion
+
+ #region Private Helper Functions
+
+ ///
+ /// Init function to set the connected states and set up other variables.
+ ///
+ private void InitOnStart()
+ {
+ this.State = ConnectionStates.Connected;
+
+ //ReconnectStartedAt = null;
+ ReconnectStarted = false;
+ TransportConnectionStartedAt = null;
+
+ LastPingSentAt = DateTime.UtcNow;
+ LastMessageReceivedAt = DateTime.UtcNow;
+
+ HTTPManager.Heartbeats.Subscribe(this);
+ }
+
+ ///
+ /// Find and return with a Hub that has the message id.
+ ///
+ private Hub FindHub(UInt64 msgId)
+ {
+ if (Hubs != null)
+ for (int i = 0; i < Hubs.Length; ++i)
+ if ((Hubs[i] as IHub).HasSentMessageId(msgId))
+ return Hubs[i];
+ return null;
+ }
+
+ ///
+ /// Try to fall back to next transport. If no more transport to try, it will return false.
+ ///
+ private bool TryFallbackTransport()
+ {
+ if (this.State == ConnectionStates.Connecting)
+ {
+ if (BufferedMessages != null)
+ BufferedMessages.Clear();
+
+ // stop the current transport
+ Transport.Stop();
+ Transport = null;
+
+ switch(NextProtocolToTry)
+ {
+#if !BESTHTTP_DISABLE_WEBSOCKET
+ case SupportedProtocols.WebSocket:
+ Transport = new WebSocketTransport(this);
+ break;
+#endif
+
+#if !BESTHTTP_DISABLE_SERVERSENT_EVENTS
+ case SupportedProtocols.ServerSentEvents:
+ Transport = new ServerSentEventsTransport(this);
+ NextProtocolToTry = SupportedProtocols.HTTP;
+ break;
+#endif
+
+ case SupportedProtocols.HTTP:
+ Transport = new PollingTransport(this);
+ NextProtocolToTry = SupportedProtocols.Unknown;
+ break;
+
+ case SupportedProtocols.Unknown:
+ return false;
+ }
+
+ TransportConnectionStartedAt = DateTime.UtcNow;
+
+ Transport.Connect();
+
+ if (PingRequest != null)
+ PingRequest.Abort();
+
+ return true;
+ }
+
+ return false;
+ }
+
+ ///
+ /// This event will be called when the AdditonalQueryPrams dictionary changed. We have to reset the cached values.
+ ///
+ private void AdditionalQueryParams_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
+ {
+ BuiltQueryParams = null;
+ }
+
+ #endregion
+
+ #region Ping Implementation
+
+ ///
+ /// Sends a Ping request to the SignalR server.
+ ///
+ private void Ping()
+ {
+ HTTPManager.Logger.Information("SignalR Connection", "Sending Ping request.");
+
+ PingRequest = new HTTPRequest((this as IConnection).BuildUri(RequestTypes.Ping), OnPingRequestFinished);
+ PingRequest.ConnectTimeout = PingInterval;
+
+ (this as IConnection).PrepareRequest(PingRequest, RequestTypes.Ping);
+
+ PingRequest.Send();
+
+ LastPingSentAt = DateTime.UtcNow;
+ }
+
+ ///
+ /// Called when the Ping request finished.
+ ///
+ void OnPingRequestFinished(HTTPRequest req, HTTPResponse resp)
+ {
+ PingRequest = null;
+
+ string reason = string.Empty;
+
+ switch (req.State)
+ {
+ // The request finished without any problem.
+ case HTTPRequestStates.Finished:
+ if (resp.IsSuccess)
+ {
+ // Parse the response, and do nothing when we receive the "pong" response
+ string response = (this as IConnection).ParseResponse(resp.DataAsText);
+
+ if (response != "pong")
+ reason = "Wrong answer for ping request: " + response;
+ else
+ HTTPManager.Logger.Information("SignalR Connection", "Pong received.");
+ }
+ else
+ reason = string.Format("Ping - Request Finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
+ resp.StatusCode,
+ resp.Message,
+ resp.DataAsText);
+ break;
+
+ // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
+ case HTTPRequestStates.Error:
+ reason = "Ping - Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception");
+ break;
+
+ // Connecting to the server is timed out.
+ case HTTPRequestStates.ConnectionTimedOut:
+ reason = "Ping - Connection Timed Out!";
+ break;
+
+ // The request didn't finished in the given time.
+ case HTTPRequestStates.TimedOut:
+ reason = "Ping - Processing the request Timed Out!";
+ break;
+ }
+
+ if (!string.IsNullOrEmpty(reason))
+ (this as IConnection).Error(reason);
+ }
+
+ #endregion
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Connection.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Connection.cs.meta
new file mode 100644
index 00000000..7d487bad
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Connection.cs.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: 878e20e1ec06ef542946893b5e37c3b6
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Enums.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Enums.cs
new file mode 100644
index 00000000..a1d78408
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Enums.cs
@@ -0,0 +1,196 @@
+#if !BESTHTTP_DISABLE_SIGNALR
+
+namespace BestHTTP.SignalR
+{
+ ///
+ /// Possible transport types.
+ ///
+ public enum TransportTypes
+ {
+ ///
+ /// Transport using WebSockets.
+ ///
+ WebSocket,
+
+ ///
+ /// Transport using ServerSentEvents protocol.
+ ///
+ ServerSentEvents,
+
+ ///
+ /// Transport using long-polling requests.
+ ///
+ LongPoll
+ }
+
+ ///
+ /// Server sent message types
+ ///
+ public enum MessageTypes
+ {
+ ///
+ /// An empty json object {} sent by the server to check keep alive.
+ ///
+ KeepAlive,
+
+ ///
+ /// A no-hub message that contains data.
+ ///
+ Data,
+
+ ///
+ /// A message that can hold multiple data message alongside with other information.
+ ///
+ Multiple,
+
+ ///
+ /// A method call result.
+ ///
+ Result,
+
+ ///
+ /// A message about a failed method call.
+ ///
+ Failure,
+
+ ///
+ /// A message with all information to be able to call a method on the client.
+ ///
+ MethodCall,
+
+ ///
+ /// A long running server-method's progress.
+ ///
+ Progress
+ }
+
+ ///
+ /// Possible SignalR Connection states.
+ ///
+ public enum ConnectionStates
+ {
+ ///
+ /// The initial state of the connection.
+ ///
+ Initial,
+
+ ///
+ /// The client authenticates itself with the server. This state is skipped if no AuthenticationProvider is present.
+ ///
+ Authenticating,
+
+ ///
+ /// The client sent out the negotiation request to the server.
+ ///
+ Negotiating,
+
+ ///
+ /// The client received the negotiation data, created the transport and wait's for the transport's connection.
+ ///
+ Connecting,
+
+ ///
+ /// The transport connected and started successfully.
+ ///
+ Connected,
+
+ ///
+ /// The client started the reconnect process.
+ ///
+ Reconnecting,
+
+ ///
+ /// The connection is closed.
+ ///
+ Closed
+ }
+
+ ///
+ /// Possible types of SignalR requests.
+ ///
+ public enum RequestTypes
+ {
+ ///
+ /// Request to the /negotiate path to negotiate protocol parameters.
+ ///
+ Negotiate,
+
+ ///
+ /// Request to the /connect path to connect to the server. With long-polling, it's like a regular poll request.
+ ///
+ Connect,
+
+ ///
+ /// Request to the /start path to start the protocol.
+ ///
+ Start,
+
+ ///
+ /// Request to the /poll path to get new messages. Not used with the WebSocketTransport.
+ ///
+ Poll,
+
+ ///
+ /// Request to the /send path to send a message to the server. Not used with the WebSocketTransport.
+ ///
+ Send,
+
+ ///
+ /// Request to the /reconnect path to initiate a reconnection. It's used instead of the Connect type.
+ ///
+ Reconnect,
+
+ ///
+ /// Request to the /abort path to close the connection.
+ ///
+ Abort,
+
+ ///
+ /// Request to the /ping path to ping the server keeping the asp.net session alive.
+ ///
+ Ping
+ }
+
+ ///
+ /// Possible states of a transport.
+ ///
+ public enum TransportStates
+ {
+ ///
+ /// Initial state
+ ///
+ Initial,
+
+ ///
+ /// Connecting
+ ///
+ Connecting,
+
+ ///
+ /// Reconnecting
+ ///
+ Reconnecting,
+
+ ///
+ /// Sending Start request
+ ///
+ Starting,
+
+ ///
+ /// Start request finished successfully
+ ///
+ Started,
+
+ ///
+ /// Sending Abort request
+ ///
+ Closing,
+
+ ///
+ /// The transport closed after Abort request sent
+ ///
+ Closed
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Enums.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Enums.cs.meta
new file mode 100644
index 00000000..1ed53210
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Enums.cs.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: fafa6e4c8bf63324c82241199e91f437
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Hubs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Hubs.meta
new file mode 100644
index 00000000..4060c0cd
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Hubs.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 7208796729371c74c9d7c3398b19f8f3
+folderAsset: yes
+DefaultImporter:
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Hubs/Hub.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Hubs/Hub.cs
new file mode 100644
index 00000000..5605ff41
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Hubs/Hub.cs
@@ -0,0 +1,391 @@
+#if !BESTHTTP_DISABLE_SIGNALR
+
+using System;
+using System.Collections.Generic;
+
+using BestHTTP.SignalR.Messages;
+using System.Text;
+
+namespace BestHTTP.SignalR.Hubs
+{
+ public delegate void OnMethodCallDelegate(Hub hub, string method, params object[] args);
+ public delegate void OnMethodCallCallbackDelegate(Hub hub, MethodCallMessage methodCall);
+
+ public delegate void OnMethodResultDelegate(Hub hub, ClientMessage originalMessage, ResultMessage result);
+ public delegate void OnMethodFailedDelegate(Hub hub, ClientMessage originalMessage, FailureMessage error);
+ public delegate void OnMethodProgressDelegate(Hub hub, ClientMessage originialMessage, ProgressMessage progress);
+
+ ///
+ /// Represents a clientside Hub. This class can be used as a base class to encapsulate proxy functionalities.
+ ///
+ public class Hub : IHub
+ {
+
+ #region Public Properties
+
+ ///
+ /// Name of this hub.
+ ///
+ public string Name { get; private set; }
+
+ ///
+ /// Server and user set state of the hub.
+ ///
+ public Dictionary State
+ {
+ // Create only when we need to.
+ get
+ {
+ if (state == null)
+ state = new Dictionary();
+ return state;
+ }
+ }
+ private Dictionary state;
+
+ ///
+ /// Event called every time when the server sends an order to call a method on the client.
+ ///
+ public event OnMethodCallDelegate OnMethodCall;
+
+ #endregion
+
+ #region Privates
+
+ ///
+ /// Table of the sent messages. These messages will be removed from this table when a Result message is received from the server.
+ ///
+ private Dictionary SentMessages = new Dictionary();
+
+ ///
+ /// Methodname -> callback delegate mapping. This table stores the server callable functions.
+ ///
+ private Dictionary MethodTable = new Dictionary();
+
+ ///
+ /// A reusable StringBuilder to save some GC allocs
+ ///
+ private StringBuilder builder = new StringBuilder();
+
+ #endregion
+
+ Connection IHub.Connection { get; set; }
+
+ public Hub(string name)
+ :this(name, null)
+ {
+
+ }
+
+ public Hub(string name, Connection manager)
+ {
+ this.Name = name;
+ (this as IHub).Connection = manager;
+ }
+
+ #region Public Hub Functions
+
+ ///
+ /// Registers a callback function to the given method.
+ ///
+ public void On(string method, OnMethodCallCallbackDelegate callback)
+ {
+ MethodTable[method] = callback;
+ }
+
+ ///
+ /// Removes callback from the given method.
+ ///
+ ///
+ public void Off(string method)
+ {
+ MethodTable[method] = null;
+ }
+
+ ///
+ /// Orders the server to call a method with the given arguments.
+ ///
+ /// True if the plugin was able to send out the message
+ public bool Call(string method, params object[] args)
+ {
+ return Call(method, null, null, null, args);
+ }
+
+ ///
+ /// Orders the server to call a method with the given arguments.
+ /// The onResult callback will be called when the server successfully called the function.
+ ///
+ /// True if the plugin was able to send out the message
+ public bool Call(string method, OnMethodResultDelegate onResult, params object[] args)
+ {
+ return Call(method, onResult, null, null, args);
+ }
+
+ ///
+ /// Orders the server to call a method with the given arguments.
+ /// The onResult callback will be called when the server successfully called the function.
+ /// The onResultError will be called when the server can't call the function, or when the function throws an exception.
+ ///
+ /// True if the plugin was able to send out the message
+ public bool Call(string method, OnMethodResultDelegate onResult, OnMethodFailedDelegate onResultError, params object[] args)
+ {
+ return Call(method, onResult, onResultError, null, args);
+ }
+
+ ///
+ /// Orders the server to call a method with the given arguments.
+ /// The onResult callback will be called when the server successfully called the function.
+ /// The onProgress callback called multiple times when the method is a long running function and reports back its progress.
+ ///
+ /// True if the plugin was able to send out the message
+ public bool Call(string method, OnMethodResultDelegate onResult, OnMethodProgressDelegate onProgress, params object[] args)
+ {
+ return Call(method, onResult, null, onProgress, args);
+ }
+
+ ///
+ /// Orders the server to call a method with the given arguments.
+ /// The onResult callback will be called when the server successfully called the function.
+ /// The onResultError will be called when the server can't call the function, or when the function throws an exception.
+ /// The onProgress callback called multiple times when the method is a long running function and reports back its progress.
+ ///
+ /// True if the plugin was able to send out the message
+ public bool Call(string method, OnMethodResultDelegate onResult, OnMethodFailedDelegate onResultError, OnMethodProgressDelegate onProgress, params object[] args)
+ {
+ IHub thisHub = this as IHub;
+
+ lock (thisHub.Connection.SyncRoot)
+ {
+ // Start over the counter if we are reached the max value if the UInt64 type.
+ // While we are using this property only here, we don't want to make it static to avoid another thread synchronization, neither we want to make it a Hub-instance field to achieve better deuggability.
+ thisHub.Connection.ClientMessageCounter %= UInt64.MaxValue;
+
+ // Create and send the client message
+ return thisHub.Call(new ClientMessage(this, method, args, thisHub.Connection.ClientMessageCounter++, onResult, onResultError, onProgress));
+ }
+ }
+
+ #endregion
+
+ #region IHub Implementation
+
+ bool IHub.Call(ClientMessage msg)
+ {
+ IHub thisHub = this as IHub;
+
+ lock (thisHub.Connection.SyncRoot)
+ {
+ if (!thisHub.Connection.SendJson(BuildMessage(msg)))
+ return false;
+
+ SentMessages.Add(msg.CallIdx, msg);
+ }
+
+ return true;
+ }
+
+ ///
+ /// Return true if this hub sent the message with the given id.
+ ///
+ bool IHub.HasSentMessageId(UInt64 id)
+ {
+ return SentMessages.ContainsKey(id);
+ }
+
+ ///
+ /// Called on the manager's close.
+ ///
+ void IHub.Close()
+ {
+ SentMessages.Clear();
+ }
+
+ ///
+ /// Called when the client receives an order to call a hub-function.
+ ///
+ void IHub.OnMethod(MethodCallMessage msg)
+ {
+ // Merge the newly received states with the old one
+ MergeState(msg.State);
+
+ if (OnMethodCall != null)
+ {
+ try
+ {
+ OnMethodCall(this, msg.Method, msg.Arguments);
+ }
+ catch(Exception ex)
+ {
+ HTTPManager.Logger.Exception("Hub - " + this.Name, "IHub.OnMethod - OnMethodCall", ex);
+ }
+ }
+
+ OnMethodCallCallbackDelegate callback;
+ if (MethodTable.TryGetValue(msg.Method, out callback) && callback != null)
+ {
+ try
+ {
+ callback(this, msg);
+ }
+ catch(Exception ex)
+ {
+ HTTPManager.Logger.Exception("Hub - " + this.Name, "IHub.OnMethod - callback", ex);
+ }
+ }
+ else if (OnMethodCall == null)
+ HTTPManager.Logger.Warning("Hub - " + this.Name, string.Format("[Client] {0}.{1} (args: {2})", this.Name, msg.Method, msg.Arguments.Length));
+ }
+
+ ///
+ /// Called when the client receives back messages as a result of a server method call.
+ ///
+ void IHub.OnMessage(IServerMessage msg)
+ {
+ ClientMessage originalMsg;
+
+ UInt64 id = (msg as IHubMessage).InvocationId;
+ if (!SentMessages.TryGetValue(id, out originalMsg))
+ {
+ // This can happen when a result message removes the ClientMessage from the SentMessages dictionary,
+ // then a late come progress message tries to access it
+ HTTPManager.Logger.Warning("Hub - " + this.Name, "OnMessage - Sent message not found with id: " + id.ToString());
+ return;
+ }
+
+ switch(msg.Type)
+ {
+ case MessageTypes.Result:
+ ResultMessage result = msg as ResultMessage;
+
+ // Merge the incoming State before firing the events
+ MergeState(result.State);
+
+ if (originalMsg.ResultCallback != null)
+ {
+ try
+ {
+ originalMsg.ResultCallback(this, originalMsg, result);
+ }
+ catch(Exception ex)
+ {
+ HTTPManager.Logger.Exception("Hub " + this.Name, "IHub.OnMessage - ResultCallback", ex);
+ }
+ }
+
+ SentMessages.Remove(id);
+
+ break;
+
+ case MessageTypes.Failure:
+ FailureMessage error = msg as FailureMessage;
+
+ // Merge the incoming State before firing the events
+ MergeState(error.State);
+
+ if (originalMsg.ResultErrorCallback != null)
+ {
+ try
+ {
+ originalMsg.ResultErrorCallback(this, originalMsg, error);
+ }
+ catch(Exception ex)
+ {
+ HTTPManager.Logger.Exception("Hub " + this.Name, "IHub.OnMessage - ResultErrorCallback", ex);
+ }
+ }
+
+ SentMessages.Remove(id);
+ break;
+
+ case MessageTypes.Progress:
+ if (originalMsg.ProgressCallback != null)
+ {
+ try
+ {
+ originalMsg.ProgressCallback(this, originalMsg, msg as ProgressMessage);
+ }
+ catch(Exception ex)
+ {
+ HTTPManager.Logger.Exception("Hub " + this.Name, "IHub.OnMessage - ProgressCallback", ex);
+ }
+ }
+ break;
+ }
+ }
+
+ #endregion
+
+ #region Helper Functions
+
+ ///
+ /// Merges the current and the new states.
+ ///
+#if BESTHTTP_SIGNALR_WITH_JSONDOTNET
+ private void MergeState(IDictionary state)
+#else
+ private void MergeState(IDictionary state)
+#endif
+ {
+ if (state != null && state.Count > 0)
+ foreach (var kvp in state)
+ this.State[kvp.Key] = kvp.Value;
+ }
+
+ ///
+ /// Builds a JSon string from the given message.
+ ///
+ private string BuildMessage(ClientMessage msg)
+ {
+ try
+ {
+ builder.Append("{\"H\":\"");
+ builder.Append(this.Name);
+ builder.Append("\",\"M\":\"");
+ builder.Append(msg.Method);
+ builder.Append("\",\"A\":");
+
+ string jsonEncoded = string.Empty;
+
+ // Arguments
+ if (msg.Args != null && msg.Args.Length > 0)
+ jsonEncoded = (this as IHub).Connection.JsonEncoder.Encode(msg.Args);
+ else
+ jsonEncoded = "[]";
+
+ builder.Append(jsonEncoded);
+
+ builder.Append(",\"I\":\"");
+ builder.Append(msg.CallIdx.ToString());
+ builder.Append("\"");
+
+ // State, if any
+ if (msg.Hub.state != null && msg.Hub.state.Count > 0)
+ {
+ builder.Append(",\"S\":");
+
+ jsonEncoded = (this as IHub).Connection.JsonEncoder.Encode(msg.Hub.state);
+ builder.Append(jsonEncoded);
+ }
+
+ builder.Append("}");
+
+ return builder.ToString();
+ }
+ catch (Exception ex)
+ {
+ HTTPManager.Logger.Exception("Hub - " + this.Name, "Send", ex);
+
+ return null;
+ }
+ finally
+ {
+ // reset the StringBuilder instance, to reuse next time
+ builder.Length = 0;
+ }
+ }
+
+ #endregion
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Hubs/Hub.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Hubs/Hub.cs.meta
new file mode 100644
index 00000000..ee76d02b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Hubs/Hub.cs.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: 00b4b8fd0e14de941b796a56a1272233
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Hubs/IHub.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Hubs/IHub.cs
new file mode 100644
index 00000000..5426c293
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Hubs/IHub.cs
@@ -0,0 +1,24 @@
+#if !BESTHTTP_DISABLE_SIGNALR
+
+using System;
+
+using BestHTTP.SignalR.Messages;
+
+namespace BestHTTP.SignalR.Hubs
+{
+ ///
+ /// Interface to be able to hide internally used functions and properties.
+ ///
+ public interface IHub
+ {
+ Connection Connection { get; set; }
+
+ bool Call(ClientMessage msg);
+ bool HasSentMessageId(UInt64 id);
+ void Close();
+ void OnMethod(MethodCallMessage msg);
+ void OnMessage(IServerMessage msg);
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Hubs/IHub.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Hubs/IHub.cs.meta
new file mode 100644
index 00000000..78982e77
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Hubs/IHub.cs.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: 1813781a232e6c74ba3e00896327ace6
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/JsonEncoders.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/JsonEncoders.meta
new file mode 100644
index 00000000..794d22c3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/JsonEncoders.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: c593c51184e979a4d8e4bb2cc2a9b1d0
+folderAsset: yes
+DefaultImporter:
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/JsonEncoders/DefaultJsonEncoder.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/JsonEncoders/DefaultJsonEncoder.cs
new file mode 100644
index 00000000..cc6c3c18
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/JsonEncoders/DefaultJsonEncoder.cs
@@ -0,0 +1,24 @@
+#if !BESTHTTP_DISABLE_SIGNALR
+
+using BestHTTP.JSON;
+using System.Collections.Generic;
+
+namespace BestHTTP.SignalR.JsonEncoders
+{
+ public sealed class DefaultJsonEncoder : IJsonEncoder
+ {
+ public string Encode(object obj)
+ {
+ return Json.Encode(obj);
+ }
+
+ public IDictionary DecodeMessage(string json)
+ {
+ bool ok = false;
+ IDictionary result = Json.Decode(json, ref ok) as IDictionary;
+ return ok ? result : null;
+ }
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/JsonEncoders/DefaultJsonEncoder.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/JsonEncoders/DefaultJsonEncoder.cs.meta
new file mode 100644
index 00000000..d6d0d4ed
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/JsonEncoders/DefaultJsonEncoder.cs.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: 1a4bf647dcdcdbf44ab1edc744192ca0
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/JsonEncoders/IJsonEncoder.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/JsonEncoders/IJsonEncoder.cs
new file mode 100644
index 00000000..7304031f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/JsonEncoders/IJsonEncoder.cs
@@ -0,0 +1,24 @@
+#if !BESTHTTP_DISABLE_SIGNALR
+
+using System.Collections.Generic;
+
+namespace BestHTTP.SignalR.JsonEncoders
+{
+ ///
+ /// Interface to be able to write custom Json encoders/decoders.
+ ///
+ public interface IJsonEncoder
+ {
+ ///
+ /// This function must create a json formatted string from the given object. If the encoding fails, it should return null.
+ ///
+ string Encode(object obj);
+
+ ///
+ /// This function must create a dictionary the Json formatted string parameter. If the decoding fails, it should return null.
+ ///
+ IDictionary DecodeMessage(string json);
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/JsonEncoders/IJsonEncoder.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/JsonEncoders/IJsonEncoder.cs.meta
new file mode 100644
index 00000000..ce9466d3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/JsonEncoders/IJsonEncoder.cs.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: b494cd3e9ad9bd243bd68251a27c86b9
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Messages.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Messages.meta
new file mode 100644
index 00000000..ad774686
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Messages.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 3ea7772f76aa54748aa8b466ba3113a9
+folderAsset: yes
+DefaultImporter:
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Messages/ClientMessage.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Messages/ClientMessage.cs
new file mode 100644
index 00000000..c1c4c867
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Messages/ClientMessage.cs
@@ -0,0 +1,71 @@
+#if !BESTHTTP_DISABLE_SIGNALR
+
+using System;
+
+using BestHTTP.SignalR.Hubs;
+
+namespace BestHTTP.SignalR.Messages
+{
+ ///
+ /// This struct represents a message from the client.
+ /// It holds every data and reference needed to construct the string represented message that will be sent to the wire.
+ ///
+ public struct ClientMessage
+ {
+ ///
+ /// Reference to the source Hub. The Name and the State of the hub will be user.
+ ///
+ public readonly Hub Hub;
+
+ ///
+ /// Name of the method on the server to be called.
+ ///
+ public readonly string Method;
+
+ ///
+ /// Arguments of the method.
+ ///
+ public readonly object[] Args;
+
+ ///
+ /// Unique id on the client of this message
+ ///
+ public readonly UInt64 CallIdx;
+
+ ///
+ /// The delegate that will be called when the server will sends a result of this method call.
+ ///
+ public readonly OnMethodResultDelegate ResultCallback;
+
+ ///
+ /// The delegate that will be called when the server sends an error-result to this method call.
+ ///
+ public readonly OnMethodFailedDelegate ResultErrorCallback;
+
+ ///
+ /// The delegate that will be called when the server sends a progress message to this method call.
+ ///
+ public readonly OnMethodProgressDelegate ProgressCallback;
+
+ public ClientMessage(Hub hub,
+ string method,
+ object[] args,
+ UInt64 callIdx,
+ OnMethodResultDelegate resultCallback,
+ OnMethodFailedDelegate resultErrorCallback,
+ OnMethodProgressDelegate progressCallback)
+ {
+ Hub = hub;
+ Method = method;
+ Args = args;
+
+ CallIdx = callIdx;
+
+ ResultCallback = resultCallback;
+ ResultErrorCallback = resultErrorCallback;
+ ProgressCallback = progressCallback;
+ }
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Messages/ClientMessage.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Messages/ClientMessage.cs.meta
new file mode 100644
index 00000000..658559cb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Messages/ClientMessage.cs.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: af18bb2021dd2f045b2d168d5769fab1
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Messages/IServerMessage.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Messages/IServerMessage.cs
new file mode 100644
index 00000000..c5ffb288
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Messages/IServerMessage.cs
@@ -0,0 +1,19 @@
+#if !BESTHTTP_DISABLE_SIGNALR
+
+using System;
+
+namespace BestHTTP.SignalR.Messages
+{
+ public interface IServerMessage
+ {
+ MessageTypes Type { get; }
+ void Parse(object data);
+ }
+
+ public interface IHubMessage
+ {
+ UInt64 InvocationId { get; }
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Messages/IServerMessage.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Messages/IServerMessage.cs.meta
new file mode 100644
index 00000000..278f6781
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Messages/IServerMessage.cs.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: 25c60db0524552144bf03b547ae8a585
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Messages/ServerMessages.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Messages/ServerMessages.cs
new file mode 100644
index 00000000..8f82c5b6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Messages/ServerMessages.cs
@@ -0,0 +1,354 @@
+#if !BESTHTTP_DISABLE_SIGNALR
+
+#if BESTHTTP_SIGNALR_WITH_JSONDOTNET
+using Newtonsoft.Json.Linq;
+#endif
+using System;
+using System.Collections;
+using System.Collections.Generic;
+
+namespace BestHTTP.SignalR.Messages
+{
+ ///
+ /// Keep-alive message sent by the server. No data sent with it.
+ ///
+ public sealed class KeepAliveMessage : IServerMessage
+ {
+ MessageTypes IServerMessage.Type { get { return MessageTypes.KeepAlive; } }
+ void IServerMessage.Parse(object data) { }
+ }
+
+ ///
+ /// A message that may contains multiple sub-messages and additional informations.
+ ///
+ public sealed class MultiMessage : IServerMessage
+ {
+ MessageTypes IServerMessage.Type { get { return MessageTypes.Multiple; } }
+
+ ///
+ /// Id of the sent message
+ ///
+ public string MessageId { get; private set; }
+
+ ///
+ /// True if it's an initialization message, false otherwise.
+ ///
+ public bool IsInitialization { get; private set; }
+
+ ///
+ /// Group token may be sent, if the group changed that the client belongs to.
+ ///
+ public string GroupsToken { get; private set; }
+
+ ///
+ /// The server suggests that the client should do a reconnect turn.
+ ///
+ public bool ShouldReconnect { get; private set; }
+
+ ///
+ /// Additional poll delay sent by the server.
+ ///
+ public TimeSpan? PollDelay { get; private set; }
+
+ ///
+ /// List of server messages sent inside this message.
+ ///
+ public List Data { get; private set; }
+
+ void IServerMessage.Parse(object data)
+ {
+ IDictionary dic = data as IDictionary;
+ object value;
+
+ this.MessageId = dic["C"].ToString();
+
+ if (dic.TryGetValue("S", out value))
+ IsInitialization = int.Parse(value.ToString()) == 1 ? true : false;
+ else
+ IsInitialization = false;
+
+ if (dic.TryGetValue("G", out value))
+ GroupsToken = value.ToString();
+
+ if (dic.TryGetValue("T", out value))
+ ShouldReconnect = int.Parse(value.ToString()) == 1 ? true : false;
+ else
+ ShouldReconnect = false;
+
+ if (dic.TryGetValue("L", out value))
+ PollDelay = TimeSpan.FromMilliseconds(double.Parse(value.ToString()));
+
+ IEnumerable enumerable = dic["M"] as IEnumerable;
+
+ if (enumerable != null)
+ {
+ Data = new List();
+
+ foreach (object subData in enumerable)
+ {
+#if BESTHTTP_SIGNALR_WITH_JSONDOTNET
+ IDictionary subObj = subData as IDictionary;
+#else
+ IDictionary subObj = subData as IDictionary;
+#endif
+
+ IServerMessage subMsg = null;
+
+ if (subObj != null)
+ {
+ if (subObj.ContainsKey("H"))
+ subMsg = new MethodCallMessage();
+ else if (subObj.ContainsKey("I"))
+ subMsg = new ProgressMessage();
+ else
+ subMsg = new DataMessage();
+ }
+ else
+ subMsg = new DataMessage();
+
+ subMsg.Parse(subData);
+
+ Data.Add(subMsg);
+ }
+ }
+ }
+ }
+
+ ///
+ /// A simple non-hub data message. It holds only one Data property.
+ ///
+ public sealed class DataMessage : IServerMessage
+ {
+ MessageTypes IServerMessage.Type { get { return MessageTypes.Data; } }
+
+ public object Data { get; private set; }
+
+ void IServerMessage.Parse(object data)
+ {
+ this.Data = data;
+ }
+ }
+
+ ///
+ /// A Hub message that orders the client to call a method.
+ ///
+ public sealed class MethodCallMessage : IServerMessage
+ {
+ MessageTypes IServerMessage.Type { get { return MessageTypes.MethodCall; } }
+
+ ///
+ /// The name of the Hub that the method is called on.
+ ///
+ public string Hub { get; private set; }
+
+ ///
+ /// Name of the Method.
+ ///
+ public string Method { get; private set; }
+
+ ///
+ /// Arguments of the method call.
+ ///
+ public object[] Arguments { get; private set; }
+
+ ///
+ /// State changes of the hub. It's handled automatically by the Hub.
+ ///
+#if BESTHTTP_SIGNALR_WITH_JSONDOTNET
+ public IDictionary State { get; private set; }
+#else
+ public IDictionary State { get; private set; }
+#endif
+
+ void IServerMessage.Parse(object data)
+ {
+ #if BESTHTTP_SIGNALR_WITH_JSONDOTNET
+ IDictionary dic = data as IDictionary;
+ #else
+ IDictionary dic = data as IDictionary;
+ #endif
+
+ Hub = dic["H"].ToString();
+ Method = dic["M"].ToString();
+
+ List args = new List();
+ foreach (object arg in dic["A"] as IEnumerable)
+ args.Add(arg);
+ Arguments = args.ToArray();
+
+#if BESTHTTP_SIGNALR_WITH_JSONDOTNET
+ JToken value;
+ if (dic.TryGetValue("S", out value))
+ State = value as IDictionary;
+#else
+ object value;
+ if (dic.TryGetValue("S", out value))
+ State = value as IDictionary;
+#endif
+ }
+ }
+
+ ///
+ /// Message of a server side method invocation result.
+ ///
+ public sealed class ResultMessage : IServerMessage, IHubMessage
+ {
+ MessageTypes IServerMessage.Type { get { return MessageTypes.Result; } }
+
+ ///
+ /// The unique id that the client set when called the server side method. Used by the plugin to deliver this message to the good Hub.
+ ///
+ public UInt64 InvocationId { get; private set; }
+
+ ///
+ /// The return value of the server side method call, or null if the method's return type is void.
+ ///
+ public object ReturnValue { get; private set; }
+
+ ///
+ /// State changes of the hub. It's handled automatically by the Hub.
+ ///
+#if BESTHTTP_SIGNALR_WITH_JSONDOTNET
+ public IDictionary State { get; private set; }
+#else
+ public IDictionary State { get; private set; }
+#endif
+
+ void IServerMessage.Parse(object data)
+ {
+ IDictionary dic = data as IDictionary;
+
+ InvocationId = UInt64.Parse(dic["I"].ToString());
+
+ object value;
+ if (dic.TryGetValue("R", out value))
+ ReturnValue = value;
+
+ if (dic.TryGetValue("S", out value))
+ {
+#if BESTHTTP_SIGNALR_WITH_JSONDOTNET
+ State = value as IDictionary;
+#else
+ State = value as IDictionary;
+#endif
+ }
+ }
+ }
+
+ public sealed class FailureMessage : IServerMessage, IHubMessage
+ {
+ MessageTypes IServerMessage.Type { get { return MessageTypes.Failure; } }
+
+ ///
+ /// The unique id that the client set when called the server side method. Used by the plugin to deliver this message to the good Hub.
+ ///
+ public UInt64 InvocationId { get; private set; }
+
+ ///
+ /// True if it's a hub error.
+ ///
+ public bool IsHubError { get; private set; }
+
+ ///
+ /// If the method call failed, it contains the error message to detail what happened.
+ ///
+ public string ErrorMessage { get; private set; }
+
+ ///
+ /// A dictionary that may contain additional error data (can only be present for hub errors). It can be null.
+ ///
+#if BESTHTTP_SIGNALR_WITH_JSONDOTNET
+ public IDictionary AdditionalData { get; private set; }
+#else
+ public IDictionary AdditionalData { get; private set; }
+#endif
+
+ ///
+ /// Stack trace of the error. It present only if detailed error reporting is turned on on the server (https://msdn.microsoft.com/en-us/library/microsoft.aspnet.signalr.hubconfiguration.enabledetailederrors%28v=vs.118%29.aspx).
+ ///
+ public string StackTrace { get; private set; }
+
+ ///
+ /// State changes of the hub. It's handled automatically by the Hub.
+ ///
+#if BESTHTTP_SIGNALR_WITH_JSONDOTNET
+ public IDictionary State { get; private set; }
+#else
+ public IDictionary State { get; private set; }
+#endif
+
+ void IServerMessage.Parse(object data)
+ {
+ IDictionary dic = data as IDictionary;
+
+ InvocationId = UInt64.Parse(dic["I"].ToString());
+
+ object value;
+
+ if (dic.TryGetValue("E", out value))
+ ErrorMessage = value.ToString();
+
+ if (dic.TryGetValue("H", out value))
+ IsHubError = int.Parse(value.ToString()) == 1 ? true : false;
+
+ if (dic.TryGetValue("D", out value))
+ {
+#if BESTHTTP_SIGNALR_WITH_JSONDOTNET
+ AdditionalData = value as IDictionary;
+#else
+ AdditionalData = value as IDictionary;
+#endif
+ }
+
+ if (dic.TryGetValue("T", out value))
+ StackTrace = value.ToString();
+
+ if (dic.TryGetValue("S", out value))
+ {
+#if BESTHTTP_SIGNALR_WITH_JSONDOTNET
+ State = value as IDictionary;
+#else
+ State = value as IDictionary;
+#endif
+ }
+ }
+ }
+
+ ///
+ /// When a server method is a long running method the server can send the information about the progress of execution of the method to the client.
+ ///
+ public sealed class ProgressMessage : IServerMessage, IHubMessage
+ {
+ MessageTypes IServerMessage.Type { get { return MessageTypes.Progress; } }
+
+ ///
+ /// The unique id that the client set when called the server side method. Used by the plugin to deliver this message to the good Hub.
+ ///
+ public UInt64 InvocationId { get; private set; }
+
+ ///
+ /// Current progress of the long running method.
+ ///
+ public double Progress { get; private set; }
+
+ void IServerMessage.Parse(object data)
+ {
+#if BESTHTTP_SIGNALR_WITH_JSONDOTNET
+ IDictionary dic = data as IDictionary;
+#else
+ IDictionary dic = data as IDictionary;
+#endif
+
+#if BESTHTTP_SIGNALR_WITH_JSONDOTNET
+ IDictionary P = dic["P"] as IDictionary;
+#else
+ IDictionary P = dic["P"] as IDictionary;
+#endif
+
+ InvocationId = UInt64.Parse(P["I"].ToString());
+ Progress = double.Parse(P["D"].ToString());
+ }
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Messages/ServerMessages.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Messages/ServerMessages.cs.meta
new file mode 100644
index 00000000..eb21219b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Messages/ServerMessages.cs.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: a128625937e3c5b459b3aa221061a03f
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/NegotiationData.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/NegotiationData.cs
new file mode 100644
index 00000000..989f81f3
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/NegotiationData.cs
@@ -0,0 +1,276 @@
+#if !BESTHTTP_DISABLE_SIGNALR
+
+using System;
+using System.Collections.Generic;
+
+using BestHTTP.JSON;
+
+namespace BestHTTP.SignalR
+{
+ public sealed class NegotiationData
+ {
+ #region Public Negotiate data
+
+ ///
+ /// Path to the SignalR endpoint. Currently not used by the client.
+ ///
+ public string Url { get; private set; }
+
+ ///
+ /// WebSocket endpoint.
+ ///
+ public string WebSocketServerUrl { get; private set; }
+
+ ///
+ /// Connection token assigned by the server. See this article for more details: http://www.asp.net/signalr/overview/security/introduction-to-security#connectiontoken.
+ /// This value needs to be sent in each subsequent request as the value of the connectionToken parameter
+ ///
+ public string ConnectionToken { get; private set; }
+
+ ///
+ /// The id of the connection.
+ ///
+ public string ConnectionId { get; private set; }
+
+ ///
+ /// The amount of time in seconds the client should wait before attempting to reconnect if it has not received a keep alive message.
+ /// If the server is configured to not send keep alive messages this value is null.
+ ///
+ public TimeSpan? KeepAliveTimeout { get; private set; }
+
+ ///
+ /// The amount of time within which the client should try to reconnect if the connection goes away.
+ ///
+ public TimeSpan DisconnectTimeout { get; private set; }
+
+ ///
+ /// Timeout of poll requests.
+ ///
+ public TimeSpan ConnectionTimeout { get; private set; }
+
+ ///
+ /// Whether the server supports websockets.
+ ///
+ public bool TryWebSockets { get; private set; }
+
+ ///
+ /// The version of the protocol used for communication.
+ ///
+ public string ProtocolVersion { get; private set; }
+
+ ///
+ /// The maximum amount of time the client should try to connect to the server using a given transport.
+ ///
+ public TimeSpan TransportConnectTimeout { get; private set; }
+
+ ///
+ /// The wait time before restablishing a long poll connection after data is sent from the server. The default value is 0.
+ ///
+ public TimeSpan LongPollDelay { get; private set; }
+
+ #endregion
+
+ #region Event Handlers
+
+ ///
+ /// Event handler that called when the negotiation data received and parsed successfully.
+ ///
+ public Action OnReceived;
+
+ ///
+ /// Event handler that called when an error happens.
+ ///
+ public Action OnError;
+
+ #endregion
+
+ #region Private
+
+ private HTTPRequest NegotiationRequest;
+ private IConnection Connection;
+
+ #endregion
+
+ public NegotiationData(Connection connection)
+ {
+ this.Connection = connection;
+ }
+
+ ///
+ /// Start to get the negotiation data.
+ ///
+ public void Start()
+ {
+ NegotiationRequest = new HTTPRequest(Connection.BuildUri(RequestTypes.Negotiate), HTTPMethods.Get, true, true, OnNegotiationRequestFinished);
+ Connection.PrepareRequest(NegotiationRequest, RequestTypes.Negotiate);
+ NegotiationRequest.Send();
+
+ HTTPManager.Logger.Information("NegotiationData", "Negotiation request sent");
+ }
+
+ ///
+ /// Abort the negotiation request.
+ ///
+ public void Abort()
+ {
+ if (NegotiationRequest != null)
+ {
+ OnReceived = null;
+ OnError = null;
+ NegotiationRequest.Abort();
+ }
+ }
+
+ #region Request Event Handler
+
+ private void OnNegotiationRequestFinished(HTTPRequest req, HTTPResponse resp)
+ {
+ NegotiationRequest = null;
+
+ switch (req.State)
+ {
+ case HTTPRequestStates.Finished:
+ if (resp.IsSuccess)
+ {
+ HTTPManager.Logger.Information("NegotiationData", "Negotiation data arrived: " + resp.DataAsText);
+
+ int idx = resp.DataAsText.IndexOf("{");
+ if (idx < 0)
+ {
+ RaiseOnError("Invalid negotiation text: " + resp.DataAsText);
+ return;
+ }
+
+ var Negotiation = Parse(resp.DataAsText.Substring(idx));
+
+ if (Negotiation == null)
+ {
+ RaiseOnError("Parsing Negotiation data failed: " + resp.DataAsText);
+ return;
+ }
+
+ if (OnReceived != null)
+ {
+ OnReceived(this);
+ OnReceived = null;
+ }
+ }
+ else
+ RaiseOnError(string.Format("Negotiation request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2} Uri: {3}",
+ resp.StatusCode,
+ resp.Message,
+ resp.DataAsText,
+ req.CurrentUri));
+ break;
+
+ case HTTPRequestStates.Error:
+ RaiseOnError(req.Exception != null ? (req.Exception.Message + " " + req.Exception.StackTrace) : string.Empty);
+ break;
+
+ default:
+ RaiseOnError(req.State.ToString());
+ break;
+ }
+ }
+
+ #endregion
+
+ #region Helper Methods
+
+ private void RaiseOnError(string err)
+ {
+ HTTPManager.Logger.Error("NegotiationData", "Negotiation request failed with error: " + err);
+
+ if (OnError != null)
+ {
+ OnError(this, err);
+ OnError = null;
+ }
+ }
+
+ private NegotiationData Parse(string str)
+ {
+ bool success = false;
+ Dictionary dict = Json.Decode(str, ref success) as Dictionary;
+ if (!success)
+ return null;
+
+ try
+ {
+ this.Url = GetString(dict, "Url");
+
+ if (dict.ContainsKey("webSocketServerUrl"))
+ this.WebSocketServerUrl = GetString(dict, "webSocketServerUrl");
+
+ this.ConnectionToken = Uri.EscapeDataString(GetString(dict, "ConnectionToken"));
+ this.ConnectionId = GetString(dict, "ConnectionId");
+
+ if (dict.ContainsKey("KeepAliveTimeout"))
+ this.KeepAliveTimeout = TimeSpan.FromSeconds(GetDouble(dict, "KeepAliveTimeout"));
+
+ this.DisconnectTimeout = TimeSpan.FromSeconds(GetDouble(dict, "DisconnectTimeout"));
+
+ if (dict.ContainsKey("ConnectionTimeout"))
+ this.ConnectionTimeout = TimeSpan.FromSeconds(GetDouble(dict, "ConnectionTimeout"));
+ else
+ this.ConnectionTimeout = TimeSpan.FromSeconds(120);
+
+ this.TryWebSockets = (bool)Get(dict, "TryWebSockets");
+ this.ProtocolVersion = GetString(dict, "ProtocolVersion");
+ this.TransportConnectTimeout = TimeSpan.FromSeconds(GetDouble(dict, "TransportConnectTimeout"));
+
+ if (dict.ContainsKey("LongPollDelay"))
+ this.LongPollDelay = TimeSpan.FromSeconds(GetDouble(dict, "LongPollDelay"));
+ }
+ catch(Exception ex)
+ {
+ HTTPManager.Logger.Exception("NegotiationData", "Parse", ex);
+ return null;
+ }
+
+ return this;
+ }
+
+ private static object Get(Dictionary from, string key)
+ {
+ object value;
+ if (!from.TryGetValue(key, out value))
+ throw new System.Exception(string.Format("Can't get {0} from Negotiation data!", key));
+ return value;
+ }
+
+ private static string GetString(Dictionary from, string key)
+ {
+ return Get(from, key) as string;
+ }
+
+ private static List GetStringList(Dictionary from, string key)
+ {
+ List value = Get(from, key) as List;
+
+ List result = new List(value.Count);
+ for (int i = 0; i < value.Count; ++i)
+ {
+ string str = value[i] as string;
+ if (str != null)
+ result.Add(str);
+ }
+
+ return result;
+ }
+
+ private static int GetInt(Dictionary from, string key)
+ {
+ return (int)(double)Get(from, key);
+ }
+
+ private static double GetDouble(Dictionary from, string key)
+ {
+ return (double)Get(from, key);
+ }
+
+ #endregion
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/NegotiationData.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/NegotiationData.cs.meta
new file mode 100644
index 00000000..69855b5a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/NegotiationData.cs.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: c20f605e63af7ef4eb7782aa663f0196
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports.meta
new file mode 100644
index 00000000..7a14d7a5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: c390001e221f7e1429a38eb6222413c5
+folderAsset: yes
+DefaultImporter:
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/PollingTransport.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/PollingTransport.cs
new file mode 100644
index 00000000..a77a0cfe
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/PollingTransport.cs
@@ -0,0 +1,256 @@
+#if !BESTHTTP_DISABLE_SIGNALR
+
+using System;
+
+using BestHTTP.Extensions;
+using BestHTTP.SignalR.Messages;
+
+namespace BestHTTP.SignalR.Transports
+{
+ public sealed class PollingTransport : PostSendTransportBase, IHeartbeat
+ {
+ #region Overridden Properties
+
+ public override bool SupportsKeepAlive { get { return false; } }
+ public override TransportTypes Type { get { return TransportTypes.LongPoll; } }
+
+ #endregion
+
+ #region Privates
+
+ ///
+ /// When we received the last poll.
+ ///
+ private DateTime LastPoll;
+
+ ///
+ /// How much time we have to wait before we can send out a new poll request. This value sent by the server.
+ ///
+ private TimeSpan PollDelay;
+
+ ///
+ /// How much time we wait to a poll request to finish. It's value is the server sent negotiation's ConnectionTimeout + 10sec.
+ ///
+ private TimeSpan PollTimeout;
+
+ ///
+ /// Reference to the the current poll request.
+ ///
+ private HTTPRequest pollRequest;
+
+ #endregion
+
+ public PollingTransport(Connection connection)
+ : base("longPolling", connection)
+ {
+ this.LastPoll = DateTime.MinValue;
+ this.PollTimeout = connection.NegotiationResult.ConnectionTimeout + TimeSpan.FromSeconds(10);
+ }
+
+ #region Overrides from TransportBase
+
+ ///
+ /// Polling transport specific connection logic. It's a regular GET request to the /connect path.
+ ///
+ public override void Connect()
+ {
+ HTTPManager.Logger.Information("Transport - " + this.Name, "Sending Open Request");
+
+ // Skip the Connecting state if we are reconnecting. If the connect succeeds, we will set the Started state directly
+ if (this.State != TransportStates.Reconnecting)
+ this.State = TransportStates.Connecting;
+
+ RequestTypes requestType = this.State == TransportStates.Reconnecting ? RequestTypes.Reconnect : RequestTypes.Connect;
+
+ var request = new HTTPRequest(Connection.BuildUri(requestType, this), HTTPMethods.Get, true, true, OnConnectRequestFinished);
+
+ Connection.PrepareRequest(request, requestType);
+
+ request.Send();
+ }
+
+ public override void Stop()
+ {
+ HTTPManager.Heartbeats.Unsubscribe(this);
+
+ if (pollRequest != null)
+ {
+ pollRequest.Abort();
+ pollRequest = null;
+ }
+
+ // Should we abort the send requests in the sendRequestQueue?
+ }
+
+ protected override void Started()
+ {
+ LastPoll = DateTime.UtcNow;
+ HTTPManager.Heartbeats.Subscribe(this);
+ }
+
+ protected override void Aborted()
+ {
+ HTTPManager.Heartbeats.Unsubscribe(this);
+ }
+
+ #endregion
+
+ #region Request Handlers
+
+ void OnConnectRequestFinished(HTTPRequest req, HTTPResponse resp)
+ {
+ // error reason if there is any. We will call the manager's Error function if it's not empty.
+ string reason = string.Empty;
+
+ switch (req.State)
+ {
+ // The request finished without any problem.
+ case HTTPRequestStates.Finished:
+ if (resp.IsSuccess)
+ {
+ HTTPManager.Logger.Information("Transport - " + this.Name, "Connect - Request Finished Successfully! " + resp.DataAsText);
+
+ OnConnected();
+
+ IServerMessage msg = TransportBase.Parse(Connection.JsonEncoder, resp.DataAsText);
+
+ if (msg != null)
+ {
+ Connection.OnMessage(msg);
+
+ MultiMessage multiple = msg as MultiMessage;
+ if (multiple != null && multiple.PollDelay.HasValue)
+ PollDelay = multiple.PollDelay.Value;
+ }
+ }
+ else
+ reason = string.Format("Connect - Request Finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
+ resp.StatusCode,
+ resp.Message,
+ resp.DataAsText);
+ break;
+
+ // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
+ case HTTPRequestStates.Error:
+ reason = "Connect - Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception");
+ break;
+
+ // The request aborted, initiated by the user.
+ case HTTPRequestStates.Aborted:
+ reason = "Connect - Request Aborted!";
+ break;
+
+ // Connecting to the server is timed out.
+ case HTTPRequestStates.ConnectionTimedOut:
+ reason = "Connect - Connection Timed Out!";
+ break;
+
+ // The request didn't finished in the given time.
+ case HTTPRequestStates.TimedOut:
+ reason = "Connect - Processing the request Timed Out!";
+ break;
+ }
+
+ if (!string.IsNullOrEmpty(reason))
+ Connection.Error(reason);
+ }
+
+ void OnPollRequestFinished(HTTPRequest req, HTTPResponse resp)
+ {
+ // When Stop() called on the transport.
+ // In Stop() we set the pollRequest to null, but a new poll request can be made after a quick reconnection, and there is a chanse that
+ // in this handler function we can null out the new request. So we return early here.
+ if (req.State == HTTPRequestStates.Aborted)
+ {
+ HTTPManager.Logger.Warning("Transport - " + this.Name, "Poll - Request Aborted!");
+ return;
+ }
+
+ // Set the pollRequest to null, now we can send out a new one
+ pollRequest = null;
+
+ // error reason if there is any. We will call the manager's Error function if it's not empty.
+ string reason = string.Empty;
+
+ switch (req.State)
+ {
+ // The request finished without any problem.
+ case HTTPRequestStates.Finished:
+ if (resp.IsSuccess)
+ {
+ HTTPManager.Logger.Information("Transport - " + this.Name, "Poll - Request Finished Successfully! " + resp.DataAsText);
+
+ IServerMessage msg = TransportBase.Parse(Connection.JsonEncoder, resp.DataAsText);
+
+ if (msg != null)
+ {
+ Connection.OnMessage(msg);
+
+ MultiMessage multiple = msg as MultiMessage;
+ if (multiple != null && multiple.PollDelay.HasValue)
+ PollDelay = multiple.PollDelay.Value;
+
+ LastPoll = DateTime.UtcNow;
+ }
+ }
+ else
+ reason = string.Format("Poll - Request Finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
+ resp.StatusCode,
+ resp.Message,
+ resp.DataAsText);
+ break;
+
+ // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
+ case HTTPRequestStates.Error:
+ reason = "Poll - Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception");
+ break;
+
+ // Connecting to the server is timed out.
+ case HTTPRequestStates.ConnectionTimedOut:
+ reason = "Poll - Connection Timed Out!";
+ break;
+
+ // The request didn't finished in the given time.
+ case HTTPRequestStates.TimedOut:
+ reason = "Poll - Processing the request Timed Out!";
+ break;
+ }
+
+ if (!string.IsNullOrEmpty(reason))
+ Connection.Error(reason);
+ }
+
+ #endregion
+
+ ///
+ /// Polling transport speficic function. Sends a GET request to the /poll path to receive messages.
+ ///
+ private void Poll()
+ {
+ pollRequest = new HTTPRequest(Connection.BuildUri(RequestTypes.Poll, this), HTTPMethods.Get, true, true, OnPollRequestFinished);
+
+ Connection.PrepareRequest(pollRequest, RequestTypes.Poll);
+
+ pollRequest.Timeout = this.PollTimeout;
+
+ pollRequest.Send();
+ }
+
+ #region IHeartbeat Implementation
+
+ void IHeartbeat.OnHeartbeatUpdate(TimeSpan dif)
+ {
+ switch(State)
+ {
+ case TransportStates.Started:
+ if (pollRequest == null && DateTime.UtcNow >= (LastPoll + PollDelay + Connection.NegotiationResult.LongPollDelay))
+ Poll();
+ break;
+ }
+ }
+
+ #endregion
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/PollingTransport.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/PollingTransport.cs.meta
new file mode 100644
index 00000000..ec93c4dc
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/PollingTransport.cs.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: 702a1cd6038bbc347a4b568983058f63
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/PostSendTransportBase.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/PostSendTransportBase.cs
new file mode 100644
index 00000000..7ce7c896
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/PostSendTransportBase.cs
@@ -0,0 +1,103 @@
+#if !BESTHTTP_DISABLE_SIGNALR
+
+using System.Collections.Generic;
+
+using BestHTTP.SignalR.Messages;
+
+namespace BestHTTP.SignalR.Transports
+{
+ ///
+ /// A base class for implementations that must send the data in unique requests. These are currently the LongPolling and ServerSentEvents transports.
+ ///
+ public abstract class PostSendTransportBase : TransportBase
+ {
+ ///
+ /// Sent out send requests. Keeping a reference to them for future use.
+ ///
+ protected List sendRequestQueue = new List();
+
+ public PostSendTransportBase(string name, Connection con)
+ : base(name, con)
+ {
+
+ }
+
+ #region Send Implementation
+
+ protected override void SendImpl(string json)
+ {
+ var request = new HTTPRequest(Connection.BuildUri(RequestTypes.Send, this), HTTPMethods.Post, true, true, OnSendRequestFinished);
+
+ request.FormUsage = Forms.HTTPFormUsage.UrlEncoded;
+ request.AddField("data", json);
+
+ Connection.PrepareRequest(request, RequestTypes.Send);
+
+ // Set a lower priority then the default. This way requests that are sent out alongside with SignalR sent requests can be processed sooner.
+ request.Priority = -1;
+
+ request.Send();
+
+ sendRequestQueue.Add(request);
+ }
+
+ void OnSendRequestFinished(HTTPRequest req, HTTPResponse resp)
+ {
+ sendRequestQueue.Remove(req);
+
+ // error reason if there is any. We will call the manager's Error function if it's not empty.
+ string reason = string.Empty;
+
+ switch (req.State)
+ {
+ // The request finished without any problem.
+ case HTTPRequestStates.Finished:
+ if (resp.IsSuccess)
+ {
+ HTTPManager.Logger.Information("Transport - " + this.Name, "Send - Request Finished Successfully! " + resp.DataAsText);
+
+ if (!string.IsNullOrEmpty(resp.DataAsText))
+ {
+ IServerMessage msg = TransportBase.Parse(Connection.JsonEncoder, resp.DataAsText);
+
+ if (msg != null)
+ Connection.OnMessage(msg);
+ }
+ }
+ else
+ reason = string.Format("Send - Request Finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
+ resp.StatusCode,
+ resp.Message,
+ resp.DataAsText);
+ break;
+
+ // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
+ case HTTPRequestStates.Error:
+ reason = "Send - Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception");
+ break;
+
+ // The request aborted, initiated by the user.
+ case HTTPRequestStates.Aborted:
+ reason = "Send - Request Aborted!";
+ break;
+
+ // Connecting to the server is timed out.
+ case HTTPRequestStates.ConnectionTimedOut:
+ reason = "Send - Connection Timed Out!";
+ break;
+
+ // The request didn't finished in the given time.
+ case HTTPRequestStates.TimedOut:
+ reason = "Send - Processing the request Timed Out!";
+ break;
+ }
+
+ if (!string.IsNullOrEmpty(reason))
+ Connection.Error(reason);
+ }
+
+ #endregion
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/PostSendTransportBase.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/PostSendTransportBase.cs.meta
new file mode 100644
index 00000000..0d145323
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/PostSendTransportBase.cs.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: f47176f2538ccf54e855235ecb7647f3
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/ServerSentEventsTransport.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/ServerSentEventsTransport.cs
new file mode 100644
index 00000000..5a36384e
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/ServerSentEventsTransport.cs
@@ -0,0 +1,171 @@
+#if !BESTHTTP_DISABLE_SIGNALR
+#if !BESTHTTP_DISABLE_SERVERSENT_EVENTS
+
+using System;
+
+using BestHTTP.ServerSentEvents;
+using BestHTTP.SignalR.Messages;
+
+namespace BestHTTP.SignalR.Transports
+{
+ ///
+ /// A SignalR transport implementation that uses the Server-Sent Events protocol.
+ ///
+ public sealed class ServerSentEventsTransport : PostSendTransportBase
+ {
+ #region Overridden Properties
+
+ ///
+ /// It's a persistent connection. We support the keep-alive mechanism.
+ ///
+ public override bool SupportsKeepAlive { get { return true; } }
+
+ ///
+ /// Type of the transport.
+ ///
+ public override TransportTypes Type { get { return TransportTypes.ServerSentEvents; } }
+
+ #endregion
+
+ #region Privates
+
+ ///
+ /// The EventSource object.
+ ///
+ private EventSource EventSource;
+
+ #endregion
+
+ public ServerSentEventsTransport(Connection con)
+ : base("serverSentEvents", con)
+ {
+
+ }
+
+ #region Overrides from TransportBase
+
+ public override void Connect()
+ {
+ if (EventSource != null)
+ {
+ HTTPManager.Logger.Warning("ServerSentEventsTransport", "Start - EventSource already created!");
+ return;
+ }
+
+ // Skip the Connecting state if we are reconnecting. If the connect succeeds, we will set the Started state directly
+ if (this.State != TransportStates.Reconnecting)
+ this.State = TransportStates.Connecting;
+
+ RequestTypes requestType = this.State == TransportStates.Reconnecting ? RequestTypes.Reconnect : RequestTypes.Connect;
+
+ Uri uri = Connection.BuildUri(requestType, this);
+
+ EventSource = new EventSource(uri);
+
+ EventSource.OnOpen += OnEventSourceOpen;
+ EventSource.OnMessage += OnEventSourceMessage;
+ EventSource.OnError += OnEventSourceError;
+ EventSource.OnClosed += OnEventSourceClosed;
+
+#if !UNITY_WEBGL || UNITY_EDITOR
+ // Disable internal retry
+ EventSource.OnRetry += (es) => false;
+#endif
+
+ // Start connecting to the server.
+ EventSource.Open();
+ }
+
+ public override void Stop()
+ {
+ EventSource.OnOpen -= OnEventSourceOpen;
+ EventSource.OnMessage -= OnEventSourceMessage;
+ EventSource.OnError -= OnEventSourceError;
+ EventSource.OnClosed -= OnEventSourceClosed;
+
+ EventSource.Close();
+
+ EventSource = null;
+ }
+
+ protected override void Started()
+ {
+ // Nothing to do here for this transport
+ }
+
+ ///
+ /// A custom Abort function where we will start to close the EventSource object.
+ ///
+ public override void Abort()
+ {
+ base.Abort();
+
+ EventSource.Close();
+ }
+
+ protected override void Aborted()
+ {
+ if (this.State == TransportStates.Closing)
+ this.State = TransportStates.Closed;
+ }
+
+ #endregion
+
+ #region EventSource Event Handlers
+
+ private void OnEventSourceOpen(EventSource eventSource)
+ {
+ HTTPManager.Logger.Information("Transport - " + this.Name, "OnEventSourceOpen");
+ }
+
+ private void OnEventSourceMessage(EventSource eventSource, BestHTTP.ServerSentEvents.Message message)
+ {
+ if (message.Data.Equals("initialized"))
+ {
+ base.OnConnected();
+
+ return;
+ }
+
+ IServerMessage msg = TransportBase.Parse(Connection.JsonEncoder, message.Data);
+
+ if (msg != null)
+ Connection.OnMessage(msg);
+
+ }
+
+ private void OnEventSourceError(EventSource eventSource, string error)
+ {
+ HTTPManager.Logger.Information("Transport - " + this.Name, "OnEventSourceError");
+
+ // We are in a reconnecting phase, we have to connect now.
+ if (this.State == TransportStates.Reconnecting)
+ {
+ Connect();
+ return;
+ }
+
+ // Already closed?
+ if (this.State == TransportStates.Closed)
+ return;
+
+ // Closing? Then we are closed now.
+ if (this.State == TransportStates.Closing)
+ this.State = TransportStates.Closed;
+ else // Errored when we didn't expected it.
+ Connection.Error(error);
+ }
+
+ private void OnEventSourceClosed(ServerSentEvents.EventSource eventSource)
+ {
+ HTTPManager.Logger.Information("Transport - " + this.Name, "OnEventSourceClosed");
+
+ OnEventSourceError(eventSource, "EventSource Closed!");
+ }
+
+ #endregion
+ }
+}
+
+#endif
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/ServerSentEventsTransport.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/ServerSentEventsTransport.cs.meta
new file mode 100644
index 00000000..218dab36
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/ServerSentEventsTransport.cs.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: b8c1fc0aacfa94c4793a2e8958a34058
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/TransportBase.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/TransportBase.cs
new file mode 100644
index 00000000..e2e92b16
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/TransportBase.cs
@@ -0,0 +1,386 @@
+#if !BESTHTTP_DISABLE_SIGNALR
+
+using System;
+using System.Collections.Generic;
+
+using BestHTTP.SignalR.Messages;
+using BestHTTP.SignalR.JsonEncoders;
+
+namespace BestHTTP.SignalR.Transports
+{
+ public delegate void OnTransportStateChangedDelegate(TransportBase transport, TransportStates oldState, TransportStates newState);
+
+ public abstract class TransportBase
+ {
+ private const int MaxRetryCount = 5;
+
+ #region Public Properties
+
+ ///
+ /// Name of the transport.
+ ///
+ public string Name { get; protected set; }
+
+ ///
+ /// True if the manager has to check the last message received time and reconnect if too much time passes.
+ ///
+ public abstract bool SupportsKeepAlive { get; }
+
+ ///
+ /// Type of the transport. Used mainly by the manager in its BuildUri function.
+ ///
+ public abstract TransportTypes Type { get; }
+
+ ///
+ /// Reference to the manager.
+ ///
+ public IConnection Connection { get; protected set; }
+
+ ///
+ /// The current state of the transport.
+ ///
+ public TransportStates State
+ {
+ get { return _state; }
+ protected set
+ {
+ TransportStates old = _state;
+ _state = value;
+
+ if (OnStateChanged != null)
+ OnStateChanged(this, old, _state);
+ }
+ }
+ public TransportStates _state;
+
+ ///
+ /// Thi event called when the transport's State set to a new value.
+ ///
+ public event OnTransportStateChangedDelegate OnStateChanged;
+
+ #endregion
+
+ public TransportBase(string name, Connection connection)
+ {
+ this.Name = name;
+ this.Connection = connection;
+ this.State = TransportStates.Initial;
+ }
+
+ #region Abstract functions
+
+ ///
+ /// Start to connect to the server
+ ///
+ public abstract void Connect();
+
+ ///
+ /// Stop the connection
+ ///
+ public abstract void Stop();
+
+ ///
+ /// The transport specific implementation to send the given json string to the server.
+ ///
+ protected abstract void SendImpl(string json);
+
+ ///
+ /// Called when the Start request finished successfully, or after a reconnect.
+ /// Manager.TransportOpened(); called from the TransportBase after this call
+ ///
+ protected abstract void Started();
+
+ ///
+ /// Called when the abort request finished successfully.
+ ///
+ protected abstract void Aborted();
+
+ #endregion
+
+ ///
+ /// Called after a succesful connect/reconnect. The transport implementations have to call this function.
+ ///
+ protected void OnConnected()
+ {
+ if (this.State != TransportStates.Reconnecting)
+ {
+ // Send the Start request
+ Start();
+ }
+ else
+ {
+ Connection.TransportReconnected();
+
+ Started();
+
+ this.State = TransportStates.Started;
+ }
+ }
+
+ #region Start Request Sending
+
+ ///
+ /// Sends out the /start request to the server.
+ ///
+ protected void Start()
+ {
+ HTTPManager.Logger.Information("Transport - " + this.Name, "Sending Start Request");
+
+ this.State = TransportStates.Starting;
+
+ if (this.Connection.Protocol > ProtocolVersions.Protocol_2_0)
+ {
+ var request = new HTTPRequest(Connection.BuildUri(RequestTypes.Start, this), HTTPMethods.Get, true, true, OnStartRequestFinished);
+
+ request.Tag = 0;
+ request.DisableRetry = true;
+
+ request.Timeout = Connection.NegotiationResult.ConnectionTimeout + TimeSpan.FromSeconds(10);
+
+ Connection.PrepareRequest(request, RequestTypes.Start);
+
+ request.Send();
+ }
+ else
+ {
+ // The transport and the signalr protocol now started
+ this.State = TransportStates.Started;
+
+ Started();
+
+ Connection.TransportStarted();
+ }
+ }
+
+ private void OnStartRequestFinished(HTTPRequest req, HTTPResponse resp)
+ {
+ switch (req.State)
+ {
+ case HTTPRequestStates.Finished:
+ if (resp.IsSuccess)
+ {
+ HTTPManager.Logger.Information("Transport - " + this.Name, "Start - Returned: " + resp.DataAsText);
+
+ string response = Connection.ParseResponse(resp.DataAsText);
+
+ if (response != "started")
+ {
+ Connection.Error(string.Format("Expected 'started' response, but '{0}' found!", response));
+ return;
+ }
+
+ // The transport and the signalr protocol now started
+ this.State = TransportStates.Started;
+
+ Started();
+
+ Connection.TransportStarted();
+
+ return;
+ }
+ else
+ HTTPManager.Logger.Warning("Transport - " + this.Name, string.Format("Start - request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2} Uri: {3}",
+ resp.StatusCode,
+ resp.Message,
+ resp.DataAsText,
+ req.CurrentUri));
+ goto default;
+
+ default:
+ HTTPManager.Logger.Information("Transport - " + this.Name, "Start request state: " + req.State.ToString());
+
+ // The request may not reached the server. Try it again.
+ int retryCount = (int)req.Tag;
+ if (retryCount++ < MaxRetryCount)
+ {
+ req.Tag = retryCount;
+ req.Send();
+ }
+ else
+ Connection.Error("Failed to send Start request.");
+
+ break;
+ }
+ }
+
+ #endregion
+
+ #region Abort Implementation
+
+ ///
+ /// Will abort the transport. In SignalR 'Abort'ing is a graceful process, while 'Close'ing is a hard-abortion...
+ ///
+ public virtual void Abort()
+ {
+ if (this.State != TransportStates.Started)
+ return;
+
+ this.State = TransportStates.Closing;
+
+ var request = new HTTPRequest(Connection.BuildUri(RequestTypes.Abort, this), HTTPMethods.Get, true, true, OnAbortRequestFinished);
+
+ // Retry counter
+ request.Tag = 0;
+ request.DisableRetry = true;
+
+ Connection.PrepareRequest(request, RequestTypes.Abort);
+
+ request.Send();
+ }
+
+ protected void AbortFinished()
+ {
+ this.State = TransportStates.Closed;
+
+ Connection.TransportAborted();
+
+ this.Aborted();
+ }
+
+ private void OnAbortRequestFinished(HTTPRequest req, HTTPResponse resp)
+ {
+ switch (req.State)
+ {
+ case HTTPRequestStates.Finished:
+ if (resp.IsSuccess)
+ {
+ HTTPManager.Logger.Information("Transport - " + this.Name, "Abort - Returned: " + resp.DataAsText);
+
+ if (this.State == TransportStates.Closing)
+ AbortFinished();
+ }
+ else
+ {
+ HTTPManager.Logger.Warning("Transport - " + this.Name, string.Format("Abort - Handshake request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2} Uri: {3}",
+ resp.StatusCode,
+ resp.Message,
+ resp.DataAsText,
+ req.CurrentUri));
+
+ // try again
+ goto default;
+ }
+ break;
+ default:
+ HTTPManager.Logger.Information("Transport - " + this.Name, "Abort request state: " + req.State.ToString());
+
+ // The request may not reached the server. Try it again.
+ int retryCount = (int)req.Tag;
+ if (retryCount++ < MaxRetryCount)
+ {
+ req.Tag = retryCount;
+ req.Send();
+ }
+ else
+ Connection.Error("Failed to send Abort request!");
+
+ break;
+ }
+ }
+
+ #endregion
+
+ #region Send Implementation
+
+ ///
+ /// Sends the given json string to the wire.
+ ///
+ ///
+ public void Send(string jsonStr)
+ {
+ try
+ {
+ HTTPManager.Logger.Information("Transport - " + this.Name, "Sending: " + jsonStr);
+
+ SendImpl(jsonStr);
+ }
+ catch (Exception ex)
+ {
+ HTTPManager.Logger.Exception("Transport - " + this.Name, "Send", ex);
+ }
+ }
+
+ #endregion
+
+ #region Helper Functions
+
+ ///
+ /// Start the reconnect process
+ ///
+ public void Reconnect()
+ {
+ HTTPManager.Logger.Information("Transport - " + this.Name, "Reconnecting");
+
+ Stop();
+
+ this.State = TransportStates.Reconnecting;
+
+ Connect();
+ }
+
+ ///
+ /// When the json string is successfully parsed will return with an IServerMessage implementation.
+ ///
+ public static IServerMessage Parse(IJsonEncoder encoder, string json)
+ {
+ // Nothing to parse?
+ if (string.IsNullOrEmpty(json))
+ {
+ HTTPManager.Logger.Error("MessageFactory", "Parse - called with empty or null string!");
+ return null;
+ }
+
+ // We don't have to do further decoding, if it's an empty json object, then it's a KeepAlive message from the server
+ if (json.Length == 2 && json == "{}")
+ return new KeepAliveMessage();
+
+ IDictionary msg = null;
+
+ try
+ {
+ // try to decode the json message with the encoder
+ msg = encoder.DecodeMessage(json);
+ }
+ catch(Exception ex)
+ {
+ HTTPManager.Logger.Exception("MessageFactory", "Parse - encoder.DecodeMessage", ex);
+ return null;
+ }
+
+ if (msg == null)
+ {
+ HTTPManager.Logger.Error("MessageFactory", "Parse - Json Decode failed for json string: \"" + json + "\"");
+ return null;
+ }
+
+ // "C" is for message id
+ IServerMessage result = null;
+ if (!msg.ContainsKey("C"))
+ {
+ // If there are no ErrorMessage in the object, then it was a success
+ if (!msg.ContainsKey("E"))
+ result = new ResultMessage();
+ else
+ result = new FailureMessage();
+ }
+ else
+ result = new MultiMessage();
+
+ try
+ {
+ result.Parse(msg);
+ }
+ catch
+ {
+ HTTPManager.Logger.Error("MessageFactory", "Can't parse msg: " + json);
+ throw;
+ }
+
+ return result;
+ }
+
+ #endregion
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/TransportBase.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/TransportBase.cs.meta
new file mode 100644
index 00000000..88831c2b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/TransportBase.cs.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: 469a77c43ea68f14da659401301834f5
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/WebSocketTransport.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/WebSocketTransport.cs
new file mode 100644
index 00000000..cbdee970
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/WebSocketTransport.cs
@@ -0,0 +1,173 @@
+#if !BESTHTTP_DISABLE_SIGNALR
+#if !BESTHTTP_DISABLE_WEBSOCKET
+
+using System;
+using System.Text;
+
+using BestHTTP;
+using BestHTTP.JSON;
+using BestHTTP.SignalR.Hubs;
+using BestHTTP.SignalR.Messages;
+using BestHTTP.SignalR.JsonEncoders;
+
+namespace BestHTTP.SignalR.Transports
+{
+ public sealed class WebSocketTransport : TransportBase
+ {
+ #region Overridden Properties
+
+ public override bool SupportsKeepAlive { get { return true; } }
+ public override TransportTypes Type { get { return TransportTypes.WebSocket; } }
+
+ #endregion
+
+ private WebSocket.WebSocket wSocket;
+
+ public WebSocketTransport(Connection connection)
+ : base("webSockets", connection)
+ {
+ }
+
+ #region Overrides from TransportBase
+
+ ///
+ /// Websocket transport specific connection logic. It will create a WebSocket instance, and starts to connect to the server.
+ ///
+ public override void Connect()
+ {
+ if (wSocket != null)
+ {
+ HTTPManager.Logger.Warning("WebSocketTransport", "Start - WebSocket already created!");
+ return;
+ }
+
+ // Skip the Connecting state if we are reconnecting. If the connect succeeds, we will set the Started state directly
+ if (this.State != TransportStates.Reconnecting)
+ this.State = TransportStates.Connecting;
+
+ RequestTypes requestType = this.State == TransportStates.Reconnecting ? RequestTypes.Reconnect : RequestTypes.Connect;
+
+ Uri uri = Connection.BuildUri(requestType, this);
+
+ // Create the WebSocket instance
+ wSocket = new WebSocket.WebSocket(uri);
+
+ // Set up eventhandlers
+ wSocket.OnOpen += WSocket_OnOpen;
+ wSocket.OnMessage += WSocket_OnMessage;
+ wSocket.OnClosed += WSocket_OnClosed;
+ wSocket.OnErrorDesc += WSocket_OnError;
+
+#if !UNITY_WEBGL || UNITY_EDITOR
+ // prepare the internal http request
+ Connection.PrepareRequest(wSocket.InternalRequest, requestType);
+#endif
+
+ // start opening the websocket protocol
+ wSocket.Open();
+ }
+
+ protected override void SendImpl(string json)
+ {
+ if (wSocket != null && wSocket.IsOpen)
+ wSocket.Send(json);
+ }
+
+ public override void Stop()
+ {
+ if (wSocket != null)
+ {
+ wSocket.OnOpen = null;
+ wSocket.OnMessage = null;
+ wSocket.OnClosed = null;
+ wSocket.OnErrorDesc = null;
+ wSocket.Close();
+ wSocket = null;
+ }
+ }
+
+ protected override void Started()
+ {
+ // Nothing to be done here for this transport
+ }
+
+ ///
+ /// The /abort request successfully finished
+ ///
+ protected override void Aborted()
+ {
+ // if the websocket is still open, close it
+ if (wSocket != null && wSocket.IsOpen)
+ {
+ wSocket.Close();
+ wSocket = null;
+ }
+ }
+
+#endregion
+
+#region WebSocket Events
+
+ void WSocket_OnOpen(WebSocket.WebSocket webSocket)
+ {
+ if (webSocket != wSocket)
+ return;
+
+ HTTPManager.Logger.Information("WebSocketTransport", "WSocket_OnOpen");
+
+ OnConnected();
+ }
+
+ void WSocket_OnMessage(WebSocket.WebSocket webSocket, string message)
+ {
+ if (webSocket != wSocket)
+ return;
+
+ IServerMessage msg = TransportBase.Parse(Connection.JsonEncoder, message);
+
+ if (msg != null)
+ Connection.OnMessage(msg);
+ }
+
+ void WSocket_OnClosed(WebSocket.WebSocket webSocket, ushort code, string message)
+ {
+ if (webSocket != wSocket)
+ return;
+
+ string reason = code.ToString() + " : " + message;
+
+ HTTPManager.Logger.Information("WebSocketTransport", "WSocket_OnClosed " + reason);
+
+ if (this.State == TransportStates.Closing)
+ this.State = TransportStates.Closed;
+ else
+ Connection.Error(reason);
+ }
+
+ void WSocket_OnError(WebSocket.WebSocket webSocket, string reason)
+ {
+ if (webSocket != wSocket)
+ return;
+
+ // On WP8.1, somehow we receive an exception that the remote server forcibly closed the connection instead of the
+ // WebSocket closed packet... Also, even the /abort request didn't finished.
+ if (this.State == TransportStates.Closing ||
+ this.State == TransportStates.Closed)
+ {
+ base.AbortFinished();
+ }
+ else
+ {
+ HTTPManager.Logger.Error("WebSocketTransport", "WSocket_OnError " + reason);
+
+ this.State = TransportStates.Closed;
+ Connection.Error(reason);
+ }
+ }
+
+#endregion
+ }
+}
+
+#endif
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/WebSocketTransport.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/WebSocketTransport.cs.meta
new file mode 100644
index 00000000..e969abb9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalR/Transports/WebSocketTransport.cs.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: 5efa5f8b9a034084b87f47b2b74b8173
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore.meta
new file mode 100644
index 00000000..81f6b4f1
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: fe53b9220e298d844bd0d53106307094
+folderAsset: yes
+timeCreated: 1515237542
+licenseType: Store
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Authentication.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Authentication.meta
new file mode 100644
index 00000000..347a9ccb
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Authentication.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: a3fe10bda4c195348b779c549e20e0d4
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Authentication/DefaultAccessTokenAuthenticator.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Authentication/DefaultAccessTokenAuthenticator.cs
new file mode 100644
index 00000000..ab5f1b76
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Authentication/DefaultAccessTokenAuthenticator.cs
@@ -0,0 +1,59 @@
+using System;
+
+namespace BestHTTP.SignalRCore.Authentication
+{
+ public sealed class DefaultAccessTokenAuthenticator : IAuthenticationProvider
+ {
+ ///
+ /// No pre-auth step required for this type of authentication
+ ///
+ public bool IsPreAuthRequired { get { return false; } }
+
+#pragma warning disable 0067
+ ///
+ /// Not used event as IsPreAuthRequired is false
+ ///
+ public event OnAuthenticationSuccededDelegate OnAuthenticationSucceded;
+
+ ///
+ /// Not used event as IsPreAuthRequired is false
+ ///
+ public event OnAuthenticationFailedDelegate OnAuthenticationFailed;
+
+#pragma warning restore 0067
+
+ private HubConnection _connection;
+
+ public DefaultAccessTokenAuthenticator(HubConnection connection)
+ {
+ this._connection = connection;
+ }
+
+ ///
+ /// Not used as IsPreAuthRequired is false
+ ///
+ public void StartAuthentication()
+ { }
+
+ ///
+ /// Prepares the request by adding two headers to it
+ ///
+ public void PrepareRequest(BestHTTP.HTTPRequest request)
+ {
+ if (HTTPProtocolFactory.GetProtocolFromUri(request.CurrentUri) == SupportedProtocols.HTTP)
+ request.Uri = PrepareUri(request.Uri);
+ }
+
+ public Uri PrepareUri(Uri uri)
+ {
+ if (this._connection.NegotiationResult != null && !string.IsNullOrEmpty(this._connection.NegotiationResult.AccessToken))
+ {
+ string query = string.IsNullOrEmpty(uri.Query) ? "?" : uri.Query + "&";
+ UriBuilder uriBuilder = new UriBuilder(uri.Scheme, uri.Host, uri.Port, uri.AbsolutePath, query + "access_token=" + this._connection.NegotiationResult.AccessToken);
+ return uriBuilder.Uri;
+ }
+ else
+ return uri;
+ }
+ }
+}
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Authentication/DefaultAccessTokenAuthenticator.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Authentication/DefaultAccessTokenAuthenticator.cs.meta
new file mode 100644
index 00000000..c404a37c
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Authentication/DefaultAccessTokenAuthenticator.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: cd70ac39ecb098a49b5a09eef4e516f7
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/HelperClasses.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/HelperClasses.cs
new file mode 100644
index 00000000..364fdadc
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/HelperClasses.cs
@@ -0,0 +1,148 @@
+#if !BESTHTTP_DISABLE_SIGNALR_CORE && !BESTHTTP_DISABLE_WEBSOCKET
+using System;
+using System.Collections.Generic;
+
+namespace BestHTTP.SignalRCore
+{
+ public enum TransportTypes
+ {
+ WebSocket
+ }
+
+ public enum TransferModes
+ {
+ Binary,
+ Text
+ }
+
+ public enum TransportStates
+ {
+ Initial,
+ Connecting,
+ Connected,
+ Closing,
+ Failed,
+ Closed
+ }
+
+ ///
+ /// Possible states of a HubConnection
+ ///
+ public enum ConnectionStates
+ {
+ Initial,
+ Authenticating,
+ Negotiating,
+ Redirected,
+ Connected,
+ CloseInitiated,
+ Closed
+ }
+
+ public interface ITransport
+ {
+ TransferModes TransferMode { get; }
+ TransportTypes TransportType { get; }
+ TransportStates State { get; }
+
+ string ErrorReason { get; }
+
+ event Action OnStateChanged;
+
+ void StartConnect();
+ void StartClose();
+
+ void Send(byte[] msg);
+ }
+
+ public interface IEncoder
+ {
+ string Name { get; }
+
+ string EncodeAsText(T value);
+ T DecodeAs(string text);
+
+ byte[] EncodeAsBinary(T value);
+ T DecodeAs(byte[] data);
+
+ object ConvertTo(Type toType, object obj);
+ }
+
+ public class StreamItemContainer
+ {
+ public readonly long id;
+
+ public List Items { get; private set; }
+ public T LastAdded { get; private set; }
+
+ //public int newIdx;
+ //public int newCount;
+
+ public bool IsCanceled;
+
+ public StreamItemContainer(long _id)
+ {
+ this.id = _id;
+ this.Items = new List();
+ }
+
+ public void AddItem(T item)
+ {
+ if (this.Items == null)
+ this.Items = new List();
+
+ //this.newIdx = this.Items.Count;
+ //this.newCount = 1;
+ this.Items.Add(item);
+ this.LastAdded = item;
+ }
+
+ //public void AddItems(T[] items)
+ //{
+ // if (this.Items == null)
+ // this.Items = new List();
+ //
+ // this.newIdx = this.Items.Count;
+ // this.newCount = items.Length;
+ //
+ // this.Items.AddRange(items);
+ //}
+ }
+
+ struct CallbackDescriptor
+ {
+ public readonly Type[] ParamTypes;
+ public readonly Action Callback;
+ public CallbackDescriptor(Type[] paramTypes, Action callback)
+ {
+ this.ParamTypes = paramTypes;
+ this.Callback = callback;
+ }
+ }
+
+ internal sealed class Subscription
+ {
+ public List callbacks = new List(1);
+
+ public void Add(Type[] paramTypes, Action callback)
+ {
+ lock(callbacks)
+ this.callbacks.Add(new CallbackDescriptor(paramTypes, callback));
+ }
+
+ public void Remove(Action callback)
+ {
+ lock (callbacks)
+ {
+ int idx = -1;
+ for (int i = 0; i < this.callbacks.Count && idx == -1; ++i)
+ if (this.callbacks[i].Callback == callback)
+ idx = i;
+
+ if (idx != -1)
+ this.callbacks.RemoveAt(idx);
+ }
+ }
+ }
+}
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/HelperClasses.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/HelperClasses.cs.meta
new file mode 100644
index 00000000..5180aee9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/HelperClasses.cs.meta
@@ -0,0 +1,13 @@
+fileFormatVersion: 2
+guid: 6742bc413b5a23041b937fb3ee3b12d8
+timeCreated: 1515237548
+licenseType: Store
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/HubConnection.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/HubConnection.cs
new file mode 100644
index 00000000..8f662c01
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/HubConnection.cs
@@ -0,0 +1,741 @@
+#if !BESTHTTP_DISABLE_SIGNALR_CORE && !BESTHTTP_DISABLE_WEBSOCKET
+using BestHTTP.Futures;
+using BestHTTP.SignalRCore.Authentication;
+using BestHTTP.SignalRCore.Messages;
+using System;
+using System.Collections.Generic;
+
+namespace BestHTTP.SignalRCore
+{
+ public sealed class HubOptions
+ {
+ ///
+ /// When this is set to true, the plugin will skip the negotiation request if the PreferedTransport is WebSocket. Its default value is false.
+ ///
+ public bool SkipNegotiation { get; set; }
+
+ ///
+ /// The preferred transport to choose when more than one available. Its default value is TransportTypes.WebSocket.
+ ///
+ public TransportTypes PreferedTransport { get; set; }
+
+ ///
+ /// A ping message is only sent if the interval has elapsed without a message being sent. Its default value is 15 seconds.
+ ///
+ public TimeSpan PingInterval { get; set; }
+
+ ///
+ /// The maximum count of redirect negoitiation result that the plugin will follow. Its default value is 100.
+ ///
+ public int MaxRedirects { get; set; }
+
+ public HubOptions()
+ {
+ this.SkipNegotiation = false;
+ this.PreferedTransport = TransportTypes.WebSocket;
+ this.PingInterval = TimeSpan.FromSeconds(15);
+ this.MaxRedirects = 100;
+ }
+ }
+
+ public sealed class HubConnection : BestHTTP.Extensions.IHeartbeat
+ {
+ public static readonly object[] EmptyArgs = new object[0];
+
+ ///
+ /// Uri of the Hub endpoint
+ ///
+ public Uri Uri { get; private set; }
+
+ ///
+ /// Current state of this connection.
+ ///
+ public ConnectionStates State { get; private set; }
+
+ ///
+ /// Current, active ITransport instance.
+ ///
+ public ITransport Transport { get; private set; }
+
+ ///
+ /// The IProtocol implementation that will parse, encode and decode messages.
+ ///
+ public IProtocol Protocol { get; private set; }
+
+ ///
+ /// This event is called when the connection is redirected to a new uri.
+ ///
+ public event Action OnRedirected;
+
+ ///
+ /// This event is called when successfully connected to the hub.
+ ///
+ public event Action OnConnected;
+
+ ///
+ /// This event is called when an unexpected error happen and the connection is closed.
+ ///
+ public event Action OnError;
+
+ ///
+ /// This event is called when the connection is gracefully terminated.
+ ///
+ public event Action OnClosed;
+
+ ///
+ /// This event is called for every server-sent message. When returns false, no further processing of the message is done
+ /// by the plugin.
+ ///
+ public event Func OnMessage;
+
+ ///
+ /// An IAuthenticationProvider implementation that will be used to authenticate the connection.
+ ///
+ public IAuthenticationProvider AuthenticationProvider { get; set; }
+
+ ///
+ /// Negotiation response sent by the server.
+ ///
+ public NegotiationResult NegotiationResult { get; private set; }
+
+ ///
+ ///
+ ///
+ public HubOptions Options { get; private set; }
+
+ ///
+ /// How many times this connection is redirected.
+ ///
+ public int RedirectCount { get; private set; }
+
+ ///
+ /// This will be increment to add a unique id to every message the plugin will send.
+ ///
+ private long lastInvocationId = 0;
+
+ ///
+ /// Store the callback for all sent message that expect a return value from the server. All sent message has
+ /// a unique invocationId that will be sent back from the server.
+ ///
+ private Dictionary> invocations = new Dictionary>();
+
+ ///
+ /// This is where we store the methodname => callback mapping.
+ ///
+ private Dictionary subscriptions = new Dictionary(StringComparer.OrdinalIgnoreCase);
+
+ ///
+ /// When we sent out the last message to the server.
+ ///
+ private DateTime lastMessageSent;
+
+ public HubConnection(Uri hubUri, IProtocol protocol)
+ : this(hubUri, protocol, new HubOptions())
+ {
+ }
+
+ public HubConnection(Uri hubUri, IProtocol protocol, HubOptions options)
+ {
+ this.Uri = hubUri;
+ this.State = ConnectionStates.Initial;
+ this.Options = options;
+ this.Protocol = protocol;
+ this.Protocol.Connection = this;
+ this.AuthenticationProvider = new DefaultAccessTokenAuthenticator(this);
+ }
+
+ public void StartConnect()
+ {
+ if (this.State != ConnectionStates.Initial && this.State != ConnectionStates.Redirected)
+ {
+ HTTPManager.Logger.Warning("HubConnection", "StartConnect - Expected Initial or Redirected state, got " + this.State.ToString());
+ return;
+ }
+
+ HTTPManager.Logger.Verbose("HubConnection", "StartConnect");
+
+ if (this.AuthenticationProvider != null && this.AuthenticationProvider.IsPreAuthRequired)
+ {
+ HTTPManager.Logger.Information("HubConnection", "StartConnect - Authenticating");
+ SetState(ConnectionStates.Authenticating);
+
+ this.AuthenticationProvider.OnAuthenticationSucceded += OnAuthenticationSucceded;
+ this.AuthenticationProvider.OnAuthenticationFailed += OnAuthenticationFailed;
+
+ // Start the authentication process
+ this.AuthenticationProvider.StartAuthentication();
+ }
+ else
+ StartNegotiation();
+ }
+
+ private void OnAuthenticationSucceded(IAuthenticationProvider provider)
+ {
+ HTTPManager.Logger.Verbose("HubConnection", "OnAuthenticationSucceded");
+
+ this.AuthenticationProvider.OnAuthenticationSucceded -= OnAuthenticationSucceded;
+ this.AuthenticationProvider.OnAuthenticationFailed -= OnAuthenticationFailed;
+
+ StartNegotiation();
+ }
+
+ private void OnAuthenticationFailed(IAuthenticationProvider provider, string reason)
+ {
+ HTTPManager.Logger.Error("HubConnection", "OnAuthenticationFailed: " + reason);
+
+ this.AuthenticationProvider.OnAuthenticationSucceded -= OnAuthenticationSucceded;
+ this.AuthenticationProvider.OnAuthenticationFailed -= OnAuthenticationFailed;
+
+ SetState(ConnectionStates.Closed, reason);
+ }
+
+ private void StartNegotiation()
+ {
+ HTTPManager.Logger.Verbose("HubConnection", "StartNegotiation");
+
+ if (this.State == ConnectionStates.CloseInitiated)
+ {
+ SetState(ConnectionStates.Closed);
+ return;
+ }
+
+ if (this.Options.SkipNegotiation)
+ {
+ HTTPManager.Logger.Verbose("HubConnection", "Skipping negotiation");
+ ConnectImpl();
+
+ return;
+ }
+
+ SetState(ConnectionStates.Negotiating);
+
+ // https://github.com/aspnet/SignalR/blob/dev/specs/TransportProtocols.md#post-endpoint-basenegotiate-request
+ // Send out a negotiation request. While we could skip it and connect right with the websocket transport
+ // it might return with additional information that could be useful.
+
+ UriBuilder builder = new UriBuilder(this.Uri);
+ builder.Path += "/negotiate";
+
+ var request = new HTTPRequest(builder.Uri, HTTPMethods.Post, OnNegotiationRequestFinished);
+ if (this.AuthenticationProvider != null)
+ this.AuthenticationProvider.PrepareRequest(request);
+
+ request.Send();
+ }
+
+ private void ConnectImpl()
+ {
+ HTTPManager.Logger.Verbose("HubConnection", "ConnectImpl");
+
+ switch (this.Options.PreferedTransport)
+ {
+ case TransportTypes.WebSocket:
+ if (this.NegotiationResult != null && !IsTransportSupported("WebSockets"))
+ {
+ SetState(ConnectionStates.Closed, "The 'WebSockets' transport isn't supported by the server!");
+ return;
+ }
+
+ this.Transport = new Transports.WebSocketTransport(this);
+ this.Transport.OnStateChanged += Transport_OnStateChanged;
+ break;
+
+ default:
+ SetState(ConnectionStates.Closed, "Unsupportted transport: " + this.Options.PreferedTransport);
+ break;
+ }
+
+ this.Transport.StartConnect();
+ }
+
+ private bool IsTransportSupported(string transportName)
+ {
+ // https://github.com/aspnet/SignalR/blob/release/2.2/specs/TransportProtocols.md#post-endpoint-basenegotiate-request
+ // If the negotiation response contains only the url and accessToken, no 'availableTransports' list is sent
+ if (this.NegotiationResult.SupportedTransports == null)
+ return true;
+
+ for (int i = 0; i < this.NegotiationResult.SupportedTransports.Count; ++i)
+ if (this.NegotiationResult.SupportedTransports[i].Name == transportName)
+ return true;
+
+ return false;
+ }
+
+ private void OnNegotiationRequestFinished(HTTPRequest req, HTTPResponse resp)
+ {
+ if (this.State == ConnectionStates.CloseInitiated)
+ {
+ SetState(ConnectionStates.Closed);
+ return;
+ }
+
+ string errorReason = null;
+
+ switch (req.State)
+ {
+ // The request finished without any problem.
+ case HTTPRequestStates.Finished:
+ if (resp.IsSuccess)
+ {
+ HTTPManager.Logger.Information("HubConnection", "Negotiation Request Finished Successfully! Response: " + resp.DataAsText);
+
+ // Parse negotiation
+ this.NegotiationResult = NegotiationResult.Parse(resp.DataAsText, out errorReason, this);
+
+ // TODO: check validity of the negotiation result:
+ // If url and accessToken is present, the other two must be null.
+ // https://github.com/aspnet/SignalR/blob/dev/specs/TransportProtocols.md#post-endpoint-basenegotiate-request
+
+ if (string.IsNullOrEmpty(errorReason))
+ {
+ if (this.NegotiationResult.Url != null)
+ {
+ this.SetState(ConnectionStates.Redirected);
+
+ if (++this.RedirectCount >= this.Options.MaxRedirects)
+ errorReason = string.Format("MaxRedirects ({0:N0}) reached!", this.Options.MaxRedirects);
+ else
+ {
+ var oldUri = this.Uri;
+ this.Uri = this.NegotiationResult.Url;
+
+ if (this.OnRedirected != null)
+ {
+ try
+ {
+ this.OnRedirected(this, oldUri, Uri);
+ }
+ catch (Exception ex)
+ {
+ HTTPManager.Logger.Exception("HubConnection", "OnNegotiationRequestFinished - OnRedirected", ex);
+ }
+ }
+
+ StartConnect();
+ }
+ }
+ else
+ ConnectImpl();
+ }
+ }
+ else // Internal server error?
+ errorReason = string.Format("Negotiation Request Finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
+ resp.StatusCode,
+ resp.Message,
+ resp.DataAsText);
+ break;
+
+ // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
+ case HTTPRequestStates.Error:
+ errorReason = "Negotiation Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception");
+ break;
+
+ // The request aborted, initiated by the user.
+ case HTTPRequestStates.Aborted:
+ errorReason = "Negotiation Request Aborted!";
+ break;
+
+ // Connecting to the server is timed out.
+ case HTTPRequestStates.ConnectionTimedOut:
+ errorReason = "Negotiation Request - Connection Timed Out!";
+ break;
+
+ // The request didn't finished in the given time.
+ case HTTPRequestStates.TimedOut:
+ errorReason = "Negotiation Request - Processing the request Timed Out!";
+ break;
+ }
+
+ if (errorReason != null)
+ SetState(ConnectionStates.Closed, errorReason);
+ }
+
+ public void StartClose()
+ {
+ HTTPManager.Logger.Verbose("HubConnection", "StartClose");
+
+ SetState(ConnectionStates.CloseInitiated);
+
+ if (this.Transport != null)
+ this.Transport.StartClose();
+ }
+
+ public IFuture> Stream(string target, params object[] args)
+ {
+ var future = new Future>();
+
+ long id = InvokeImp(target,
+ args,
+ callback: (message) =>
+ {
+ switch (message.type)
+ {
+ // StreamItem message contains only one item.
+ case MessageTypes.StreamItem:
+ {
+ var container = future.value;
+
+ if (container.IsCanceled)
+ break;
+
+ container.AddItem((TResult)this.Protocol.ConvertTo(typeof(TResult), message.item));
+
+ // (re)assign the container to raise OnItem event
+ future.AssignItem(container);
+ break;
+ }
+
+ case MessageTypes.Completion:
+ {
+ bool isSuccess = string.IsNullOrEmpty(message.error);
+ if (isSuccess)
+ {
+ var container = future.value;
+
+ // While completion message must not contain any result, this should be future-proof
+ //if (!container.IsCanceled && message.Result != null)
+ //{
+ // TResult[] results = (TResult[])this.Protocol.ConvertTo(typeof(TResult[]), message.Result);
+ //
+ // container.AddItems(results);
+ //}
+
+ future.Assign(container);
+ }
+ else
+ future.Fail(new Exception(message.error));
+ break;
+ }
+ }
+ },
+ isStreamingInvocation: true);
+
+ future.BeginProcess(new StreamItemContainer(id));
+
+ return future;
+ }
+
+ public void CancelStream(StreamItemContainer container)
+ {
+ Message message = new Message {
+ type = MessageTypes.CancelInvocation,
+ invocationId = container.id.ToString()
+ };
+
+ container.IsCanceled = true;
+
+ SendMessage(message);
+ }
+
+ public IFuture Invoke(string target, params object[] args)
+ {
+ Future future = new Future();
+
+ InvokeImp(target,
+ args,
+ (message) =>
+ {
+ bool isSuccess = string.IsNullOrEmpty(message.error);
+ if (isSuccess)
+ future.Assign((TResult)this.Protocol.ConvertTo(typeof(TResult), message.result));
+ else
+ future.Fail(new Exception(message.error));
+ });
+
+ return future;
+ }
+
+ public IFuture Send(string target, params object[] args)
+ {
+ Future future = new Future();
+
+ InvokeImp(target,
+ args,
+ (message) =>
+ {
+ bool isSuccess = string.IsNullOrEmpty(message.error);
+ if (isSuccess)
+ future.Assign(true);
+ else
+ future.Fail(new Exception(message.error));
+ });
+
+ return future;
+ }
+
+ private long InvokeImp(string target, object[] args, Action callback, bool isStreamingInvocation = false)
+ {
+ if (this.State != ConnectionStates.Connected)
+ return -1;
+
+ long invocationId = System.Threading.Interlocked.Increment(ref this.lastInvocationId);
+ var message = new Message
+ {
+ type = isStreamingInvocation ? MessageTypes.StreamInvocation : MessageTypes.Invocation,
+ invocationId = invocationId.ToString(),
+ target = target,
+ arguments = args,
+ nonblocking = callback == null,
+ };
+
+ SendMessage(message);
+
+ if (callback != null)
+ this.invocations.Add(invocationId, callback);
+
+ return invocationId;
+ }
+
+ private void SendMessage(Message message)
+ {
+ byte[] encoded = this.Protocol.EncodeMessage(message);
+ this.Transport.Send(encoded);
+
+ this.lastMessageSent = DateTime.UtcNow;
+ }
+
+ public void On(string methodName, Action callback)
+ {
+ On(methodName, null, (args) => callback());
+ }
+
+ public void On(string methodName, Action callback)
+ {
+ On(methodName, new Type[] { typeof(T1) }, (args) => callback((T1)args[0]));
+ }
+
+ public void On(string methodName, Action callback)
+ {
+ On(methodName,
+ new Type[] { typeof(T1), typeof(T2) },
+ (args) => callback((T1)args[0], (T2)args[1]));
+ }
+
+ public void On(string methodName, Action callback)
+ {
+ On(methodName,
+ new Type[] { typeof(T1), typeof(T2), typeof(T3) },
+ (args) => callback((T1)args[0], (T2)args[1], (T3)args[2]));
+ }
+
+ public void On(string methodName, Action callback)
+ {
+ On(methodName,
+ new Type[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4) },
+ (args) => callback((T1)args[0], (T2)args[1], (T3)args[2], (T4)args[3]));
+ }
+
+ public void On(string methodName, Type[] paramTypes, Action callback)
+ {
+ Subscription subscription = null;
+ if (!this.subscriptions.TryGetValue(methodName, out subscription))
+ this.subscriptions.Add(methodName, subscription = new Subscription());
+
+ subscription.Add(paramTypes, callback);
+ }
+
+ internal void OnMessages(List messages)
+ {
+ for (int messageIdx = 0; messageIdx < messages.Count; ++messageIdx)
+ {
+ var message = messages[messageIdx];
+
+ try
+ {
+ if (this.OnMessage != null && !this.OnMessage(this, message))
+ return;
+ }
+ catch (Exception ex)
+ {
+ HTTPManager.Logger.Exception("HubConnection", "Exception in OnMessage user code!", ex);
+ }
+
+ switch (message.type)
+ {
+ case MessageTypes.Invocation:
+ {
+ Subscription subscribtion = null;
+ if (this.subscriptions.TryGetValue(message.target, out subscribtion))
+ {
+ for (int i = 0; i < subscribtion.callbacks.Count; ++i)
+ {
+ var callbackDesc = subscribtion.callbacks[i];
+
+ object[] realArgs = null;
+ try
+ {
+ realArgs = this.Protocol.GetRealArguments(callbackDesc.ParamTypes, message.arguments);
+ }
+ catch (Exception ex)
+ {
+ HTTPManager.Logger.Exception("HubConnection", "OnMessages - Invocation - GetRealArguments", ex);
+ }
+
+ try
+ {
+ callbackDesc.Callback.Invoke(realArgs);
+ }
+ catch (Exception ex)
+ {
+ HTTPManager.Logger.Exception("HubConnection", "OnMessages - Invocation - Invoke", ex);
+ }
+ }
+ }
+
+ break;
+ }
+
+ case MessageTypes.StreamItem:
+ {
+ long invocationId;
+ if (long.TryParse(message.invocationId, out invocationId))
+ {
+ Action callback;
+ if (this.invocations.TryGetValue(invocationId, out callback) && callback != null)
+ {
+ try
+ {
+ callback(message);
+ }
+ catch (Exception ex)
+ {
+ HTTPManager.Logger.Exception("HubConnection", "OnMessages - StreamItem - callback", ex);
+ }
+ }
+ }
+ break;
+ }
+
+ case MessageTypes.Completion:
+ {
+ long invocationId;
+ if (long.TryParse(message.invocationId, out invocationId))
+ {
+ Action callback;
+ if (this.invocations.TryGetValue(invocationId, out callback) && callback != null)
+ {
+ try
+ {
+ callback(message);
+ }
+ catch (Exception ex)
+ {
+ HTTPManager.Logger.Exception("HubConnection", "OnMessages - Completion - callback", ex);
+ }
+ }
+ this.invocations.Remove(invocationId);
+ }
+ break;
+ }
+
+ case MessageTypes.Close:
+ SetState(ConnectionStates.Closed, message.error);
+ break;
+ }
+ }
+ }
+
+ private void Transport_OnStateChanged(TransportStates oldState, TransportStates newState)
+ {
+ HTTPManager.Logger.Verbose("HubConnection", string.Format("Transport_OnStateChanged - oldState: {0} newState: {1}", oldState.ToString(), newState.ToString()));
+
+ switch (newState)
+ {
+ case TransportStates.Connected:
+ SetState(ConnectionStates.Connected);
+ break;
+
+ case TransportStates.Failed:
+ SetState(ConnectionStates.Closed, this.Transport.ErrorReason);
+ break;
+
+ case TransportStates.Closed:
+ SetState(ConnectionStates.Closed);
+ break;
+ }
+ }
+
+ private void SetState(ConnectionStates state, string errorReason = null)
+ {
+ if (string.IsNullOrEmpty(errorReason))
+ HTTPManager.Logger.Information("HubConnection", "SetState - from State: '" + this.State.ToString() + "' to State: '" + state.ToString() + "'");
+ else
+ HTTPManager.Logger.Information("HubConnection", "SetState - from State: '" + this.State.ToString() + "' to State: '" + state.ToString() + "' errorReason: '" + errorReason + "'");
+
+ if (this.State == state)
+ return;
+
+ this.State = state;
+
+ switch (state)
+ {
+ case ConnectionStates.Initial:
+ case ConnectionStates.Authenticating:
+ case ConnectionStates.Negotiating:
+ case ConnectionStates.CloseInitiated:
+ break;
+
+ case ConnectionStates.Connected:
+ try
+ {
+ if (this.OnConnected != null)
+ this.OnConnected(this);
+ }
+ catch(Exception ex)
+ {
+ HTTPManager.Logger.Exception("HubConnection", "Exception in OnConnected user code!", ex);
+ }
+
+ HTTPManager.Heartbeats.Subscribe(this);
+ this.lastMessageSent = DateTime.UtcNow;
+ break;
+
+ case ConnectionStates.Closed:
+ if (string.IsNullOrEmpty(errorReason))
+ {
+ if (this.OnClosed != null)
+ {
+ try
+ {
+ this.OnClosed(this);
+ }
+ catch(Exception ex)
+ {
+ HTTPManager.Logger.Exception("HubConnection", "Exception in OnClosed user code!", ex);
+ }
+ }
+ }
+ else
+ {
+ if (this.OnError != null)
+ {
+ try
+ {
+ this.OnError(this, errorReason);
+ }
+ catch(Exception ex)
+ {
+ HTTPManager.Logger.Exception("HubConnection", "Exception in OnError user code!", ex);
+ }
+ }
+ }
+ HTTPManager.Heartbeats.Unsubscribe(this);
+ break;
+ }
+ }
+
+ void BestHTTP.Extensions.IHeartbeat.OnHeartbeatUpdate(TimeSpan dif)
+ {
+ switch (this.State)
+ {
+ case ConnectionStates.Connected:
+ if (this.Options.PingInterval != TimeSpan.Zero && DateTime.UtcNow - this.lastMessageSent >= this.Options.PingInterval)
+ SendMessage(new Message() { type = MessageTypes.Ping });
+ break;
+ }
+ }
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/HubConnection.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/HubConnection.cs.meta
new file mode 100644
index 00000000..af016096
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/HubConnection.cs.meta
@@ -0,0 +1,13 @@
+fileFormatVersion: 2
+guid: e8abbf851f5c2224380d8755c487b006
+timeCreated: 1515237548
+licenseType: Store
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/IAuthenticationProvider.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/IAuthenticationProvider.cs
new file mode 100644
index 00000000..ce770d68
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/IAuthenticationProvider.cs
@@ -0,0 +1,44 @@
+#if !BESTHTTP_DISABLE_SIGNALR_CORE && !BESTHTTP_DISABLE_WEBSOCKET
+
+using System;
+
+namespace BestHTTP.SignalRCore
+{
+ public delegate void OnAuthenticationSuccededDelegate(IAuthenticationProvider provider);
+ public delegate void OnAuthenticationFailedDelegate(IAuthenticationProvider provider, string reason);
+
+ public interface IAuthenticationProvider
+ {
+ ///
+ /// The authentication must be run before any request made to build up the SignalR protocol
+ ///
+ bool IsPreAuthRequired { get; }
+
+ ///
+ /// This event must be called when the pre-authentication succeded. When IsPreAuthRequired is false, no-one will subscribe to this event.
+ ///
+ event OnAuthenticationSuccededDelegate OnAuthenticationSucceded;
+
+ ///
+ /// This event must be called when the pre-authentication failed. When IsPreAuthRequired is false, no-one will subscribe to this event.
+ ///
+ event OnAuthenticationFailedDelegate OnAuthenticationFailed;
+
+ ///
+ /// This function called once, when the before the SignalR negotiation begins. If IsPreAuthRequired is false, then this step will be skipped.
+ ///
+ void StartAuthentication();
+
+ ///
+ /// This function will be called for every request before sending it.
+ ///
+ void PrepareRequest(HTTPRequest request);
+
+ ///
+ /// This function can customize the given uri. If there's no intention to modify the uri, this function
+ /// should return with the parameter.
+ ///
+ Uri PrepareUri(Uri uri);
+ }
+}
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/IAuthenticationProvider.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/IAuthenticationProvider.cs.meta
new file mode 100644
index 00000000..fbab001f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/IAuthenticationProvider.cs.meta
@@ -0,0 +1,13 @@
+fileFormatVersion: 2
+guid: d30367ca9f9cbda45ad05e42d66c93cd
+timeCreated: 1515237548
+licenseType: Store
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/JsonProtocol.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/JsonProtocol.cs
new file mode 100644
index 00000000..799e7013
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/JsonProtocol.cs
@@ -0,0 +1,169 @@
+#if !BESTHTTP_DISABLE_SIGNALR_CORE && !BESTHTTP_DISABLE_WEBSOCKET
+
+using BestHTTP.SignalRCore.Messages;
+using System;
+using System.Collections.Generic;
+
+#if NETFX_CORE || NET_4_6
+using System.Reflection;
+#endif
+
+namespace BestHTTP.SignalRCore
+{
+ public interface IProtocol
+ {
+ TransferModes Type { get; }
+ IEncoder Encoder { get; }
+ HubConnection Connection { get; set; }
+
+ ///
+ /// This function must parse textual representation of the messages into the list of Messages.
+ ///
+ void ParseMessages(string data, ref List messages);
+
+ ///
+ /// This function must parse binary representation of the messages into the list of Messages.
+ ///
+ void ParseMessages(byte[] data, ref List messages);
+
+ ///
+ /// This function must return the encoded representation of the given message.
+ ///
+ byte[] EncodeMessage(Message message);
+
+ ///
+ /// This function must convert all element in the arguments array to the corresponding type from the argTypes array.
+ ///
+ object[] GetRealArguments(Type[] argTypes, object[] arguments);
+
+ ///
+ /// Convert a value to the given type.
+ ///
+ object ConvertTo(Type toType, object obj);
+ }
+
+ public sealed class JsonProtocol : IProtocol
+ {
+ public const char Separator = (char)0x1E;
+
+ public TransferModes Type { get { return TransferModes.Text; } }
+ public IEncoder Encoder { get; private set; }
+ public HubConnection Connection { get; set; }
+
+ public JsonProtocol(IEncoder encoder)
+ {
+ if (encoder == null)
+ throw new ArgumentNullException("encoder");
+ if (encoder.Name != "json")
+ throw new ArgumentException("Encoder must be a json encoder!");
+
+ this.Encoder = encoder;
+ }
+
+ public void ParseMessages(string data, ref List messages)
+ {
+ int from = 0;
+ int separatorIdx = data.IndexOf(JsonProtocol.Separator);
+ if (separatorIdx == -1)
+ throw new Exception("Missing separator!");
+
+ while (separatorIdx != -1)
+ {
+ string sub = data.Substring(from, separatorIdx - from);
+
+ var message = this.Encoder.DecodeAs(sub);
+
+ messages.Add(message);
+
+ from = separatorIdx + 1;
+ separatorIdx = data.IndexOf(JsonProtocol.Separator, from);
+ }
+ }
+
+ public void ParseMessages(byte[] data, ref List messages) { }
+
+ public byte[] EncodeMessage(Message message)
+ {
+ string json = null;
+ switch (message.type)
+ {
+ case MessageTypes.Invocation:
+ case MessageTypes.StreamInvocation:
+ // While message contains all informations already, the spec states that no additional field are allowed in messages
+ // So we are creating 'specialized' messages here to send to the server.
+ json = this.Encoder.EncodeAsText(new InvocationMessage()
+ {
+ type = message.type,
+ invocationId = message.invocationId,
+ nonblocking = message.nonblocking,
+ target = message.target,
+ arguments = message.arguments
+ });
+ break;
+
+ case MessageTypes.CancelInvocation:
+ json = this.Encoder.EncodeAsText(new CancelInvocationMessage()
+ {
+ invocationId = message.invocationId
+ });
+ break;
+
+ case MessageTypes.Ping:
+ json = this.Encoder.EncodeAsText(new PingMessage());
+ break;
+ }
+
+ return !string.IsNullOrEmpty(json) ? JsonProtocol.WithSeparator(json) : null;
+ }
+
+ public object[] GetRealArguments(Type[] argTypes, object[] arguments)
+ {
+ if (arguments == null || arguments.Length == 0)
+ return null;
+
+ if (argTypes.Length > arguments.Length)
+ throw new Exception(string.Format("argType.Length({0}) < arguments.length({1})", argTypes.Length, arguments.Length));
+
+ object[] realArgs = new object[arguments.Length];
+
+ for (int i = 0; i < arguments.Length; ++i)
+ realArgs[i] = ConvertTo(argTypes[i], arguments[i]);
+
+ return realArgs;
+ }
+
+ public object ConvertTo(Type toType, object obj)
+ {
+ if (obj == null)
+ return null;
+#if NETFX_CORE //|| NET_4_6
+ if (toType.GetTypeInfo().IsPrimitive || toType.GetTypeInfo().IsEnum)
+#else
+ if (toType.IsPrimitive || toType.IsEnum)
+#endif
+ return Convert.ChangeType(obj, toType);
+
+ if (toType == typeof(string))
+ return obj.ToString();
+
+ return this.Encoder.ConvertTo(toType, obj);
+ }
+
+ ///
+ /// Returns the given string parameter's bytes with the added separator(0x1E).
+ ///
+ public static byte[] WithSeparator(string str)
+ {
+ int len = System.Text.Encoding.UTF8.GetByteCount(str);
+
+ byte[] buffer = new byte[len + 1];
+
+ System.Text.Encoding.UTF8.GetBytes(str, 0, str.Length, buffer, 0);
+
+ buffer[len] = 0x1e;
+
+ return buffer;
+ }
+ }
+}
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/JsonProtocol.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/JsonProtocol.cs.meta
new file mode 100644
index 00000000..f9ca713d
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/JsonProtocol.cs.meta
@@ -0,0 +1,13 @@
+fileFormatVersion: 2
+guid: b98779f03b6433e4387c86a676d50027
+timeCreated: 1515237548
+licenseType: Store
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Messages.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Messages.meta
new file mode 100644
index 00000000..9f91ecde
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Messages.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: 04849aa46f6e586469d9275d70387fb0
+folderAsset: yes
+timeCreated: 1515237542
+licenseType: Store
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Messages/Invocation.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Messages/Invocation.cs
new file mode 100644
index 00000000..e9fecd03
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Messages/Invocation.cs
@@ -0,0 +1,26 @@
+#if !BESTHTTP_DISABLE_SIGNALR_CORE && !BESTHTTP_DISABLE_WEBSOCKET
+using System;
+
+namespace BestHTTP.SignalRCore.Messages
+{
+ public struct InvocationMessage
+ {
+ public MessageTypes type;
+ public string invocationId;
+ public bool nonblocking;
+ public string target;
+ public object[] arguments;
+ }
+
+ public struct CancelInvocationMessage
+ {
+ public MessageTypes type { get { return MessageTypes.CancelInvocation; } }
+ public string invocationId;
+ }
+
+ public struct PingMessage
+ {
+ public MessageTypes type { get { return MessageTypes.Ping; } }
+ }
+}
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Messages/Invocation.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Messages/Invocation.cs.meta
new file mode 100644
index 00000000..b05e69c0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Messages/Invocation.cs.meta
@@ -0,0 +1,13 @@
+fileFormatVersion: 2
+guid: 80d549225d0ced34c864973a497e97bc
+timeCreated: 1515237548
+licenseType: Store
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Messages/Message.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Messages/Message.cs
new file mode 100644
index 00000000..954d091f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Messages/Message.cs
@@ -0,0 +1,84 @@
+#if !BESTHTTP_DISABLE_SIGNALR_CORE && !BESTHTTP_DISABLE_WEBSOCKET
+using System;
+
+namespace BestHTTP.SignalRCore.Messages
+{
+ public enum MessageTypes : int
+ {
+ ///
+ /// This is a made up message type, for easier handshake handling.
+ ///
+ Handshake = 0,
+
+ ///
+ /// https://github.com/aspnet/SignalR/blob/dev/specs/HubProtocol.md#invocation-message-encoding
+ ///
+ Invocation = 1,
+
+ ///
+ /// https://github.com/aspnet/SignalR/blob/dev/specs/HubProtocol.md#streamitem-message-encoding
+ ///
+ StreamItem = 2,
+
+ ///
+ /// https://github.com/aspnet/SignalR/blob/dev/specs/HubProtocol.md#completion-message-encoding
+ ///
+ Completion = 3,
+
+ ///
+ /// https://github.com/aspnet/SignalR/blob/dev/specs/HubProtocol.md#streaminvocation-message-encoding
+ ///
+ StreamInvocation = 4,
+
+ ///
+ /// https://github.com/aspnet/SignalR/blob/dev/specs/HubProtocol.md#cancelinvocation-message-encoding
+ ///
+ CancelInvocation = 5,
+
+ ///
+ /// https://github.com/aspnet/SignalR/blob/dev/specs/HubProtocol.md#ping-message-encoding
+ ///
+ Ping = 6,
+
+ ///
+ /// https://github.com/aspnet/SignalR/blob/dev/specs/HubProtocol.md#close-message-encoding
+ ///
+ Close = 7
+ }
+
+ public struct Message
+ {
+ public MessageTypes type;
+ public string invocationId;
+ public bool nonblocking;
+ public string target;
+ public object[] arguments;
+ public object item;
+ public object result;
+ public string error;
+
+ public override string ToString()
+ {
+ switch (this.type)
+ {
+ case MessageTypes.Invocation:
+ return string.Format("[Invocation Id: {0}, Target: '{1}', Argument count: {2}]", this.invocationId, this.target, this.arguments != null ? this.arguments.Length : 0);
+ case MessageTypes.StreamItem:
+ return string.Format("[StreamItem Id: {0}, Item: {1}]", this.invocationId, this.item.ToString());
+ case MessageTypes.Completion:
+ return string.Format("[Completion Id: {0}, Result: {1}, Error: '{2}']", this.invocationId, this.result, this.error);
+ case MessageTypes.StreamInvocation:
+ return string.Format("[StreamInvocation Id: {0}, Target: '{1}', Argument count: {2}]", this.invocationId, this.target, this.arguments != null ? this.arguments.Length : 0);
+ case MessageTypes.CancelInvocation:
+ return string.Format("[CancelInvocation Id: {0}]", this.invocationId);
+ case MessageTypes.Ping:
+ return "[Ping]";
+ case MessageTypes.Close:
+ return string.IsNullOrEmpty(this.error) ? "[Close]" : string.Format("[Close {0}]", this.error);
+ default:
+ return "Unknown message! Type: " + this.type;
+ }
+ }
+ }
+}
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Messages/Message.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Messages/Message.cs.meta
new file mode 100644
index 00000000..566711ca
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Messages/Message.cs.meta
@@ -0,0 +1,13 @@
+fileFormatVersion: 2
+guid: f6a7c57303e62774fb902547acce515a
+timeCreated: 1515237548
+licenseType: Store
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Messages/NegotiationResult.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Messages/NegotiationResult.cs
new file mode 100644
index 00000000..4897e056
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Messages/NegotiationResult.cs
@@ -0,0 +1,142 @@
+using System;
+using System.Collections.Generic;
+
+namespace BestHTTP.SignalRCore.Messages
+{
+ public sealed class SupportedTransport
+ {
+ ///
+ /// Name of the transport.
+ ///
+ public string Name { get; private set; }
+
+ ///
+ /// Supported transfer formats of the transport.
+ ///
+ public List SupportedFormats { get; private set; }
+
+ internal SupportedTransport(string transportName, List transferFormats)
+ {
+ this.Name = transportName;
+ this.SupportedFormats = transferFormats;
+ }
+ }
+
+ ///
+ /// Negotiation result of the /negotiation request.
+ ///
+ ///
+ public sealed class NegotiationResult
+ {
+ ///
+ /// The connectionId which is required by the Long Polling and Server-Sent Events transports (in order to correlate sends and receives).
+ ///
+ public string ConnectionId { get; private set; }
+
+ ///
+ /// The availableTransports list which describes the transports the server supports. For each transport, the name of the transport (transport) is listed, as is a list of "transfer formats" supported by the transport (transferFormats)
+ ///
+ public List SupportedTransports { get; private set; }
+
+ ///
+ /// The url which is the URL the client should connect to.
+ ///
+ public Uri Url { get; private set; }
+
+ ///
+ /// The accessToken which is an optional bearer token for accessing the specified url.
+ ///
+ public string AccessToken { get; private set; }
+
+ internal static NegotiationResult Parse(string json, out string error, HubConnection hub)
+ {
+ error = null;
+
+ Dictionary response = BestHTTP.JSON.Json.Decode(json) as Dictionary;
+ if (response == null)
+ {
+ error = "Json decoding failed!";
+ return null;
+ }
+
+ try
+ {
+ NegotiationResult result = new NegotiationResult();
+ object value;
+ if (response.TryGetValue("connectionId", out value))
+ result.ConnectionId = value.ToString();
+
+ if (response.TryGetValue("availableTransports", out value))
+ {
+ List transports = value as List;
+ if (transports != null)
+ {
+ List supportedTransports = new List(transports.Count);
+
+ foreach (Dictionary transport in transports)
+ {
+ string transportName = string.Empty;
+ List transferModes = null;
+
+ if (transport.TryGetValue("transport", out value))
+ transportName = value.ToString();
+
+ if (transport.TryGetValue("transferFormats", out value))
+ {
+ List transferFormats = value as List;
+
+ if (transferFormats != null)
+ {
+ transferModes = new List(transferFormats.Count);
+ foreach (var mode in transferFormats)
+ transferModes.Add(mode.ToString());
+ }
+ }
+
+ supportedTransports.Add(new SupportedTransport(transportName, transferModes));
+ }
+
+ result.SupportedTransports = supportedTransports;
+ }
+ }
+
+ if (response.TryGetValue("url", out value))
+ {
+ string uriStr = value.ToString();
+
+ Uri redirectUri;
+
+ // Here we will try to parse the received url. If TryCreate fails, we will throw an exception
+ // as it should be able to successfully parse whole (absolute) urls (like "https://server:url/path")
+ // and relative ones (like "/path").
+ if (!Uri.TryCreate(uriStr, UriKind.RelativeOrAbsolute, out redirectUri))
+ throw new Exception(string.Format("Couldn't parse url: '{0}'", uriStr));
+
+ // If received a relative url we will use the hub's current url to append the new path to it.
+ if (!redirectUri.IsAbsoluteUri)
+ {
+ Uri oldUri = hub.Uri;
+ var builder = new UriBuilder(oldUri);
+ builder.Path = uriStr;
+
+ redirectUri = builder.Uri;
+ }
+
+ result.Url = redirectUri;
+ }
+
+ if (response.TryGetValue("accessToken", out value))
+ result.AccessToken = value.ToString();
+ else if (hub.NegotiationResult != null)
+ result.AccessToken = hub.NegotiationResult.AccessToken;
+
+ return result;
+ }
+ catch (Exception ex)
+ {
+ error = "Error while parsing result: " + ex.Message + " StackTrace: " + ex.StackTrace;
+ return null;
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Messages/NegotiationResult.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Messages/NegotiationResult.cs.meta
new file mode 100644
index 00000000..46097767
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Messages/NegotiationResult.cs.meta
@@ -0,0 +1,12 @@
+fileFormatVersion: 2
+guid: ff02294dfc0839f4b8cfa92dce810808
+timeCreated: 1528093299
+licenseType: Store
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Transports.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Transports.meta
new file mode 100644
index 00000000..7e926363
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Transports.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: 93299fbc9d294004caa37d06aea06bb5
+folderAsset: yes
+timeCreated: 1515237543
+licenseType: Store
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Transports/WebsocketTransport.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Transports/WebsocketTransport.cs
new file mode 100644
index 00000000..2c59d3a7
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Transports/WebsocketTransport.cs
@@ -0,0 +1,247 @@
+#if !BESTHTTP_DISABLE_SIGNALR_CORE && !BESTHTTP_DISABLE_WEBSOCKET
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+using BestHTTP.SignalRCore.Messages;
+
+namespace BestHTTP.SignalRCore.Transports
+{
+ ///
+ /// WebSockets transport implementation.
+ /// https://github.com/aspnet/SignalR/blob/dev/specs/TransportProtocols.md#websockets-full-duplex
+ ///
+ internal sealed class WebSocketTransport : ITransport
+ {
+ public TransportTypes TransportType { get { return TransportTypes.WebSocket; } }
+ public TransferModes TransferMode { get { return TransferModes.Binary; } }
+
+ ///
+ /// Current state of the transport. All changes will be propagated to the HubConnection through the onstateChanged event.
+ ///
+ public TransportStates State {
+ get { return this._state; }
+ private set
+ {
+ if (this._state != value)
+ {
+ TransportStates oldState = this._state;
+ this._state = value;
+
+ if (this.OnStateChanged != null)
+ this.OnStateChanged(oldState, this._state);
+ }
+ }
+ }
+ private TransportStates _state;
+
+ ///
+ /// This will store the reason of failures so HubConnection can include it in its OnError event.
+ ///
+ public string ErrorReason { get; private set; }
+
+ ///
+ /// Called every time when the transport's changed.
+ ///
+ public event Action OnStateChanged;
+
+ private WebSocket.WebSocket webSocket;
+ private HubConnection connection;
+
+ ///
+ /// Cached list of parsed messages.
+ ///
+ private List messages = new List();
+
+ public WebSocketTransport(HubConnection con)
+ {
+ this.connection = con;
+ this.State = TransportStates.Initial;
+ }
+
+ void ITransport.StartConnect()
+ {
+ HTTPManager.Logger.Verbose("WebSocketTransport", "StartConnect");
+
+ if (this.webSocket == null)
+ {
+ Uri uri = BuildUri(this.connection.Uri);
+
+ // Also, if there's an authentication provider it can alter further our uri.
+ if (this.connection.AuthenticationProvider != null)
+ uri = this.connection.AuthenticationProvider.PrepareUri(uri) ?? uri;
+
+ HTTPManager.Logger.Verbose("WebSocketTransport", "StartConnect connecting to Uri: " + uri.ToString());
+
+ this.webSocket = new WebSocket.WebSocket(uri);
+ }
+
+#if !UNITY_WEBGL || UNITY_EDITOR
+ // prepare the internal http request
+ if (this.connection.AuthenticationProvider != null)
+ this.connection.AuthenticationProvider.PrepareRequest(webSocket.InternalRequest);
+#endif
+ this.webSocket.OnOpen += OnOpen;
+ this.webSocket.OnMessage += OnMessage;
+ this.webSocket.OnBinary += OnBinary;
+ this.webSocket.OnErrorDesc += OnError;
+ this.webSocket.OnClosed += OnClosed;
+
+ this.webSocket.Open();
+
+ this.State = TransportStates.Connecting;
+ }
+
+ void ITransport.Send(byte[] msg)
+ {
+ // To help debugging, in the editor when the plugin's loggging level is set to All, we will
+ // send all messages in textual form. This will help the readability when sent through a proxy.
+#if UNITY_EDITOR
+ if (HTTPManager.Logger.Level == Logger.Loglevels.All)
+ this.webSocket.Send(System.Text.Encoding.UTF8.GetString(msg, 0, msg.Length));
+ else
+#endif
+ this.webSocket.Send(msg);
+ }
+
+ // The websocket connection is open
+ private void OnOpen(WebSocket.WebSocket webSocket)
+ {
+ HTTPManager.Logger.Verbose("WebSocketTransport", "OnOpen");
+
+ // https://github.com/aspnet/SignalR/blob/dev/specs/HubProtocol.md#overview
+ // When our websocket connection is open, send the 'negotiation' message to the server.
+
+ string json = string.Format("{{'protocol':'{0}', 'version': 1}}", this.connection.Protocol.Encoder.Name);
+
+ byte[] buffer = JsonProtocol.WithSeparator(json);
+
+ (this as ITransport).Send(buffer);
+ }
+
+ private string ParseHandshakeResponse(string data)
+ {
+ // The handshake response is
+ // -an empty json object ('{}') if the handshake process is succesfull
+ // -otherwise it has one 'error' field
+
+ Dictionary response = BestHTTP.JSON.Json.Decode(data) as Dictionary;
+
+ if (response == null)
+ return "Couldn't parse json data: " + data;
+
+ object error;
+ if (response.TryGetValue("error", out error))
+ return error.ToString();
+
+ return null;
+ }
+
+ private void HandleHandshakeResponse(string data)
+ {
+ this.ErrorReason = ParseHandshakeResponse(data);
+
+ this.State = string.IsNullOrEmpty(this.ErrorReason) ? TransportStates.Connected : TransportStates.Failed;
+ }
+
+ private void OnMessage(WebSocket.WebSocket webSocket, string data)
+ {
+ if (this.State == TransportStates.Connecting)
+ {
+ HandleHandshakeResponse(data);
+
+ return;
+ }
+
+ this.messages.Clear();
+ try
+ {
+ this.connection.Protocol.ParseMessages(data, ref this.messages);
+
+ this.connection.OnMessages(this.messages);
+ }
+ catch (Exception ex)
+ {
+ HTTPManager.Logger.Exception("WebSocketTransport", "OnMessage(string)", ex);
+ }
+ finally
+ {
+ this.messages.Clear();
+ }
+ }
+
+ private void OnBinary(WebSocket.WebSocket webSocket, byte[] data)
+ {
+ if (this.State == TransportStates.Connecting)
+ {
+ HandleHandshakeResponse(System.Text.Encoding.UTF8.GetString(data, 0, data.Length));
+
+ return;
+ }
+
+ this.messages.Clear();
+ try
+ {
+ this.connection.Protocol.ParseMessages(data, ref this.messages);
+
+ this.connection.OnMessages(this.messages);
+ }
+ catch (Exception ex)
+ {
+ HTTPManager.Logger.Exception("WebSocketTransport", "OnMessage(byte[])", ex);
+ }
+ finally
+ {
+ this.messages.Clear();
+ }
+ }
+
+ private void OnError(WebSocket.WebSocket webSocket, string reason)
+ {
+ HTTPManager.Logger.Verbose("WebSocketTransport", "OnError: " + reason);
+
+ this.ErrorReason = reason;
+ this.State = TransportStates.Failed;
+ }
+
+ private void OnClosed(WebSocket.WebSocket webSocket, ushort code, string message)
+ {
+ HTTPManager.Logger.Verbose("WebSocketTransport", "OnClosed: " + code + " " + message);
+
+ this.webSocket = null;
+
+ this.State = TransportStates.Closed;
+ }
+
+ void ITransport.StartClose()
+ {
+ HTTPManager.Logger.Verbose("WebSocketTransport", "StartClose");
+
+ if (this.webSocket != null)
+ {
+ this.State = TransportStates.Closing;
+ this.webSocket.Close();
+ }
+ else
+ this.State = TransportStates.Closed;
+ }
+
+ private Uri BuildUri(Uri baseUri)
+ {
+ if (this.connection.NegotiationResult == null)
+ return baseUri;
+
+ UriBuilder builder = new UriBuilder(baseUri);
+ StringBuilder queryBuilder = new StringBuilder();
+
+ queryBuilder.Append(baseUri.Query);
+ if (!string.IsNullOrEmpty(this.connection.NegotiationResult.ConnectionId))
+ queryBuilder.Append("&id=").Append(this.connection.NegotiationResult.ConnectionId);
+
+ builder.Query = queryBuilder.ToString();
+
+ return builder.Uri;
+ }
+ }
+}
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Transports/WebsocketTransport.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Transports/WebsocketTransport.cs.meta
new file mode 100644
index 00000000..7489628b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SignalRCore/Transports/WebsocketTransport.cs.meta
@@ -0,0 +1,13 @@
+fileFormatVersion: 2
+guid: e89b403b974cebf40845e9ca6616a0e0
+timeCreated: 1515237548
+licenseType: Store
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO.meta
new file mode 100644
index 00000000..563bd54f
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 70d2cd72d4442e349a1cfa407bbcfe8d
+folderAsset: yes
+DefaultImporter:
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Enums.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Enums.cs
new file mode 100644
index 00000000..dbc350f5
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Enums.cs
@@ -0,0 +1,105 @@
+#if !BESTHTTP_DISABLE_SOCKETIO
+
+namespace BestHTTP.SocketIO
+{
+ ///
+ /// Possible event types on the transport level.
+ ///
+ public enum TransportEventTypes : int
+ {
+ Unknown = -1,
+ Open = 0,
+ Close = 1,
+ Ping = 2,
+ Pong = 3,
+ Message = 4,
+ Upgrade = 5,
+ Noop = 6
+ }
+
+ ///
+ /// Event types of the SocketIO protocol.
+ ///
+ public enum SocketIOEventTypes : int
+ {
+ Unknown = -1,
+
+ ///
+ /// Connect to a namespace, or we connected to a namespace
+ ///
+ Connect = 0,
+
+ ///
+ /// Disconnect a namespace, or we disconnected from a namespace.
+ ///
+ Disconnect = 1,
+
+ ///
+ /// A general event. The event's name is in the payload.
+ ///
+ Event = 2,
+
+ ///
+ /// Acknowledgment of an event.
+ ///
+ Ack = 3,
+
+ ///
+ /// Error sent by the server, or by the plugin
+ ///
+ Error = 4,
+
+ ///
+ /// A general event with binary attached to the packet. The event's name is in the payload.
+ ///
+ BinaryEvent = 5,
+
+ ///
+ /// Acknowledgment of a binary event.
+ ///
+ BinaryAck = 6
+ }
+
+ ///
+ /// Possible error codes that the SocketIO server can send.
+ ///
+ public enum SocketIOErrors
+ {
+ ///
+ /// Transport unknown
+ ///
+ UnknownTransport = 0,
+
+ ///
+ /// Session ID unknown
+ ///
+ UnknownSid = 1,
+
+ ///
+ /// Bad handshake method
+ ///
+ BadHandshakeMethod = 2,
+
+ ///
+ /// Bad request
+ ///
+ BadRequest = 3,
+
+ ///
+ /// Plugin internal error!
+ ///
+ Internal,
+
+ ///
+ /// Exceptions that caught by the plugin but raised in a user code.
+ ///
+ User,
+
+ ///
+ /// A custom, server sent error, most probably from a Socket.IO middleware.
+ ///
+ Custom,
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Enums.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Enums.cs.meta
new file mode 100644
index 00000000..88ef434b
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Enums.cs.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: 94f15ba2f99e9e148869183ae648e7e6
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Error.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Error.cs
new file mode 100644
index 00000000..6f4fc606
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Error.cs
@@ -0,0 +1,23 @@
+#if !BESTHTTP_DISABLE_SOCKETIO
+
+namespace BestHTTP.SocketIO
+{
+ public sealed class Error
+ {
+ public SocketIOErrors Code { get; private set; }
+ public string Message { get; private set; }
+
+ public Error(SocketIOErrors code, string msg)
+ {
+ this.Code = code;
+ this.Message = msg;
+ }
+
+ public override string ToString()
+ {
+ return string.Format("Code: {0} Message: \"{1}\"", this.Code.ToString(), this.Message);
+ }
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Error.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Error.cs.meta
new file mode 100644
index 00000000..56563548
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Error.cs.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: bede350068da4b74b9cc566b9bff3bdd
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Events.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Events.meta
new file mode 100644
index 00000000..125739a9
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Events.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 97e9578ca337d0f42a4145ade32a3a5c
+folderAsset: yes
+DefaultImporter:
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Events/EventDescriptor.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Events/EventDescriptor.cs
new file mode 100644
index 00000000..13e177c6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Events/EventDescriptor.cs
@@ -0,0 +1,97 @@
+#if !BESTHTTP_DISABLE_SOCKETIO
+
+using System;
+using System.Collections.Generic;
+
+namespace BestHTTP.SocketIO.Events
+{
+ public delegate void SocketIOCallback(Socket socket, Packet packet, params object[] args);
+ public delegate void SocketIOAckCallback(Socket socket, Packet packet, params object[] args);
+
+ ///
+ /// A class to describe an event, and its metadatas.
+ ///
+ internal sealed class EventDescriptor
+ {
+ #region Public Properties
+
+ ///
+ /// List of callback delegates.
+ ///
+ public List Callbacks { get; private set; }
+
+ ///
+ /// If this property is true, callbacks are removed automatically after the event dispatch.
+ ///
+ public bool OnlyOnce { get; private set; }
+
+ ///
+ /// If this property is true, the dispatching packet's Payload will be decoded using the Manager's Encoder.
+ ///
+ public bool AutoDecodePayload { get; private set; }
+
+ #endregion
+
+ ///
+ /// Cache an array on a hot-path.
+ ///
+ private SocketIOCallback[] CallbackArray;
+
+ ///
+ /// Constructor to create an EventDescriptor instance and set the meta-datas.
+ ///
+ public EventDescriptor(bool onlyOnce, bool autoDecodePayload, SocketIOCallback callback)
+ {
+ this.OnlyOnce = onlyOnce;
+ this.AutoDecodePayload = autoDecodePayload;
+ this.Callbacks = new List(1);
+
+ if (callback != null)
+ Callbacks.Add(callback);
+ }
+
+ ///
+ /// Will call the callback delegates with the given parameters and remove the callbacks if this descriptor marked with a true OnlyOnce property.
+ ///
+ public void Call(Socket socket, Packet packet, params object[] args)
+ {
+ int callbackCount = Callbacks.Count;
+ if (CallbackArray == null || CallbackArray.Length < callbackCount)
+ Array.Resize(ref CallbackArray, callbackCount);
+
+ // Copy the callback delegates to an array, because in one of the callbacks we can modify the list(by calling On/Once/Off in an event handler)
+ // This way we can prevent some strange bug
+ Callbacks.CopyTo(CallbackArray);
+
+ // Go through the delegates and call them
+ for (int i = 0; i < callbackCount; ++i)
+ {
+ try
+ {
+ // Call the delegate.
+ SocketIOCallback callback = CallbackArray[i];
+ if (callback!= null)
+ callback(socket, packet, args);
+ }
+ catch (Exception ex)
+ {
+ // Do not try to emit a new Error when we already tried to deliver an Error, possible causing a
+ // stack overflow
+ if (args == null || args.Length == 0 || !(args[0] is Error))
+ (socket as ISocket).EmitError(SocketIOErrors.User, ex.Message + " " + ex.StackTrace);
+
+ HTTPManager.Logger.Exception("EventDescriptor", "Call", ex);
+ }
+
+ // If these callbacks has to be called only once, remove them from the main list
+ if (this.OnlyOnce)
+ Callbacks.Remove(CallbackArray[i]);
+
+ // Don't keep any reference avoiding memory leaks
+ CallbackArray[i] = null;
+ }
+ }
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Events/EventDescriptor.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Events/EventDescriptor.cs.meta
new file mode 100644
index 00000000..40d24c3a
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Events/EventDescriptor.cs.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: ab942858f5ff2a4458ec312bc2955779
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Events/EventNames.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Events/EventNames.cs
new file mode 100644
index 00000000..7e420349
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Events/EventNames.cs
@@ -0,0 +1,48 @@
+#if !BESTHTTP_DISABLE_SOCKETIO
+
+using System;
+
+namespace BestHTTP.SocketIO.Events
+{
+ ///
+ /// Helper class to provide functions to an easy Enum->string conversation of the transport and SocketIO evenet types.
+ ///
+ public static class EventNames
+ {
+ public const string Connect = "connect";
+ public const string Disconnect = "disconnect";
+ public const string Event = "event";
+ public const string Ack = "ack";
+ public const string Error = "error";
+ public const string BinaryEvent = "binaryevent";
+ public const string BinaryAck = "binaryack";
+
+ private static string[] SocketIONames = new string[] { "unknown", "connect", "disconnect", "event", "ack", "error", "binaryevent", "binaryack" };
+ private static string[] TransportNames = new string[] { "unknown", "open", "close", "ping", "pong", "message", "upgrade", "noop" };
+ private static string[] BlacklistedEvents = new string[] { "connect", "connect_error", "connect_timeout", "disconnect", "error", "reconnect",
+ "reconnect_attempt", "reconnect_failed", "reconnect_error", "reconnecting" };
+
+ public static string GetNameFor(SocketIOEventTypes type)
+ {
+ return SocketIONames[(int)type + 1];
+ }
+
+ public static string GetNameFor(TransportEventTypes transEvent)
+ {
+ return TransportNames[(int)transEvent + 1];
+ }
+
+ ///
+ /// Checks an event name whether it's blacklisted or not.
+ ///
+ public static bool IsBlacklisted(string eventName)
+ {
+ for (int i = 0; i < BlacklistedEvents.Length; ++i)
+ if (string.Compare(BlacklistedEvents[i], eventName, StringComparison.OrdinalIgnoreCase) == 0)
+ return true;
+ return false;
+ }
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Events/EventNames.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Events/EventNames.cs.meta
new file mode 100644
index 00000000..68ed6494
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Events/EventNames.cs.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: 3ab78cfee54d71543bec1cdef098cd4b
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Events/EventTable.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Events/EventTable.cs
new file mode 100644
index 00000000..37f94326
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Events/EventTable.cs
@@ -0,0 +1,154 @@
+#if !BESTHTTP_DISABLE_SOCKETIO
+
+using System.Collections.Generic;
+
+namespace BestHTTP.SocketIO.Events
+{
+ ///
+ /// This class helps keep track and maintain EventDescriptor instances and dispatching packets to the right delegates.
+ ///
+ internal sealed class EventTable
+ {
+ #region Privates
+
+ ///
+ /// The Socket that this EventTable is bound to.
+ ///
+ private Socket Socket { get; set; }
+
+ ///
+ /// The 'EventName -> List of events' mapping.
+ ///
+ private Dictionary> Table = new Dictionary>();
+
+ #endregion
+
+ ///
+ /// Constructor to create an instance and bind it to a socket.
+ ///
+ public EventTable(Socket socket)
+ {
+ this.Socket = socket;
+ }
+
+ ///
+ /// Register a callback to a name with the given metadata.
+ ///
+ public void Register(string eventName, SocketIOCallback callback, bool onlyOnce, bool autoDecodePayload)
+ {
+ List events;
+ if (!Table.TryGetValue(eventName, out events))
+ Table.Add(eventName, events = new List(1));
+
+ // Find a matching desriptor
+ var desc = events.Find((d) => d.OnlyOnce == onlyOnce && d.AutoDecodePayload == autoDecodePayload);
+
+ // If not found, create one
+ if (desc == null)
+ events.Add(new EventDescriptor(onlyOnce, autoDecodePayload, callback));
+ else // if found, add the new callback
+ desc.Callbacks.Add(callback);
+ }
+
+ ///
+ /// Removes all events that registered for the given name.
+ ///
+ public void Unregister(string eventName)
+ {
+ Table.Remove(eventName);
+ }
+
+ ///
+ ///
+ ///
+ public void Unregister(string eventName, SocketIOCallback callback)
+ {
+ List events;
+ if (Table.TryGetValue(eventName, out events))
+ for (int i = 0; i < events.Count; ++i)
+ events[i].Callbacks.Remove(callback);
+ }
+
+ ///
+ /// Will call the delegates that associated to the given eventName.
+ ///
+ public void Call(string eventName, Packet packet, params object[] args)
+ {
+ if (HTTPManager.Logger.Level <= BestHTTP.Logger.Loglevels.All)
+ HTTPManager.Logger.Verbose("EventTable", "Call - " + eventName);
+
+ List events;
+
+ if (Table.TryGetValue(eventName, out events))
+ for (int i = 0; i < events.Count; ++i)
+ events[i].Call(Socket, packet, args);
+ }
+
+ ///
+ /// This function will get the eventName from the packet's Payload, and optionally will decode it from Json.
+ ///
+ public void Call(Packet packet)
+ {
+ string eventName = packet.DecodeEventName();
+ string typeName = packet.SocketIOEvent != SocketIOEventTypes.Unknown ? EventNames.GetNameFor(packet.SocketIOEvent) : EventNames.GetNameFor(packet.TransportEvent);
+ object[] args = null;
+
+ if (!HasSubsciber(eventName) && !HasSubsciber(typeName))
+ return;
+
+ // If this is an Event or BinaryEvent message, or we have a subscriber with AutoDecodePayload, then
+ // we have to decode the packet's Payload.
+ if (packet.TransportEvent == TransportEventTypes.Message && (packet.SocketIOEvent == SocketIOEventTypes.Event || packet.SocketIOEvent == SocketIOEventTypes.BinaryEvent) && ShouldDecodePayload(eventName))
+ args = packet.Decode(Socket.Manager.Encoder);
+
+ // call event callbacks registered for 'eventName'
+ if (!string.IsNullOrEmpty(eventName))
+ Call(eventName, packet, args);
+
+ if (!packet.IsDecoded && ShouldDecodePayload(typeName))
+ args = packet.Decode(Socket.Manager.Encoder);
+
+ // call event callbacks registered for 'typeName'
+ if (!string.IsNullOrEmpty(typeName))
+ Call(typeName, packet, args);
+ }
+
+ ///
+ /// Remove all event -> delegate association.
+ ///
+ public void Clear()
+ {
+ Table.Clear();
+ }
+
+ #region Private Helpers
+
+ ///
+ /// Returns true, if for the given event name there are at least one event that needs a decoded
+ ///
+ ///
+ ///
+ private bool ShouldDecodePayload(string eventName)
+ {
+ List events;
+
+ // If we find at least one EventDescriptor with AutoDecodePayload == true, we have to
+ // decode the whole payload
+ if (Table.TryGetValue(eventName, out events))
+ for (int i = 0; i < events.Count; ++i)
+ if (events[i].AutoDecodePayload && events[i].Callbacks.Count > 0)
+ return true;
+
+ return false;
+ }
+
+ private bool HasSubsciber(string eventName)
+ {
+ return Table.ContainsKey(eventName);
+ }
+
+ #endregion
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Events/EventTable.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Events/EventTable.cs.meta
new file mode 100644
index 00000000..6089fc31
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Events/EventTable.cs.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: 62b1e6227e8b13446b06cf83b7ab23e2
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/HandshakeData.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/HandshakeData.cs
new file mode 100644
index 00000000..a05607b0
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/HandshakeData.cs
@@ -0,0 +1,101 @@
+#if !BESTHTTP_DISABLE_SOCKETIO
+
+using System;
+using System.Collections.Generic;
+
+namespace BestHTTP.SocketIO
+{
+ using BestHTTP.JSON;
+
+ ///
+ /// Helper class to parse and hold handshake information.
+ ///
+ public sealed class HandshakeData
+ {
+ #region Public Handshake Data
+
+ ///
+ /// Session ID of this connection.
+ ///
+ public string Sid { get; private set; }
+
+ ///
+ /// List of possible upgrades.
+ ///
+ public List Upgrades { get; private set; }
+
+ ///
+ /// What interval we have to set a ping message.
+ ///
+ public TimeSpan PingInterval { get; private set; }
+
+ ///
+ /// What time have to pass without an answer to our ping request when we can consider the connection disconnected.
+ ///
+ public TimeSpan PingTimeout { get; private set; }
+
+ #endregion
+
+ #region Helper Methods
+
+ public bool Parse(string str)
+ {
+ bool success = false;
+ Dictionary dict = Json.Decode(str, ref success) as Dictionary;
+ if (!success)
+ return false;
+
+ try
+ {
+ this.Sid = GetString(dict, "sid");
+ this.Upgrades = GetStringList(dict, "upgrades");
+ this.PingInterval = TimeSpan.FromMilliseconds(GetInt(dict, "pingInterval"));
+ this.PingTimeout = TimeSpan.FromMilliseconds(GetInt(dict, "pingTimeout"));
+ }
+ catch (Exception ex)
+ {
+ BestHTTP.HTTPManager.Logger.Exception("HandshakeData", "Parse", ex);
+ return false;
+ }
+
+ return true;
+ }
+
+ private static object Get(Dictionary from, string key)
+ {
+ object value;
+ if (!from.TryGetValue(key, out value))
+ throw new System.Exception(string.Format("Can't get {0} from Handshake data!", key));
+ return value;
+ }
+
+ private static string GetString(Dictionary from, string key)
+ {
+ return Get(from, key) as string;
+ }
+
+ private static List GetStringList(Dictionary from, string key)
+ {
+ List value = Get(from, key) as List;
+
+ List result = new List(value.Count);
+ for (int i = 0; i < value.Count; ++i)
+ {
+ string str = value[i] as string;
+ if (str != null)
+ result.Add(str);
+ }
+
+ return result;
+ }
+
+ private static int GetInt(Dictionary from, string key)
+ {
+ return (int)(double)Get(from, key);
+ }
+
+ #endregion
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/HandshakeData.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/HandshakeData.cs.meta
new file mode 100644
index 00000000..9ad5b710
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/HandshakeData.cs.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: 28457ee0deb7f0e4e8477f231304c601
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Interfaces.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Interfaces.cs
new file mode 100644
index 00000000..7e5b1712
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Interfaces.cs
@@ -0,0 +1,40 @@
+#if !BESTHTTP_DISABLE_SOCKETIO
+
+namespace BestHTTP.SocketIO
+{
+ using BestHTTP.SocketIO.Transports;
+
+ ///
+ /// Interface to hide internal functions from the user by implementing it as an explicit interface.
+ ///
+ public interface IManager
+ {
+ void Remove(Socket socket);
+ void Close(bool removeSockets = true);
+ void TryToReconnect();
+ bool OnTransportConnected(ITransport transport);
+ void OnTransportError(ITransport trans, string err);
+ void OnTransportProbed(ITransport trans);
+ void SendPacket(Packet packet);
+ void OnPacket(Packet packet);
+ void EmitEvent(string eventName, params object[] args);
+ void EmitEvent(SocketIOEventTypes type, params object[] args);
+ void EmitError(SocketIOErrors errCode, string msg);
+ void EmitAll(string eventName, params object[] args);
+ }
+
+ ///
+ /// Interface to hide internal functions from the user by implementing it as an explicit interface.
+ ///
+ public interface ISocket
+ {
+ void Open();
+ void Disconnect(bool remove);
+ void OnPacket(Packet packet);
+ void EmitEvent(SocketIOEventTypes type, params object[] args);
+ void EmitEvent(string eventName, params object[] args);
+ void EmitError(SocketIOErrors errCode, string msg);
+ }
+}
+
+#endif
\ No newline at end of file
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Interfaces.cs.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Interfaces.cs.meta
new file mode 100644
index 00000000..d7d93f16
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/Interfaces.cs.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: e37425596e0069c4b99fea0b55dcd4cc
+MonoImporter:
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/JsonEncoders.meta b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/JsonEncoders.meta
new file mode 100644
index 00000000..62ac15d4
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/JsonEncoders.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: ed82682a337846d47b38e6ca7189a0c8
+folderAsset: yes
+DefaultImporter:
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/JsonEncoders/DefaultJSonEncoder.cs b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/JsonEncoders/DefaultJSonEncoder.cs
new file mode 100644
index 00000000..5dee8cf6
--- /dev/null
+++ b/JNFrame/Assets/Plugins/BestHTTP/BestHTTP/SocketIO/JsonEncoders/DefaultJSonEncoder.cs
@@ -0,0 +1,25 @@
+#if !BESTHTTP_DISABLE_SOCKETIO
+
+using System.Collections.Generic;
+using BestHTTP.JSON;
+
+namespace BestHTTP.SocketIO.JsonEncoders
+{
+ ///
+ /// The default IJsonEncoder implementation. It's uses the Json class from the BestHTTP.JSON namespace to encode and decode.
+ ///
+ public sealed class DefaultJSonEncoder : IJsonEncoder
+ {
+ public List Decode(string json)
+ {
+ return Json.Decode(json) as List